diff --git a/closed/openjdk-tag.gmk b/closed/openjdk-tag.gmk index 9006ff95cb2..0cf1f95dd61 100644 --- a/closed/openjdk-tag.gmk +++ b/closed/openjdk-tag.gmk @@ -1 +1 @@ -OPENJDK_TAG := jdk-24+23 +OPENJDK_TAG := jdk-24+24 diff --git a/make/RunTests.gmk b/make/RunTests.gmk index 747d8f84dbc..636d1ed18b2 100644 --- a/make/RunTests.gmk +++ b/make/RunTests.gmk @@ -45,7 +45,7 @@ ifneq ($(TEST_VM_OPTS), ) endif $(eval $(call ParseKeywordVariable, TEST_OPTS, \ - SINGLE_KEYWORDS := JOBS TIMEOUT_FACTOR JCOV JCOV_DIFF_CHANGESET, \ + SINGLE_KEYWORDS := JOBS TIMEOUT_FACTOR JCOV JCOV_DIFF_CHANGESET AOT_JDK, \ STRING_KEYWORDS := VM_OPTIONS JAVA_OPTIONS, \ )) @@ -202,11 +202,12 @@ $(eval $(call SetTestOpt,JOBS,JTREG)) $(eval $(call SetTestOpt,TIMEOUT_FACTOR,JTREG)) $(eval $(call SetTestOpt,FAILURE_HANDLER_TIMEOUT,JTREG)) $(eval $(call SetTestOpt,REPORT,JTREG)) +$(eval $(call SetTestOpt,AOT_JDK,JTREG)) $(eval $(call ParseKeywordVariable, JTREG, \ SINGLE_KEYWORDS := JOBS TIMEOUT_FACTOR FAILURE_HANDLER_TIMEOUT \ TEST_MODE ASSERT VERBOSE RETAIN TEST_THREAD_FACTORY MAX_MEM RUN_PROBLEM_LISTS \ - RETRY_COUNT REPEAT_COUNT MAX_OUTPUT REPORT $(CUSTOM_JTREG_SINGLE_KEYWORDS), \ + RETRY_COUNT REPEAT_COUNT MAX_OUTPUT REPORT AOT_JDK $(CUSTOM_JTREG_SINGLE_KEYWORDS), \ STRING_KEYWORDS := OPTIONS JAVA_OPTIONS VM_OPTIONS KEYWORDS \ EXTRA_PROBLEM_LISTS LAUNCHER_OPTIONS \ $(CUSTOM_JTREG_STRING_KEYWORDS), \ @@ -702,6 +703,58 @@ define SetJtregValue endif endef + +# Parameter 1 is the name of the rule. +# +# Remaining parameters are named arguments. +# VM_OPTIONS List of JVM arguments to use when creating AOT cache +# +# After calling this, the following variables are defined +# $1_AOT_TARGETS List of all targets that the test rule will need to depend on +# $1_AOT_JDK_CACHE The AOT cache file to be used to run the test with +# +SetupAot = $(NamedParamsMacroTemplate) +define SetupAotBody + $1_AOT_JDK_CONF := $$($1_TEST_SUPPORT_DIR)/aot/jdk.aotconf + $1_AOT_JDK_CACHE := $$($1_TEST_SUPPORT_DIR)/aot/jdk.aotcache + + $1_JAVA_TOOL_OPTS := $$(addprefix -J, $$($1_VM_OPTIONS)) + + $$($1_AOT_JDK_CACHE): $$(JDK_IMAGE_DIR)/release + $$(call MakeDir, $$($1_TEST_SUPPORT_DIR)/aot) + + $(foreach jtool, javac javap jlink jar, \ + $(info AOT: Create cache configuration for $(jtool)) \ + $$(call ExecuteWithLog, $$($1_TEST_SUPPORT_DIR)/aot.$(jtool), ( \ + $$(FIXPATH) $(JDK_UNDER_TEST)/bin/$(jtool) $$($1_JAVA_TOOL_OPTS) \ + -J-XX:AOTMode=record -J-XX:AOTConfiguration=$$($1_AOT_JDK_CONF).$(jtool) --help \ + )) + ) + + $$(info AOT: Copy $(JDK_UNDER_TEST)/lib/classlist to $$($1_AOT_JDK_CONF).jdk ) + $$(call ExecuteWithLog, $$($1_TEST_SUPPORT_DIR)/aot, ( \ + $$(FIXPATH) $(CP) $(JDK_UNDER_TEST)/lib/classlist $$($1_AOT_JDK_CONF).jdk \ + )) + + $$(FIXPATH) $$(CAT) $$($1_AOT_JDK_CONF).* > $$($1_AOT_JDK_CONF).temp + $$(FIXPATH) $$(CAT) $$($1_AOT_JDK_CONF).temp | $(GREP) -v '#' | $(GREP) -v '@' | $(SORT) | \ + $(SED) -e 's/id:.*//g' | uniq \ + > $$($1_AOT_JDK_CONF) + $$(FIXPATH) $$(CAT) $$($1_AOT_JDK_CONF).temp | $(GREP) '@cp' | $(SORT) \ + >> $$($1_AOT_JDK_CONF) + + $$(info AOT: Generate AOT cache $$($1_AOT_JDK_CACHE) with flags: $$($1_VM_OPTIONS)) + $$(call ExecuteWithLog, $$($1_TEST_SUPPORT_DIR)/aot, ( \ + $$(FIXPATH) $(JDK_UNDER_TEST)/bin/java \ + $$($1_VM_OPTIONS) -Xlog:cds,cds+class=debug:file=$$($1_AOT_JDK_CACHE).log \ + -XX:AOTMode=create -XX:AOTConfiguration=$$($1_AOT_JDK_CONF) -XX:AOTCache=$$($1_AOT_JDK_CACHE) \ + )) + + $1_AOT_TARGETS += $$($1_AOT_JDK_CACHE) + +endef + + SetupRunJtregTest = $(NamedParamsMacroTemplate) define SetupRunJtregTestBody $1_TEST_RESULTS_DIR := $$(TEST_RESULTS_DIR)/$1 @@ -762,6 +815,7 @@ define SetupRunJtregTestBody JTREG_RETRY_COUNT ?= 0 JTREG_REPEAT_COUNT ?= 0 JTREG_REPORT ?= files + JTREG_AOT_JDK ?= false ifneq ($$(JTREG_RETRY_COUNT), 0) ifneq ($$(JTREG_REPEAT_COUNT), 0) @@ -891,6 +945,17 @@ define SetupRunJtregTestBody endif endif + ifeq ($$(JTREG_AOT_JDK), true) + $$(info Add AOT target for $1) + $$(eval $$(call SetupAot, $1, VM_OPTIONS := $$(JTREG_ALL_OPTIONS) )) + + $$(info AOT_TARGETS=$$($1_AOT_TARGETS)) + $$(info AOT_JDK_CACHE=$$($1_AOT_JDK_CACHE)) + + $1_JTREG_BASIC_OPTIONS += -vmoption:-XX:AOTCache="$$($1_AOT_JDK_CACHE)" + endif + + $$(eval $$(call SetupRunJtregTestCustom, $1)) # SetupRunJtregTestCustom might also adjust JTREG_AUTO_ variables @@ -906,6 +971,7 @@ define SetupRunJtregTestBody JTREG_TIMEOUT_FACTOR ?= $$(JTREG_AUTO_TIMEOUT_FACTOR) clean-outputdirs-$1: + $$(call LogWarn, Clean up dirs for $1) $$(RM) -r $$($1_TEST_SUPPORT_DIR) $$(RM) -r $$($1_TEST_RESULTS_DIR) @@ -953,7 +1019,7 @@ define SetupRunJtregTestBody done endif - run-test-$1: pre-run-test clean-outputdirs-$1 + run-test-$1: clean-outputdirs-$1 pre-run-test $$($1_AOT_TARGETS) $$(call LogWarn) $$(call LogWarn, Running test '$$($1_TEST)') $$(call MakeDir, $$($1_TEST_RESULTS_DIR) $$($1_TEST_SUPPORT_DIR) \ diff --git a/src/java.base/share/classes/java/io/BufferedInputStream.java b/src/java.base/share/classes/java/io/BufferedInputStream.java index c401873ce12..5ca55d838ae 100644 --- a/src/java.base/share/classes/java/io/BufferedInputStream.java +++ b/src/java.base/share/classes/java/io/BufferedInputStream.java @@ -28,7 +28,6 @@ import java.util.Arrays; import java.util.Objects; -import jdk.internal.misc.InternalLock; import jdk.internal.misc.Unsafe; import jdk.internal.util.ArraysSupport; @@ -74,9 +73,6 @@ public class BufferedInputStream extends FilterInputStream { private static final long BUF_OFFSET = U.objectFieldOffset(BufferedInputStream.class, "buf"); - // initialized to null when BufferedInputStream is sub-classed - private final InternalLock lock; - // initial buffer size (DEFAULT_BUFFER_SIZE or size specified to constructor) private final int initialSize; @@ -243,12 +239,9 @@ public BufferedInputStream(InputStream in, int size) { } initialSize = size; if (getClass() == BufferedInputStream.class) { - // use internal lock and lazily create buffer when not subclassed - lock = InternalLock.newLockOrNull(); + // lazily create buffer when not subclassed buf = EMPTY; } else { - // use monitors and eagerly create buffer when subclassed - lock = null; buf = new byte[size]; } } @@ -256,7 +249,7 @@ public BufferedInputStream(InputStream in, int size) { /** * Fills the buffer with more data, taking into account * shuffling and other tricks for dealing with marks. - * Assumes that it is being called by a locked method. + * Assumes that it is being called by a synchronized method. * This method also assumes that all data has already been read in, * hence pos > count. */ @@ -310,22 +303,7 @@ else if (pos >= buffer.length) { /* no room left in buffer */ * or an I/O error occurs. * @see java.io.FilterInputStream#in */ - public int read() throws IOException { - if (lock != null) { - lock.lock(); - try { - return implRead(); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - return implRead(); - } - } - } - - private int implRead() throws IOException { + public synchronized int read() throws IOException { if (pos >= count) { fill(); if (pos >= count) @@ -397,22 +375,7 @@ private int read1(byte[] b, int off, int len) throws IOException { * or an I/O error occurs. * @throws IndexOutOfBoundsException {@inheritDoc} */ - public int read(byte[] b, int off, int len) throws IOException { - if (lock != null) { - lock.lock(); - try { - return implRead(b, off, len); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - return implRead(b, off, len); - } - } - } - - private int implRead(byte[] b, int off, int len) throws IOException { + public synchronized int read(byte[] b, int off, int len) throws IOException { ensureOpen(); if ((off | len | (off + len) | (b.length - (off + len))) < 0) { throw new IndexOutOfBoundsException(); @@ -444,22 +407,7 @@ private int implRead(byte[] b, int off, int len) throws IOException { * {@code in.skip(n)} throws an IOException, * or an I/O error occurs. */ - public long skip(long n) throws IOException { - if (lock != null) { - lock.lock(); - try { - return implSkip(n); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - return implSkip(n); - } - } - } - - private long implSkip(long n) throws IOException { + public synchronized long skip(long n) throws IOException { ensureOpen(); if (n <= 0) { return 0; @@ -500,22 +448,7 @@ private long implSkip(long n) throws IOException { * invoking its {@link #close()} method, * or an I/O error occurs. */ - public int available() throws IOException { - if (lock != null) { - lock.lock(); - try { - return implAvailable(); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - return implAvailable(); - } - } - } - - private int implAvailable() throws IOException { + public synchronized int available() throws IOException { int n = count - pos; int avail = getInIfOpen().available(); return n > (Integer.MAX_VALUE - avail) @@ -531,22 +464,7 @@ private int implAvailable() throws IOException { * the mark position becomes invalid. * @see java.io.BufferedInputStream#reset() */ - public void mark(int readlimit) { - if (lock != null) { - lock.lock(); - try { - implMark(readlimit); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - implMark(readlimit); - } - } - } - - private void implMark(int readlimit) { + public synchronized void mark(int readlimit) { marklimit = readlimit; markpos = pos; } @@ -567,22 +485,7 @@ private void implMark(int readlimit) { * method, or an I/O error occurs. * @see java.io.BufferedInputStream#mark(int) */ - public void reset() throws IOException { - if (lock != null) { - lock.lock(); - try { - implReset(); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - implReset(); - } - } - } - - private void implReset() throws IOException { + public synchronized void reset() throws IOException { ensureOpen(); if (markpos < 0) throw new IOException("Resetting to invalid mark"); @@ -628,23 +531,8 @@ public void close() throws IOException { } @Override - public long transferTo(OutputStream out) throws IOException { + public synchronized long transferTo(OutputStream out) throws IOException { Objects.requireNonNull(out, "out"); - if (lock != null) { - lock.lock(); - try { - return implTransferTo(out); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - return implTransferTo(out); - } - } - } - - private long implTransferTo(OutputStream out) throws IOException { if (getClass() == BufferedInputStream.class && markpos == -1) { int avail = count - pos; if (avail > 0) { diff --git a/src/java.base/share/classes/java/io/BufferedOutputStream.java b/src/java.base/share/classes/java/io/BufferedOutputStream.java index 687f0c91bc4..2ad9adad5ad 100644 --- a/src/java.base/share/classes/java/io/BufferedOutputStream.java +++ b/src/java.base/share/classes/java/io/BufferedOutputStream.java @@ -26,7 +26,6 @@ package java.io; import java.util.Arrays; -import jdk.internal.misc.InternalLock; import jdk.internal.misc.VM; /** @@ -47,9 +46,6 @@ public class BufferedOutputStream extends FilterOutputStream { private static final int DEFAULT_INITIAL_BUFFER_SIZE = 512; private static final int DEFAULT_MAX_BUFFER_SIZE = 8192; - // initialized to null when BufferedOutputStream is sub-classed - private final InternalLock lock; - /** * The internal buffer where data is stored. */ @@ -90,12 +86,9 @@ private BufferedOutputStream(OutputStream out, int initialSize, int maxSize) { } if (getClass() == BufferedOutputStream.class) { - // use InternalLock and resizable buffer when not sub-classed - this.lock = InternalLock.newLockOrNull(); - this.buf = new byte[initialSize]; // resizable + // resizable when not sub-classed + this.buf = new byte[initialSize]; } else { - // use monitors and no resizing when sub-classed - this.lock = null; this.buf = new byte[maxSize]; } this.maxBufSize = maxSize; @@ -136,8 +129,6 @@ private void flushBuffer() throws IOException { * Grow buf to fit an additional len bytes if needed. * If possible, it grows by len+1 to avoid flushing when len bytes * are added. A no-op if the buffer is not resizable. - * - * This method should only be called while holding the lock. */ private void growIfNeeded(int len) { int neededSize = count + len + 1; @@ -157,22 +148,7 @@ private void growIfNeeded(int len) { * @throws IOException if an I/O error occurs. */ @Override - public void write(int b) throws IOException { - if (lock != null) { - lock.lock(); - try { - implWrite(b); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - implWrite(b); - } - } - } - - private void implWrite(int b) throws IOException { + public synchronized void write(int b) throws IOException { growIfNeeded(1); if (count >= buf.length) { flushBuffer(); @@ -198,22 +174,7 @@ private void implWrite(int b) throws IOException { * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override - public void write(byte[] b, int off, int len) throws IOException { - if (lock != null) { - lock.lock(); - try { - implWrite(b, off, len); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - implWrite(b, off, len); - } - } - } - - private void implWrite(byte[] b, int off, int len) throws IOException { + public synchronized void write(byte[] b, int off, int len) throws IOException { if (len >= maxBufSize) { /* If the request length exceeds the max size of the output buffer, flush the output buffer and then write the data directly. @@ -238,22 +199,7 @@ private void implWrite(byte[] b, int off, int len) throws IOException { * @see java.io.FilterOutputStream#out */ @Override - public void flush() throws IOException { - if (lock != null) { - lock.lock(); - try { - implFlush(); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - implFlush(); - } - } - } - - private void implFlush() throws IOException { + public synchronized void flush() throws IOException { flushBuffer(); out.flush(); } diff --git a/src/java.base/share/classes/java/io/BufferedReader.java b/src/java.base/share/classes/java/io/BufferedReader.java index c2f6b89e086..a51f0acaf00 100644 --- a/src/java.base/share/classes/java/io/BufferedReader.java +++ b/src/java.base/share/classes/java/io/BufferedReader.java @@ -32,7 +32,6 @@ import java.util.Spliterators; import java.util.stream.Stream; import java.util.stream.StreamSupport; -import jdk.internal.misc.InternalLock; /** * Reads text from a character-input stream, buffering characters so as to @@ -181,37 +180,23 @@ private void fill() throws IOException { * @throws IOException If an I/O error occurs */ public int read() throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - return implRead(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - return implRead(); - } - } - } - - private int implRead() throws IOException { - ensureOpen(); - for (;;) { - if (nextChar >= nChars) { - fill(); - if (nextChar >= nChars) - return -1; - } - if (skipLF) { - skipLF = false; - if (cb[nextChar] == '\n') { - nextChar++; - continue; + synchronized (lock) { + ensureOpen(); + for (;;) { + if (nextChar >= nChars) { + fill(); + if (nextChar >= nChars) + return -1; + } + if (skipLF) { + skipLF = false; + if (cb[nextChar] == '\n') { + nextChar++; + continue; + } } + return cb[nextChar++]; } - return cb[nextChar++]; } } @@ -296,36 +281,22 @@ private int read1(char[] cbuf, int off, int len) throws IOException { * @throws IOException {@inheritDoc} */ public int read(char[] cbuf, int off, int len) throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - return implRead(cbuf, off, len); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - return implRead(cbuf, off, len); + synchronized (lock) { + ensureOpen(); + Objects.checkFromIndexSize(off, len, cbuf.length); + if (len == 0) { + return 0; } - } - } - - private int implRead(char[] cbuf, int off, int len) throws IOException { - ensureOpen(); - Objects.checkFromIndexSize(off, len, cbuf.length); - if (len == 0) { - return 0; - } - int n = read1(cbuf, off, len); - if (n <= 0) return n; - while ((n < len) && in.ready()) { - int n1 = read1(cbuf, off + n, len - n); - if (n1 <= 0) break; - n += n1; + int n = read1(cbuf, off, len); + if (n <= 0) return n; + while ((n < len) && in.ready()) { + int n1 = read1(cbuf, off + n, len - n); + if (n1 <= 0) break; + n += n1; + } + return n; } - return n; } /** @@ -347,81 +318,67 @@ private int implRead(char[] cbuf, int off, int len) throws IOException { * @throws IOException If an I/O error occurs */ String readLine(boolean ignoreLF, boolean[] term) throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - return implReadLine(ignoreLF, term); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - return implReadLine(ignoreLF, term); - } - } - } + synchronized (lock) { + StringBuilder s = null; + int startChar; - private String implReadLine(boolean ignoreLF, boolean[] term) throws IOException { - StringBuilder s = null; - int startChar; + ensureOpen(); + boolean omitLF = ignoreLF || skipLF; + if (term != null) term[0] = false; - ensureOpen(); - boolean omitLF = ignoreLF || skipLF; - if (term != null) term[0] = false; + bufferLoop: + for (;;) { - bufferLoop: - for (;;) { - - if (nextChar >= nChars) - fill(); - if (nextChar >= nChars) { /* EOF */ - if (s != null && s.length() > 0) - return s.toString(); - else - return null; - } - boolean eol = false; - char c = 0; - int i; + if (nextChar >= nChars) + fill(); + if (nextChar >= nChars) { /* EOF */ + if (s != null && s.length() > 0) + return s.toString(); + else + return null; + } + boolean eol = false; + char c = 0; + int i; - /* Skip a leftover '\n', if necessary */ - if (omitLF && (cb[nextChar] == '\n')) - nextChar++; - skipLF = false; - omitLF = false; - - charLoop: - for (i = nextChar; i < nChars; i++) { - c = cb[i]; - if ((c == '\n') || (c == '\r')) { - if (term != null) term[0] = true; - eol = true; - break charLoop; + /* Skip a leftover '\n', if necessary */ + if (omitLF && (cb[nextChar] == '\n')) + nextChar++; + skipLF = false; + omitLF = false; + + charLoop: + for (i = nextChar; i < nChars; i++) { + c = cb[i]; + if ((c == '\n') || (c == '\r')) { + if (term != null) term[0] = true; + eol = true; + break charLoop; + } } - } - startChar = nextChar; - nextChar = i; + startChar = nextChar; + nextChar = i; - if (eol) { - String str; - if (s == null) { - str = new String(cb, startChar, i - startChar); - } else { - s.append(cb, startChar, i - startChar); - str = s.toString(); - } - nextChar++; - if (c == '\r') { - skipLF = true; + if (eol) { + String str; + if (s == null) { + str = new String(cb, startChar, i - startChar); + } else { + s.append(cb, startChar, i - startChar); + str = s.toString(); + } + nextChar++; + if (c == '\r') { + skipLF = true; + } + return str; } - return str; - } - if (s == null) - s = new StringBuilder(DEFAULT_EXPECTED_LINE_LENGTH); - s.append(cb, startChar, i - startChar); + if (s == null) + s = new StringBuilder(DEFAULT_EXPECTED_LINE_LENGTH); + s.append(cb, startChar, i - startChar); + } } } @@ -450,47 +407,33 @@ public long skip(long n) throws IOException { if (n < 0L) { throw new IllegalArgumentException("skip value is negative"); } - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - return implSkip(n); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - return implSkip(n); - } - } - } - - private long implSkip(long n) throws IOException { - ensureOpen(); - long r = n; - while (r > 0) { - if (nextChar >= nChars) - fill(); - if (nextChar >= nChars) /* EOF */ - break; - if (skipLF) { - skipLF = false; - if (cb[nextChar] == '\n') { - nextChar++; + synchronized (lock) { + ensureOpen(); + long r = n; + while (r > 0) { + if (nextChar >= nChars) + fill(); + if (nextChar >= nChars) /* EOF */ + break; + if (skipLF) { + skipLF = false; + if (cb[nextChar] == '\n') { + nextChar++; + } + } + long d = nChars - nextChar; + if (r <= d) { + nextChar += (int)r; + r = 0; + break; + } + else { + r -= d; + nextChar = nChars; } } - long d = nChars - nextChar; - if (r <= d) { - nextChar += (int)r; - r = 0; - break; - } - else { - r -= d; - nextChar = nChars; - } + return n - r; } - return n - r; } /** @@ -501,42 +444,28 @@ private long implSkip(long n) throws IOException { * @throws IOException If an I/O error occurs */ public boolean ready() throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - return implReady(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - return implReady(); - } - } - } + synchronized (lock) { + ensureOpen(); - private boolean implReady() throws IOException { - ensureOpen(); - - /* - * If newline needs to be skipped and the next char to be read - * is a newline character, then just skip it right away. - */ - if (skipLF) { - /* Note that in.ready() will return true if and only if the next - * read on the stream will not block. + /* + * If newline needs to be skipped and the next char to be read + * is a newline character, then just skip it right away. */ - if (nextChar >= nChars && in.ready()) { - fill(); - } - if (nextChar < nChars) { - if (cb[nextChar] == '\n') - nextChar++; - skipLF = false; + if (skipLF) { + /* Note that in.ready() will return true if and only if the next + * read on the stream will not block. + */ + if (nextChar >= nChars && in.ready()) { + fill(); + } + if (nextChar < nChars) { + if (cb[nextChar] == '\n') + nextChar++; + skipLF = false; + } } + return (nextChar < nChars) || in.ready(); } - return (nextChar < nChars) || in.ready(); } /** @@ -566,28 +495,14 @@ public void mark(int readAheadLimit) throws IOException { if (readAheadLimit < 0) { throw new IllegalArgumentException("Read-ahead limit < 0"); } - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - implMark(readAheadLimit); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - implMark(readAheadLimit); - } + synchronized (lock) { + ensureOpen(); + this.readAheadLimit = readAheadLimit; + markedChar = nextChar; + markedSkipLF = skipLF; } } - private void implMark(int readAheadLimit) throws IOException { - ensureOpen(); - this.readAheadLimit = readAheadLimit; - markedChar = nextChar; - markedSkipLF = skipLF; - } - /** * Resets the stream to the most recent mark. * @@ -595,55 +510,27 @@ private void implMark(int readAheadLimit) throws IOException { * or if the mark has been invalidated */ public void reset() throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - implReset(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - implReset(); - } + synchronized (lock) { + ensureOpen(); + if (markedChar < 0) + throw new IOException((markedChar == INVALIDATED) + ? "Mark invalid" + : "Stream not marked"); + nextChar = markedChar; + skipLF = markedSkipLF; } } - private void implReset() throws IOException { - ensureOpen(); - if (markedChar < 0) - throw new IOException((markedChar == INVALIDATED) - ? "Mark invalid" - : "Stream not marked"); - nextChar = markedChar; - skipLF = markedSkipLF; - } - public void close() throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); + synchronized (lock) { + if (in == null) + return; try { - implClose(); + in.close(); } finally { - locker.unlock(); + in = null; + cb = null; } - } else { - synchronized (lock) { - implClose(); - } - } - } - - private void implClose() throws IOException { - if (in == null) - return; - try { - in.close(); - } finally { - in = null; - cb = null; } } diff --git a/src/java.base/share/classes/java/io/BufferedWriter.java b/src/java.base/share/classes/java/io/BufferedWriter.java index 17862a265ae..e3f8a21fe60 100644 --- a/src/java.base/share/classes/java/io/BufferedWriter.java +++ b/src/java.base/share/classes/java/io/BufferedWriter.java @@ -27,7 +27,6 @@ import java.util.Arrays; import java.util.Objects; -import jdk.internal.misc.InternalLock; import jdk.internal.misc.VM; /** @@ -162,58 +161,30 @@ private void growIfNeeded(int len) { * may be invoked by PrintStream. */ void flushBuffer() throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - implFlushBuffer(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - implFlushBuffer(); - } + synchronized (lock) { + ensureOpen(); + if (nextChar == 0) + return; + out.write(cb, 0, nextChar); + nextChar = 0; } } - private void implFlushBuffer() throws IOException { - ensureOpen(); - if (nextChar == 0) - return; - out.write(cb, 0, nextChar); - nextChar = 0; - } - /** * Writes a single character. * * @throws IOException If an I/O error occurs */ public void write(int c) throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - implWrite(c); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - implWrite(c); - } + synchronized (lock) { + ensureOpen(); + growIfNeeded(1); + if (nextChar >= nChars) + flushBuffer(); + cb[nextChar++] = (char) c; } } - private void implWrite(int c) throws IOException { - ensureOpen(); - growIfNeeded(1); - if (nextChar >= nChars) - flushBuffer(); - cb[nextChar++] = (char) c; - } - /** * Our own little min method, to avoid loading java.lang.Math if we've run * out of file descriptors and we're trying to print a stack trace. @@ -245,46 +216,32 @@ private int min(int a, int b) { * @throws IOException If an I/O error occurs */ public void write(char[] cbuf, int off, int len) throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - implWrite(cbuf, off, len); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - implWrite(cbuf, off, len); + synchronized (lock) { + ensureOpen(); + Objects.checkFromIndexSize(off, len, cbuf.length); + if (len == 0) { + return; } - } - } - private void implWrite(char[] cbuf, int off, int len) throws IOException { - ensureOpen(); - Objects.checkFromIndexSize(off, len, cbuf.length); - if (len == 0) { - return; - } - - if (len >= maxChars) { - /* If the request length exceeds the max size of the output buffer, - flush the buffer and then write the data directly. In this - way buffered streams will cascade harmlessly. */ - flushBuffer(); - out.write(cbuf, off, len); - return; - } - - growIfNeeded(len); - int b = off, t = off + len; - while (b < t) { - int d = min(nChars - nextChar, t - b); - System.arraycopy(cbuf, b, cb, nextChar, d); - b += d; - nextChar += d; - if (nextChar >= nChars) { + if (len >= maxChars) { + /* If the request length exceeds the max size of the output buffer, + flush the buffer and then write the data directly. In this + way buffered streams will cascade harmlessly. */ flushBuffer(); + out.write(cbuf, off, len); + return; + } + + growIfNeeded(len); + int b = off, t = off + len; + while (b < t) { + int d = min(nChars - nextChar, t - b); + System.arraycopy(cbuf, b, cb, nextChar, d); + b += d; + nextChar += d; + if (nextChar >= nChars) { + flushBuffer(); + } } } } @@ -312,35 +269,21 @@ private void implWrite(char[] cbuf, int off, int len) throws IOException { * @throws IOException If an I/O error occurs */ public void write(String s, int off, int len) throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - implWrite(s, off, len); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - implWrite(s, off, len); + synchronized (lock) { + ensureOpen(); + growIfNeeded(len); + int b = off, t = off + len; + while (b < t) { + int d = min(nChars - nextChar, t - b); + s.getChars(b, b + d, cb, nextChar); + b += d; + nextChar += d; + if (nextChar >= nChars) + flushBuffer(); } } } - private void implWrite(String s, int off, int len) throws IOException { - ensureOpen(); - growIfNeeded(len); - int b = off, t = off + len; - while (b < t) { - int d = min(nChars - nextChar, t - b); - s.getChars(b, b + d, cb, nextChar); - b += d; - nextChar += d; - if (nextChar >= nChars) - flushBuffer(); - } - } - /** * Writes a line separator. The line separator string is defined by the * system property {@code line.separator}, and is not necessarily a single @@ -358,52 +301,24 @@ public void newLine() throws IOException { * @throws IOException If an I/O error occurs */ public void flush() throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - implFlush(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - implFlush(); - } + synchronized (lock) { + flushBuffer(); + out.flush(); } } - private void implFlush() throws IOException { - flushBuffer(); - out.flush(); - } - + @SuppressWarnings("try") public void close() throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - implClose(); - } finally { - locker.unlock(); + synchronized (lock) { + if (out == null) { + return; } - } else { - synchronized (lock) { - implClose(); + try (Writer w = out) { + flushBuffer(); + } finally { + out = null; + cb = null; } } } - - @SuppressWarnings("try") - private void implClose() throws IOException { - if (out == null) { - return; - } - try (Writer w = out) { - flushBuffer(); - } finally { - out = null; - cb = null; - } - } } diff --git a/src/java.base/share/classes/java/io/InputStreamReader.java b/src/java.base/share/classes/java/io/InputStreamReader.java index d3033b15b9f..6d43c4ae0cd 100644 --- a/src/java.base/share/classes/java/io/InputStreamReader.java +++ b/src/java.base/share/classes/java/io/InputStreamReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,7 +28,6 @@ import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; -import jdk.internal.misc.InternalLock; import sun.nio.cs.StreamDecoder; /** @@ -62,20 +61,6 @@ public class InputStreamReader extends Reader { private final StreamDecoder sd; - /** - * Return the lock object for the given reader's stream decoder. - * If the reader type is trusted then an internal lock can be used. If the - * reader type is not trusted then the reader object is the lock. - */ - private static Object lockFor(InputStreamReader reader) { - Class clazz = reader.getClass(); - if (clazz == InputStreamReader.class || clazz == FileReader.class) { - return InternalLock.newLockOr(reader); - } else { - return reader; - } - } - /** * Creates an InputStreamReader that uses the * {@link Charset#defaultCharset() default charset}. @@ -88,7 +73,7 @@ private static Object lockFor(InputStreamReader reader) { public InputStreamReader(InputStream in) { super(in); Charset cs = Charset.defaultCharset(); - sd = StreamDecoder.forInputStreamReader(in, lockFor(this), cs); + sd = StreamDecoder.forInputStreamReader(in, this, cs); } /** @@ -110,7 +95,7 @@ public InputStreamReader(InputStream in, String charsetName) super(in); if (charsetName == null) throw new NullPointerException("charsetName"); - sd = StreamDecoder.forInputStreamReader(in, lockFor(this), charsetName); + sd = StreamDecoder.forInputStreamReader(in, this, charsetName); } /** @@ -126,7 +111,7 @@ public InputStreamReader(InputStream in, Charset cs) { super(in); if (cs == null) throw new NullPointerException("charset"); - sd = StreamDecoder.forInputStreamReader(in, lockFor(this), cs); + sd = StreamDecoder.forInputStreamReader(in, this, cs); } /** @@ -142,7 +127,7 @@ public InputStreamReader(InputStream in, CharsetDecoder dec) { super(in); if (dec == null) throw new NullPointerException("charset decoder"); - sd = StreamDecoder.forInputStreamReader(in, lockFor(this), dec); + sd = StreamDecoder.forInputStreamReader(in, this, dec); } /** diff --git a/src/java.base/share/classes/java/io/OutputStreamWriter.java b/src/java.base/share/classes/java/io/OutputStreamWriter.java index cda9fead18e..9a16aa140bc 100644 --- a/src/java.base/share/classes/java/io/OutputStreamWriter.java +++ b/src/java.base/share/classes/java/io/OutputStreamWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,7 +28,6 @@ import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; -import jdk.internal.misc.InternalLock; import sun.nio.cs.StreamEncoder; /** @@ -75,20 +74,6 @@ public class OutputStreamWriter extends Writer { private final StreamEncoder se; - /** - * Return the lock object for the given writer's stream encoder. - * If the writer type is trusted then an internal lock can be used. If the - * writer type is not trusted then the writer object is the lock. - */ - private static Object lockFor(OutputStreamWriter writer) { - Class clazz = writer.getClass(); - if (clazz == OutputStreamWriter.class || clazz == FileWriter.class) { - return InternalLock.newLockOr(writer); - } else { - return writer; - } - } - /** * Creates an OutputStreamWriter that uses the named charset. * @@ -108,7 +93,7 @@ public OutputStreamWriter(OutputStream out, String charsetName) super(out); if (charsetName == null) throw new NullPointerException("charsetName"); - se = StreamEncoder.forOutputStreamWriter(out, lockFor(this), charsetName); + se = StreamEncoder.forOutputStreamWriter(out, this, charsetName); } /** @@ -122,7 +107,7 @@ public OutputStreamWriter(OutputStream out, String charsetName) @SuppressWarnings("this-escape") public OutputStreamWriter(OutputStream out) { super(out); - se = StreamEncoder.forOutputStreamWriter(out, lockFor(this), + se = StreamEncoder.forOutputStreamWriter(out, this, out instanceof PrintStream ps ? ps.charset() : Charset.defaultCharset()); } @@ -142,7 +127,7 @@ public OutputStreamWriter(OutputStream out, Charset cs) { super(out); if (cs == null) throw new NullPointerException("charset"); - se = StreamEncoder.forOutputStreamWriter(out, lockFor(this), cs); + se = StreamEncoder.forOutputStreamWriter(out, this, cs); } /** @@ -161,7 +146,7 @@ public OutputStreamWriter(OutputStream out, CharsetEncoder enc) { super(out); if (enc == null) throw new NullPointerException("charset encoder"); - se = StreamEncoder.forOutputStreamWriter(out, lockFor(this), enc); + se = StreamEncoder.forOutputStreamWriter(out, this, enc); } /** diff --git a/src/java.base/share/classes/java/io/PrintStream.java b/src/java.base/share/classes/java/io/PrintStream.java index bd2af07156e..79e3dcfae9d 100644 --- a/src/java.base/share/classes/java/io/PrintStream.java +++ b/src/java.base/share/classes/java/io/PrintStream.java @@ -36,9 +36,6 @@ import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.UnsupportedCharsetException; -import jdk.internal.access.JavaIOPrintStreamAccess; -import jdk.internal.access.SharedSecrets; -import jdk.internal.misc.InternalLock; /*[IF CRIU_SUPPORT]*/ import openj9.internal.criu.NotCheckpointSafe; @@ -77,9 +74,6 @@ public class PrintStream extends FilterOutputStream implements Appendable, Closeable { - // initialized to null when PrintStream is sub-classed - private final InternalLock lock; - private final boolean autoFlush; private boolean trouble = false; private Formatter formatter; @@ -127,13 +121,6 @@ private PrintStream(boolean autoFlush, OutputStream out) { this.charset = out instanceof PrintStream ps ? ps.charset() : Charset.defaultCharset(); this.charOut = new OutputStreamWriter(this, charset); this.textOut = new BufferedWriter(charOut); - - // use monitors when PrintStream is sub-classed - if (getClass() == PrintStream.class) { - lock = InternalLock.newLockOrNull(); - } else { - lock = null; - } } /* Variant of the private constructor so that the given charset name @@ -230,13 +217,6 @@ public PrintStream(OutputStream out, boolean autoFlush, Charset charset) { this.charOut = new OutputStreamWriter(this, charset); this.textOut = new BufferedWriter(charOut); this.charset = charset; - - // use monitors when PrintStream is sub-classed - if (getClass() == PrintStream.class) { - lock = InternalLock.newLockOrNull(); - } else { - lock = null; - } } /** @@ -430,30 +410,17 @@ private void ensureOpen() throws IOException { */ @Override public void flush() { - if (lock != null) { - lock.lock(); + synchronized (this) { try { - implFlush(); - } finally { - lock.unlock(); + ensureOpen(); + out.flush(); } - } else { - synchronized (this) { - implFlush(); + catch (IOException x) { + trouble = true; } } } - private void implFlush() { - try { - ensureOpen(); - out.flush(); - } - catch (IOException x) { - trouble = true; - } - } - private boolean closing = false; /* To avoid recursive closing */ /** @@ -464,33 +431,20 @@ private void implFlush() { */ @Override public void close() { - if (lock != null) { - lock.lock(); - try { - implClose(); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - implClose(); - } - } - } - - private void implClose() { - if (!closing) { - closing = true; - try { - textOut.close(); - out.close(); - } - catch (IOException x) { - trouble = true; + synchronized (this) { + if (!closing) { + closing = true; + try { + textOut.close(); + out.close(); + } + catch (IOException x) { + trouble = true; + } + textOut = null; + charOut = null; + out = null; } - textOut = null; - charOut = null; - out = null; } } @@ -557,17 +511,11 @@ protected void clearError() { @Override public void write(int b) { try { - if (lock != null) { - lock.lock(); - try { - implWrite(b); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - implWrite(b); - } + synchronized (this) { + ensureOpen(); + out.write(b); + if ((b == '\n') && autoFlush) + out.flush(); } } catch (InterruptedIOException x) { @@ -578,13 +526,6 @@ public void write(int b) { } } - private void implWrite(int b) throws IOException { - ensureOpen(); - out.write(b); - if ((b == '\n') && autoFlush) - out.flush(); - } - /** * Writes {@code len} bytes from the specified byte array starting at * offset {@code off} to this stream. If automatic flushing is @@ -603,17 +544,11 @@ private void implWrite(int b) throws IOException { @Override public void write(byte[] buf, int off, int len) { try { - if (lock != null) { - lock.lock(); - try { - implWrite(buf, off, len); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - implWrite(buf, off, len); - } + synchronized (this) { + ensureOpen(); + out.write(buf, off, len); + if (autoFlush) + out.flush(); } } catch (InterruptedIOException x) { @@ -624,14 +559,6 @@ public void write(byte[] buf, int off, int len) { } } - private void implWrite(byte[] buf, int off, int len) throws IOException { - ensureOpen(); - out.write(buf, off, len); - if (autoFlush) - out.flush(); - } - - /** * Writes all bytes from the specified byte array to this stream. If * automatic flushing is enabled then the {@code flush} method will be @@ -696,16 +623,17 @@ public void writeBytes(byte[] buf) { private void write(char[] buf) { try { - if (lock != null) { - lock.lock(); - try { - implWrite(buf); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - implWrite(buf); + synchronized (this) { + ensureOpen(); + textOut.write(buf); + textOut.flushBuffer(); + charOut.flushBuffer(); + if (autoFlush) { + for (int i = 0; i < buf.length; i++) + if (buf[i] == '\n') { + out.flush(); + break; + } } } } catch (InterruptedIOException x) { @@ -715,37 +643,20 @@ private void write(char[] buf) { } } - private void implWrite(char[] buf) throws IOException { - ensureOpen(); - textOut.write(buf); - textOut.flushBuffer(); - charOut.flushBuffer(); - if (autoFlush) { - for (int i = 0; i < buf.length; i++) - if (buf[i] == '\n') { - out.flush(); - break; - } - } - } - // Used to optimize away back-to-back flushing and synchronization when // using println, but since subclasses could exist which depend on // observing a call to print followed by newLine() we only use this if // getClass() == PrintStream.class to avoid compatibility issues. private void writeln(char[] buf) { try { - if (lock != null) { - lock.lock(); - try { - implWriteln(buf); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - implWriteln(buf); - } + synchronized (this) { + ensureOpen(); + textOut.write(buf); + textOut.newLine(); + textOut.flushBuffer(); + charOut.flushBuffer(); + if (autoFlush) + out.flush(); } } catch (InterruptedIOException x) { @@ -756,29 +667,15 @@ private void writeln(char[] buf) { } } - private void implWriteln(char[] buf) throws IOException { - ensureOpen(); - textOut.write(buf); - textOut.newLine(); - textOut.flushBuffer(); - charOut.flushBuffer(); - if (autoFlush) - out.flush(); - } - private void write(String s) { try { - if (lock != null) { - lock.lock(); - try { - implWrite(s); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - implWrite(s); - } + synchronized (this) { + ensureOpen(); + textOut.write(s); + textOut.flushBuffer(); + charOut.flushBuffer(); + if (autoFlush && (s.indexOf('\n') >= 0)) + out.flush(); } } catch (InterruptedIOException x) { @@ -789,15 +686,6 @@ private void write(String s) { } } - private void implWrite(String s) throws IOException { - ensureOpen(); - textOut.write(s); - textOut.flushBuffer(); - charOut.flushBuffer(); - if (autoFlush && (s.indexOf('\n') >= 0)) - out.flush(); - } - // Used to optimize away back-to-back flushing and synchronization when // using println, but since subclasses could exist which depend on // observing a call to print followed by newLine we only use this if @@ -807,17 +695,14 @@ private void implWrite(String s) throws IOException { /*[ENDIF] CRIU_SUPPORT */ private void writeln(String s) { try { - if (lock != null) { - lock.lock(); - try { - implWriteln(s); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - implWriteln(s); - } + synchronized (this) { + ensureOpen(); + textOut.write(s); + textOut.newLine(); + textOut.flushBuffer(); + charOut.flushBuffer(); + if (autoFlush) + out.flush(); } } catch (InterruptedIOException x) { @@ -828,29 +713,15 @@ private void writeln(String s) { } } - private void implWriteln(String s) throws IOException { - ensureOpen(); - textOut.write(s); - textOut.newLine(); - textOut.flushBuffer(); - charOut.flushBuffer(); - if (autoFlush) - out.flush(); - } - private void newLine() { try { - if (lock != null) { - lock.lock(); - try { - implNewLine(); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - implNewLine(); - } + synchronized (this) { + ensureOpen(); + textOut.newLine(); + textOut.flushBuffer(); + charOut.flushBuffer(); + if (autoFlush) + out.flush(); } } catch (InterruptedIOException x) { @@ -861,15 +732,6 @@ private void newLine() { } } - private void implNewLine() throws IOException { - ensureOpen(); - textOut.newLine(); - textOut.flushBuffer(); - charOut.flushBuffer(); - if (autoFlush) - out.flush(); - } - /* Methods that do not terminate lines */ /** @@ -1327,17 +1189,11 @@ public PrintStream printf(Locale l, String format, Object ... args) { */ public PrintStream format(String format, Object ... args) { try { - if (lock != null) { - lock.lock(); - try { - implFormat(format, args); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - implFormat(format, args); - } + synchronized (this) { + ensureOpen(); + if ((formatter == null) || (formatter.locale() != Locale.getDefault(Locale.Category.FORMAT))) + formatter = new Formatter((Appendable) this); + formatter.format(Locale.getDefault(Locale.Category.FORMAT), format, args); } } catch (InterruptedIOException x) { Thread.currentThread().interrupt(); @@ -1347,13 +1203,6 @@ public PrintStream format(String format, Object ... args) { return this; } - private void implFormat(String format, Object ... args) throws IOException { - ensureOpen(); - if ((formatter == null) || (formatter.locale() != Locale.getDefault(Locale.Category.FORMAT))) - formatter = new Formatter((Appendable) this); - formatter.format(Locale.getDefault(Locale.Category.FORMAT), format, args); - } - /** * Writes a formatted string to this output stream using the specified * format string and arguments. @@ -1396,17 +1245,11 @@ private void implFormat(String format, Object ... args) throws IOException { */ public PrintStream format(Locale l, String format, Object ... args) { try { - if (lock != null) { - lock.lock(); - try { - implFormat(l, format, args); - } finally { - lock.unlock(); - } - } else { - synchronized (this) { - implFormat(l, format, args); - } + synchronized (this) { + ensureOpen(); + if ((formatter == null) || (formatter.locale() != l)) + formatter = new Formatter(this, l); + formatter.format(l, format, args); } } catch (InterruptedIOException x) { Thread.currentThread().interrupt(); @@ -1416,13 +1259,6 @@ public PrintStream format(Locale l, String format, Object ... args) { return this; } - private void implFormat(Locale l, String format, Object ... args) throws IOException { - ensureOpen(); - if ((formatter == null) || (formatter.locale() != l)) - formatter = new Formatter(this, l); - formatter.format(l, format, args); - } - /** * Appends the specified character sequence to this output stream. * @@ -1524,13 +1360,4 @@ public PrintStream append(char c) { public Charset charset() { return charset; } - - static { - SharedSecrets.setJavaIOCPrintStreamAccess(new JavaIOPrintStreamAccess() { - public Object lock(PrintStream ps) { - Object lock = ps.lock; - return (lock != null) ? lock : ps; - } - }); - } } diff --git a/src/java.base/share/classes/java/io/PrintWriter.java b/src/java.base/share/classes/java/io/PrintWriter.java index 55baa2e0a57..dd6deb75ab7 100644 --- a/src/java.base/share/classes/java/io/PrintWriter.java +++ b/src/java.base/share/classes/java/io/PrintWriter.java @@ -31,9 +31,6 @@ import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.UnsupportedCharsetException; -import jdk.internal.access.JavaIOPrintWriterAccess; -import jdk.internal.access.SharedSecrets; -import jdk.internal.misc.InternalLock; /** * Prints formatted representations of objects to a text-output stream. This @@ -377,30 +374,16 @@ private void ensureOpen() throws IOException { * @see #checkError() */ public void flush() { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); + synchronized (lock) { try { - implFlush(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - implFlush(); + ensureOpen(); + out.flush(); + } catch (IOException x) { + trouble = true; } } } - private void implFlush() { - try { - ensureOpen(); - out.flush(); - } catch (IOException x) { - trouble = true; - } - } - /** * Closes the stream and releases any system resources associated * with it. Closing a previously closed stream has no effect. @@ -408,32 +391,18 @@ private void implFlush() { * @see #checkError() */ public void close() { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); + synchronized (lock) { try { - implClose(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - implClose(); + if (out != null) { + out.close(); + out = null; + } + } catch (IOException x) { + trouble = true; } } } - private void implClose() { - try { - if (out != null) { - out.close(); - out = null; - } - } catch (IOException x) { - trouble = true; - } - } - /** * Flushes the stream if it's not closed and checks its error state. * @@ -487,32 +456,18 @@ protected void clearError() { * @param c int specifying a character to be written. */ public void write(int c) { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); + synchronized (lock) { try { - implWrite(c); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - implWrite(c); + ensureOpen(); + out.write(c); + } catch (InterruptedIOException x) { + Thread.currentThread().interrupt(); + } catch (IOException x) { + trouble = true; } } } - private void implWrite(int c) { - try { - ensureOpen(); - out.write(c); - } catch (InterruptedIOException x) { - Thread.currentThread().interrupt(); - } catch (IOException x) { - trouble = true; - } - } - /** * Writes A Portion of an array of characters. * @param buf Array of characters @@ -525,29 +480,15 @@ private void implWrite(int c) { * to throw an {@code IndexOutOfBoundsException} */ public void write(char[] buf, int off, int len) { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); + synchronized (lock) { try { - implWrite(buf, off, len); - } finally { - locker.unlock(); + ensureOpen(); + out.write(buf, off, len); + } catch (InterruptedIOException x) { + Thread.currentThread().interrupt(); + } catch (IOException x) { + trouble = true; } - } else { - synchronized (lock) { - implWrite(buf, off, len); - } - } - } - - private void implWrite(char[] buf, int off, int len) { - try { - ensureOpen(); - out.write(buf, off, len); - } catch (InterruptedIOException x) { - Thread.currentThread().interrupt(); - } catch (IOException x) { - trouble = true; } } @@ -572,29 +513,15 @@ public void write(char[] buf) { * to throw an {@code IndexOutOfBoundsException} */ public void write(String s, int off, int len) { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); + synchronized (lock) { try { - implWrite(s, off, len); - } finally { - locker.unlock(); + ensureOpen(); + out.write(s, off, len); + } catch (InterruptedIOException x) { + Thread.currentThread().interrupt(); + } catch (IOException x) { + trouble = true; } - } else { - synchronized (lock) { - implWrite(s, off, len); - } - } - } - - private void implWrite(String s, int off, int len) { - try { - ensureOpen(); - out.write(s, off, len); - } catch (InterruptedIOException x) { - Thread.currentThread().interrupt(); - } catch (IOException x) { - trouble = true; } } @@ -608,34 +535,20 @@ public void write(String s) { } private void newLine() { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); + synchronized (lock) { try { - implNewLine(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - implNewLine(); + ensureOpen(); + out.write(System.lineSeparator()); + if (autoFlush) + out.flush(); + } catch (InterruptedIOException x) { + Thread.currentThread().interrupt(); + } catch (IOException x) { + trouble = true; } } } - private void implNewLine() { - try { - ensureOpen(); - out.write(System.lineSeparator()); - if (autoFlush) - out.flush(); - } catch (InterruptedIOException x) { - Thread.currentThread().interrupt(); - } catch (IOException x) { - trouble = true; - } - } - /* Methods that do not terminate lines */ /** @@ -788,20 +701,9 @@ public void println() { * @param x the {@code boolean} value to be printed */ public void println(boolean x) { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - print(x); - println(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - print(x); - println(); - } + synchronized (lock) { + print(x); + println(); } } @@ -813,20 +715,9 @@ public void println(boolean x) { * @param x the {@code char} value to be printed */ public void println(char x) { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - print(x); - println(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - print(x); - println(); - } + synchronized (lock) { + print(x); + println(); } } @@ -838,20 +729,9 @@ public void println(char x) { * @param x the {@code int} value to be printed */ public void println(int x) { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - print(x); - println(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - print(x); - println(); - } + synchronized (lock) { + print(x); + println(); } } @@ -863,20 +743,9 @@ public void println(int x) { * @param x the {@code long} value to be printed */ public void println(long x) { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - print(x); - println(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - print(x); - println(); - } + synchronized (lock) { + print(x); + println(); } } @@ -888,20 +757,9 @@ public void println(long x) { * @param x the {@code float} value to be printed */ public void println(float x) { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - print(x); - println(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - print(x); - println(); - } + synchronized (lock) { + print(x); + println(); } } @@ -913,20 +771,9 @@ public void println(float x) { * @param x the {@code double} value to be printed */ public void println(double x) { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - print(x); - println(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - print(x); - println(); - } + synchronized (lock) { + print(x); + println(); } } @@ -938,20 +785,9 @@ public void println(double x) { * @param x the array of {@code char} values to be printed */ public void println(char[] x) { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - print(x); - println(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - print(x); - println(); - } + synchronized (lock) { + print(x); + println(); } } @@ -963,20 +799,9 @@ public void println(char[] x) { * @param x the {@code String} value to be printed */ public void println(String x) { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - print(x); - println(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - print(x); - println(); - } + synchronized (lock) { + print(x); + println(); } } @@ -991,20 +816,9 @@ public void println(String x) { */ public void println(Object x) { String s = String.valueOf(x); - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - print(s); - println(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - print(s); - println(); - } + synchronized (lock) { + print(s); + println(); } } @@ -1150,38 +964,24 @@ public PrintWriter printf(Locale l, String format, Object ... args) { * @since 1.5 */ public PrintWriter format(String format, Object ... args) { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); + synchronized (lock) { try { - implFormat(format, args); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - implFormat(format, args); + ensureOpen(); + if ((formatter == null) + || (formatter.locale() != Locale.getDefault())) + formatter = new Formatter(this); + formatter.format(Locale.getDefault(), format, args); + if (autoFlush) + out.flush(); + } catch (InterruptedIOException x) { + Thread.currentThread().interrupt(); + } catch (IOException x) { + trouble = true; } } return this; } - private void implFormat(String format, Object ... args) { - try { - ensureOpen(); - if ((formatter == null) - || (formatter.locale() != Locale.getDefault())) - formatter = new Formatter(this); - formatter.format(Locale.getDefault(), format, args); - if (autoFlush) - out.flush(); - } catch (InterruptedIOException x) { - Thread.currentThread().interrupt(); - } catch (IOException x) { - trouble = true; - } - } - /** * Writes a formatted string to this writer using the specified format * string and arguments. If automatic flushing is enabled, calls to this @@ -1224,37 +1024,23 @@ private void implFormat(String format, Object ... args) { * @since 1.5 */ public PrintWriter format(Locale l, String format, Object ... args) { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); + synchronized (lock) { try { - implFormat(l, format, args); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - implFormat(l, format, args); + ensureOpen(); + if ((formatter == null) || (formatter.locale() != l)) + formatter = new Formatter(this, l); + formatter.format(l, format, args); + if (autoFlush) + out.flush(); + } catch (InterruptedIOException x) { + Thread.currentThread().interrupt(); + } catch (IOException x) { + trouble = true; } } return this; } - private void implFormat(Locale l, String format, Object ... args) { - try { - ensureOpen(); - if ((formatter == null) || (formatter.locale() != l)) - formatter = new Formatter(this, l); - formatter.format(l, format, args); - if (autoFlush) - out.flush(); - } catch (InterruptedIOException x) { - Thread.currentThread().interrupt(); - } catch (IOException x) { - trouble = true; - } - } - /** * Appends the specified character sequence to this writer. * @@ -1346,12 +1132,4 @@ public PrintWriter append(char c) { write(c); return this; } - - static { - SharedSecrets.setJavaIOCPrintWriterAccess(new JavaIOPrintWriterAccess() { - public Object lock(PrintWriter pw) { - return pw.lock; - } - }); - } } diff --git a/src/java.base/share/classes/java/io/PushbackInputStream.java b/src/java.base/share/classes/java/io/PushbackInputStream.java index 0c74205ba0e..5aa0e133df9 100644 --- a/src/java.base/share/classes/java/io/PushbackInputStream.java +++ b/src/java.base/share/classes/java/io/PushbackInputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1994, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1994, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,6 @@ import java.util.Arrays; import java.util.Objects; -import jdk.internal.misc.InternalLock; /** * A {@code PushbackInputStream} adds @@ -54,10 +53,6 @@ * @since 1.0 */ public class PushbackInputStream extends FilterInputStream { - - // initialized to null when PushbackInputStream is sub-classed - private final InternalLock closeLock; - /** * The pushback buffer. * @since 1.1 @@ -101,13 +96,6 @@ public PushbackInputStream(InputStream in, int size) { } this.buf = new byte[size]; this.pos = size; - - // use monitors when PushbackInputStream is sub-classed - if (getClass() == PushbackInputStream.class) { - closeLock = InternalLock.newLockOrNull(); - } else { - closeLock = null; - } } /** @@ -386,27 +374,12 @@ public void reset() throws IOException { * * @throws IOException if an I/O error occurs. */ - public void close() throws IOException { - if (closeLock != null) { - closeLock.lock(); - try { - implClose(); - } finally { - closeLock.unlock(); - } - } else { - synchronized (this) { - implClose(); - } - } - } - - private void implClose() throws IOException { - if (in != null) { - in.close(); - in = null; - buf = null; - } + public synchronized void close() throws IOException { + if (in == null) + return; + in.close(); + in = null; + buf = null; } @Override diff --git a/src/java.base/share/classes/java/io/Reader.java b/src/java.base/share/classes/java/io/Reader.java index 9fca28a3a96..1654156bee1 100644 --- a/src/java.base/share/classes/java/io/Reader.java +++ b/src/java.base/share/classes/java/io/Reader.java @@ -28,7 +28,6 @@ import java.nio.CharBuffer; import java.nio.ReadOnlyBufferException; import java.util.Objects; -import jdk.internal.misc.InternalLock; /** * Abstract class for reading character streams. The only methods that a @@ -283,21 +282,6 @@ protected Reader(Object lock) { this.lock = lock; } - /** - * For use by BufferedReader to create a character-stream reader that uses an - * internal lock when BufferedReader is not extended and the given reader is - * trusted, otherwise critical sections will synchronize on the given reader. - */ - Reader(Reader in) { - Class clazz = in.getClass(); - if (getClass() == BufferedReader.class && - (clazz == InputStreamReader.class || clazz == FileReader.class)) { - this.lock = InternalLock.newLockOr(in); - } else { - this.lock = in; - } - } - /** * Attempts to read characters into the specified character buffer. * The buffer is used as a repository of characters as-is: the only @@ -429,33 +413,19 @@ public int read(char[] cbuf) throws IOException { public long skip(long n) throws IOException { if (n < 0L) throw new IllegalArgumentException("skip value is negative"); - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - return implSkip(n); - } finally { - locker.unlock(); + synchronized (lock) { + int nn = (int) Math.min(n, maxSkipBufferSize); + if ((skipBuffer == null) || (skipBuffer.length < nn)) + skipBuffer = new char[nn]; + long r = n; + while (r > 0) { + int nc = read(skipBuffer, 0, (int)Math.min(r, nn)); + if (nc == -1) + break; + r -= nc; } - } else { - synchronized (lock) { - return implSkip(n); - } - } - } - - private long implSkip(long n) throws IOException { - int nn = (int) Math.min(n, maxSkipBufferSize); - if ((skipBuffer == null) || (skipBuffer.length < nn)) - skipBuffer = new char[nn]; - long r = n; - while (r > 0) { - int nc = read(skipBuffer, 0, (int)Math.min(r, nn)); - if (nc == -1) - break; - r -= nc; + return n - r; } - return n - r; } /** diff --git a/src/java.base/share/classes/java/io/Writer.java b/src/java.base/share/classes/java/io/Writer.java index 62fe6b053e5..433a116a4bb 100644 --- a/src/java.base/share/classes/java/io/Writer.java +++ b/src/java.base/share/classes/java/io/Writer.java @@ -26,7 +26,6 @@ package java.io; import java.util.Objects; -import jdk.internal.misc.InternalLock; /** * Abstract class for writing to character streams. The only methods that a @@ -162,21 +161,6 @@ protected Writer() { this.lock = this; } - /** - * For use by BufferedWriter to create a character-stream writer that uses an - * internal lock when BufferedWriter is not extended and the given writer is - * trusted, otherwise critical sections will synchronize on the given writer. - */ - Writer(Writer writer) { - Class clazz = writer.getClass(); - if (getClass() == BufferedWriter.class && - (clazz == OutputStreamWriter.class || clazz == FileWriter.class)) { - this.lock = InternalLock.newLockOr(writer); - } else { - this.lock = writer; - } - } - /** * Creates a new character-stream writer whose critical sections will * synchronize on the given object. @@ -206,29 +190,15 @@ protected Writer(Object lock) { * If an I/O error occurs */ public void write(int c) throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - implWrite(c); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - implWrite(c); + synchronized (lock) { + if (writeBuffer == null){ + writeBuffer = new char[WRITE_BUFFER_SIZE]; } + writeBuffer[0] = (char) c; + write(writeBuffer, 0, 1); } } - private void implWrite(int c) throws IOException { - if (writeBuffer == null){ - writeBuffer = new char[WRITE_BUFFER_SIZE]; - } - writeBuffer[0] = (char) c; - write(writeBuffer, 0, 1); - } - /** * Writes an array of characters. * @@ -305,33 +275,19 @@ public void write(String str) throws IOException { * If an I/O error occurs */ public void write(String str, int off, int len) throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - implWrite(str, off, len); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - implWrite(str, off, len); - } - } - } - - private void implWrite(String str, int off, int len) throws IOException { - char cbuf[]; - if (len <= WRITE_BUFFER_SIZE) { - if (writeBuffer == null) { - writeBuffer = new char[WRITE_BUFFER_SIZE]; + synchronized (lock) { + char cbuf[]; + if (len <= WRITE_BUFFER_SIZE) { + if (writeBuffer == null) { + writeBuffer = new char[WRITE_BUFFER_SIZE]; + } + cbuf = writeBuffer; + } else { // Don't permanently allocate very large buffers. + cbuf = new char[len]; } - cbuf = writeBuffer; - } else { // Don't permanently allocate very large buffers. - cbuf = new char[len]; + str.getChars(off, (off + len), cbuf, 0); + write(cbuf, 0, len); } - str.getChars(off, (off + len), cbuf, 0); - write(cbuf, 0, len); } /** diff --git a/src/java.base/share/classes/java/lang/Class.java b/src/java.base/share/classes/java/lang/Class.java index bbf539beeea..d9a083533a9 100644 --- a/src/java.base/share/classes/java/lang/Class.java +++ b/src/java.base/share/classes/java/lang/Class.java @@ -226,6 +226,11 @@ public final class Class implements java.io.Serializable, private static native void registerNatives(); static { + runtimeSetup(); + } + + // Called from JVM when loading an AOT cache + private static void runtimeSetup() { registerNatives(); } @@ -3474,6 +3479,15 @@ private static ReflectionFactory getReflectionFactory() { } private static ReflectionFactory reflectionFactory; + /** + * When CDS is enabled, the Class class may be aot-initialized. However, + * we can't archive reflectionFactory, so we reset it to null, so it + * will be allocated again at runtime. + */ + private static void resetArchivedStates() { + reflectionFactory = null; + } + /** * Returns the elements of this enum class or null if this * Class object does not represent an enum class. diff --git a/src/java.base/share/classes/java/lang/ClassLoader.java b/src/java.base/share/classes/java/lang/ClassLoader.java index 85fc315c767..55341635d8a 100644 --- a/src/java.base/share/classes/java/lang/ClassLoader.java +++ b/src/java.base/share/classes/java/lang/ClassLoader.java @@ -64,7 +64,6 @@ import jdk.internal.reflect.CallerSensitiveAdapter; import jdk.internal.reflect.Reflection; import jdk.internal.util.StaticProperty; -import sun.security.util.SecurityConstants; /** * A class loader is an object that is responsible for loading classes. The @@ -357,12 +356,6 @@ private static Void checkCreateClassLoader(String name) { if (name != null && name.isEmpty()) { throw new IllegalArgumentException("name must be non-empty or null"); } - - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkCreateClassLoader(); - } return null; } @@ -1735,18 +1728,7 @@ public static InputStream getSystemResourceAsStream(String name) { * * @since 1.2 */ - @CallerSensitive public final ClassLoader getParent() { - if (parent == null) - return null; - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - // Check access to the parent class loader - // If the caller's class loader is same as this class loader, - // permission check is performed. - checkClassLoaderPermission(parent, Reflection.getCallerClass()); - } return parent; } @@ -1774,15 +1756,8 @@ public final Module getUnnamedModule() { * * @since 9 */ - @CallerSensitive public static ClassLoader getPlatformClassLoader() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - ClassLoader loader = getBuiltinPlatformClassLoader(); - if (sm != null) { - checkClassLoaderPermission(loader, Reflection.getCallerClass()); - } - return loader; + return getBuiltinPlatformClassLoader(); } /** @@ -1853,7 +1828,6 @@ public static ClassLoader getPlatformClassLoader() { * underlying cause of the error can be retrieved via the * {@link Throwable#getCause()} method. */ - @CallerSensitive public static ClassLoader getSystemClassLoader() { switch (VM.initLevel()) { case 0: @@ -1867,11 +1841,6 @@ public static ClassLoader getSystemClassLoader() { default: // system fully initialized assert VM.isBooted() && scl != null; - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - checkClassLoaderPermission(scl, Reflection.getCallerClass()); - } return scl; } } @@ -1902,8 +1871,6 @@ static synchronized ClassLoader initSystemClassLoader() { } ClassLoader builtinLoader = getBuiltinAppClassLoader(); - - // All are privileged frames. No need to call doPrivileged. String cn = System.getProperty("java.system.class.loader"); if (cn != null) { try { @@ -1930,36 +1897,6 @@ static synchronized ClassLoader initSystemClassLoader() { return scl; } - // Returns true if the specified class loader can be found in this class - // loader's delegation chain. - boolean isAncestor(ClassLoader cl) { - ClassLoader acl = this; - do { - acl = acl.parent; - if (cl == acl) { - return true; - } - } while (acl != null); - return false; - } - - // Tests if class loader access requires "getClassLoader" permission - // check. A class loader 'from' can access class loader 'to' if - // class loader 'from' is same as class loader 'to' or an ancestor - // of 'to'. The class loader in a system domain can access - // any class loader. - private static boolean needsClassLoaderPermissionCheck(ClassLoader from, - ClassLoader to) - { - if (from == to) - return false; - - if (from == null) - return false; - - return !to.isAncestor(from); - } - // Returns the class's class loader, or null if none. static ClassLoader getClassLoader(Class caller) { // This can be null if the VM is requesting it @@ -1970,23 +1907,6 @@ static ClassLoader getClassLoader(Class caller) { return caller.getClassLoader0(); } - /* - * Checks RuntimePermission("getClassLoader") permission - * if caller's class loader is not null and caller's class loader - * is not the same as or an ancestor of the given cl argument. - */ - static void checkClassLoaderPermission(ClassLoader cl, Class caller) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - // caller can be null if the VM is requesting it - ClassLoader ccl = getClassLoader(caller); - if (needsClassLoaderPermissionCheck(ccl, cl)) { - sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); - } - } - } - // The system class loader // @GuardedBy("ClassLoader.class") private static volatile ClassLoader scl; diff --git a/src/java.base/share/classes/java/lang/Throwable.java b/src/java.base/share/classes/java/lang/Throwable.java index 275961a9a9f..8c0ce29dbee 100644 --- a/src/java.base/share/classes/java/lang/Throwable.java +++ b/src/java.base/share/classes/java/lang/Throwable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1994, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1994, 2024, Oracle and/or its affiliates. All rights reserved. * 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,9 +27,7 @@ import java.io.*; import java.util.*; -import jdk.internal.access.SharedSecrets; import jdk.internal.event.ThrowableTracer; -import jdk.internal.misc.InternalLock; /** * The {@code Throwable} class is the superclass of all errors and @@ -689,39 +687,27 @@ public void printStackTrace(PrintStream s) { } private void printStackTrace(PrintStreamOrWriter s) { - Object lock = s.lock(); - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - lockedPrintStackTrace(s); - } finally { - locker.unlock(); - } - } else synchronized (lock) { - lockedPrintStackTrace(s); - } - } - - private void lockedPrintStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. Set dejaVu = Collections.newSetFromMap(new IdentityHashMap<>()); dejaVu.add(this); - // Print our stack trace - s.println(this); - StackTraceElement[] trace = getOurStackTrace(); - for (StackTraceElement traceElement : trace) - s.println("\tat " + traceElement); + synchronized(s.lock()) { + // Print our stack trace + s.println(this); + StackTraceElement[] trace = getOurStackTrace(); + for (StackTraceElement traceElement : trace) + s.println("\tat " + traceElement); - // Print suppressed exceptions, if any - for (Throwable se : getSuppressed()) - se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu); + // Print suppressed exceptions, if any + for (Throwable se : getSuppressed()) + se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu); - // Print cause, if any - Throwable ourCause = getCause(); - if (ourCause != null) - ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu); + // Print cause, if any + Throwable ourCause = getCause(); + if (ourCause != null) + ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu); + } } /** @@ -733,7 +719,7 @@ private void printEnclosedStackTrace(PrintStreamOrWriter s, String caption, String prefix, Set dejaVu) { - assert s.isLockedByCurrentThread(); + assert Thread.holdsLock(s.lock()); if (dejaVu.contains(this)) { s.println(prefix + caption + "[CIRCULAR REFERENCE: " + this + "]"); } else { @@ -785,15 +771,6 @@ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter */ abstract Object lock(); - boolean isLockedByCurrentThread() { - Object lock = lock(); - if (lock instanceof InternalLock locker) { - return locker.isHeldByCurrentThread(); - } else { - return Thread.holdsLock(lock); - } - } - /** Prints the specified string as a line on this StreamOrWriter */ abstract void println(Object o); } @@ -806,7 +783,7 @@ private static class WrappedPrintStream extends PrintStreamOrWriter { } Object lock() { - return SharedSecrets.getJavaIOPrintStreamAccess().lock(printStream); + return printStream; } void println(Object o) { @@ -822,7 +799,7 @@ private static class WrappedPrintWriter extends PrintStreamOrWriter { } Object lock() { - return SharedSecrets.getJavaIOPrintWriterAccess().lock(printWriter); + return printWriter; } void println(Object o) { diff --git a/src/java.base/share/classes/java/lang/classfile/AccessFlags.java b/src/java.base/share/classes/java/lang/classfile/AccessFlags.java index 4abe17c1cf5..b1d026f52e4 100644 --- a/src/java.base/share/classes/java/lang/classfile/AccessFlags.java +++ b/src/java.base/share/classes/java/lang/classfile/AccessFlags.java @@ -28,16 +28,14 @@ import java.util.Set; import jdk.internal.classfile.impl.AccessFlagsImpl; -import jdk.internal.javac.PreviewFeature; /** * Models the access flags for a class, method, or field. Delivered as a * {@link ClassElement}, {@link FieldElement}, or {@link MethodElement} * when traversing the corresponding model type. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface AccessFlags extends ClassElement, MethodElement, FieldElement permits AccessFlagsImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/Annotation.java b/src/java.base/share/classes/java/lang/classfile/Annotation.java index 4f222084cb7..98b6ea783d5 100644 --- a/src/java.base/share/classes/java/lang/classfile/Annotation.java +++ b/src/java.base/share/classes/java/lang/classfile/Annotation.java @@ -35,7 +35,6 @@ import jdk.internal.classfile.impl.AnnotationImpl; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models an {@code annotation} structure (JVMS {@jvms 4.7.16}) or part of a {@code @@ -63,9 +62,8 @@ * @see RuntimeVisibleParameterAnnotationsAttribute * @see RuntimeInvisibleParameterAnnotationsAttribute * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface Annotation permits AnnotationImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/AnnotationElement.java b/src/java.base/share/classes/java/lang/classfile/AnnotationElement.java index 7c4283c49bf..4381bb9733a 100644 --- a/src/java.base/share/classes/java/lang/classfile/AnnotationElement.java +++ b/src/java.base/share/classes/java/lang/classfile/AnnotationElement.java @@ -29,7 +29,6 @@ import jdk.internal.classfile.impl.AnnotationImpl; import jdk.internal.classfile.impl.TemporaryConstantPool; -import jdk.internal.javac.PreviewFeature; /** * Models an element-value pair in the {@code element_value_pairs} @@ -43,9 +42,8 @@ * @see Annotation * @see AnnotationValue * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface AnnotationElement permits AnnotationImpl.AnnotationElementImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/AnnotationValue.java b/src/java.base/share/classes/java/lang/classfile/AnnotationValue.java index e1e91f2c9ed..8e92ef59a50 100644 --- a/src/java.base/share/classes/java/lang/classfile/AnnotationValue.java +++ b/src/java.base/share/classes/java/lang/classfile/AnnotationValue.java @@ -33,7 +33,6 @@ import jdk.internal.classfile.impl.AnnotationImpl; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; import static java.util.Objects.requireNonNull; @@ -48,18 +47,16 @@ * @see AnnotationElement * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface AnnotationValue { /** * Models an annotation value of an element-value pair. * The {@linkplain #tag tag} of this value is {@value TAG_ANNOTATION}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface OfAnnotation extends AnnotationValue permits AnnotationImpl.OfAnnotationImpl { /** {@return the annotation value} */ @@ -70,9 +67,8 @@ sealed interface OfAnnotation extends AnnotationValue * Models an array value of an element-value pair. * The {@linkplain #tag tag} of this value is {@value TAG_ARRAY}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface OfArray extends AnnotationValue permits AnnotationImpl.OfArrayImpl { /** @@ -91,9 +87,8 @@ sealed interface OfArray extends AnnotationValue * Models a constant value of an element-value pair. * * @sealedGraph - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface OfConstant extends AnnotationValue { /** * {@return the constant pool entry backing this constant element} @@ -128,9 +123,8 @@ sealed interface OfConstant extends AnnotationValue { * Models a string value of an element-value pair. * The {@linkplain #tag tag} of this value is {@value TAG_STRING}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface OfString extends OfConstant permits AnnotationImpl.OfStringImpl { /** {@return the backing UTF8 entry} */ @@ -156,9 +150,8 @@ default String resolvedValue() { * Models a double value of an element-value pair. * The {@linkplain #tag tag} of this value is {@value TAG_DOUBLE}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface OfDouble extends OfConstant permits AnnotationImpl.OfDoubleImpl { /** {@return the backing double entry} */ @@ -184,9 +177,8 @@ default Double resolvedValue() { * Models a float value of an element-value pair. * The {@linkplain #tag tag} of this value is {@value TAG_FLOAT}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface OfFloat extends OfConstant permits AnnotationImpl.OfFloatImpl { /** {@return the backing float entry} */ @@ -212,9 +204,8 @@ default Float resolvedValue() { * Models a long value of an element-value pair. * The {@linkplain #tag tag} of this value is {@value TAG_LONG}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface OfLong extends OfConstant permits AnnotationImpl.OfLongImpl { /** {@return the backing long entry} */ @@ -240,9 +231,8 @@ default Long resolvedValue() { * Models an int value of an element-value pair. * The {@linkplain #tag tag} of this value is {@value TAG_INT}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface OfInt extends OfConstant permits AnnotationImpl.OfIntImpl { /** {@return the backing integer entry} */ @@ -268,9 +258,8 @@ default Integer resolvedValue() { * Models a short value of an element-value pair. * The {@linkplain #tag tag} of this value is {@value TAG_SHORT}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface OfShort extends OfConstant permits AnnotationImpl.OfShortImpl { /** {@return the backing integer entry} */ @@ -299,9 +288,8 @@ default Short resolvedValue() { * Models a char value of an element-value pair. * The {@linkplain #tag tag} of this value is {@value TAG_CHAR}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface OfChar extends OfConstant permits AnnotationImpl.OfCharImpl { /** {@return the backing integer entry} */ @@ -330,9 +318,8 @@ default Character resolvedValue() { * Models a byte value of an element-value pair. * The {@linkplain #tag tag} of this value is {@value TAG_BYTE}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface OfByte extends OfConstant permits AnnotationImpl.OfByteImpl { /** {@return the backing integer entry} */ @@ -361,9 +348,8 @@ default Byte resolvedValue() { * Models a boolean value of an element-value pair. * The {@linkplain #tag tag} of this value is {@value TAG_BOOLEAN}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface OfBoolean extends OfConstant permits AnnotationImpl.OfBooleanImpl { /** {@return the backing integer entry} */ @@ -392,9 +378,8 @@ default Boolean resolvedValue() { * Models a class value of an element-value pair. * The {@linkplain #tag tag} of this value is {@value TAG_CLASS}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface OfClass extends AnnotationValue permits AnnotationImpl.OfClassImpl { /** {@return the class descriptor string} */ @@ -410,9 +395,8 @@ default ClassDesc classSymbol() { * Models an enum value of an element-value pair. * The {@linkplain #tag tag} of this value is {@value TAG_ENUM}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface OfEnum extends AnnotationValue permits AnnotationImpl.OfEnumImpl { /** {@return the enum class descriptor string} */ diff --git a/src/java.base/share/classes/java/lang/classfile/Attribute.java b/src/java.base/share/classes/java/lang/classfile/Attribute.java index f47f641ab5e..7126a63c6da 100644 --- a/src/java.base/share/classes/java/lang/classfile/Attribute.java +++ b/src/java.base/share/classes/java/lang/classfile/Attribute.java @@ -25,10 +25,10 @@ package java.lang.classfile; import java.lang.classfile.attribute.*; +import java.lang.classfile.constantpool.Utf8Entry; import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models a classfile attribute (JVMS {@jvms 4.7}). Many, though not all, subtypes of @@ -41,9 +41,8 @@ * @param the attribute type * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface Attribute> extends ClassFileElement permits AnnotationDefaultAttribute, BootstrapMethodsAttribute, @@ -65,7 +64,7 @@ public sealed interface Attribute> /** * {@return the name of the attribute} */ - String attributeName(); + Utf8Entry attributeName(); /** * {@return the {@link AttributeMapper} associated with this attribute} diff --git a/src/java.base/share/classes/java/lang/classfile/AttributeMapper.java b/src/java.base/share/classes/java/lang/classfile/AttributeMapper.java index 0b46055423a..993da9aa4a8 100644 --- a/src/java.base/share/classes/java/lang/classfile/AttributeMapper.java +++ b/src/java.base/share/classes/java/lang/classfile/AttributeMapper.java @@ -24,8 +24,6 @@ */ package java.lang.classfile; -import jdk.internal.javac.PreviewFeature; - /** * Bidirectional mapper between the classfile representation of an attribute and * how that attribute is modeled in the API. The attribute mapper is used @@ -37,17 +35,15 @@ * CustomAttribute}. * @param the attribute type * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public interface AttributeMapper> { /** * Attribute stability indicator * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) enum AttributeStability { /** diff --git a/src/java.base/share/classes/java/lang/classfile/AttributedElement.java b/src/java.base/share/classes/java/lang/classfile/AttributedElement.java index fb1bf817480..478ad1e3f0a 100644 --- a/src/java.base/share/classes/java/lang/classfile/AttributedElement.java +++ b/src/java.base/share/classes/java/lang/classfile/AttributedElement.java @@ -31,7 +31,6 @@ import java.util.Optional; import jdk.internal.classfile.impl.AbstractUnboundModel; -import jdk.internal.javac.PreviewFeature; import static java.util.Objects.requireNonNull; @@ -40,9 +39,8 @@ * as a class, field, method, code attribute, or record component. * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface AttributedElement extends ClassFileElement permits ClassModel, CodeModel, FieldModel, MethodModel, RecordComponentInfo, AbstractUnboundModel { diff --git a/src/java.base/share/classes/java/lang/classfile/Attributes.java b/src/java.base/share/classes/java/lang/classfile/Attributes.java index b790894a9af..7f32aa7d064 100644 --- a/src/java.base/share/classes/java/lang/classfile/Attributes.java +++ b/src/java.base/share/classes/java/lang/classfile/Attributes.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,6 @@ import java.lang.classfile.AttributeMapper.AttributeStability; import java.lang.classfile.attribute.*; import jdk.internal.classfile.impl.AbstractAttributeMapper.*; -import jdk.internal.javac.PreviewFeature; /** * Attribute mappers for standard classfile attributes. @@ -89,9 +88,8 @@ * * @see AttributeMapper * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public final class Attributes { /** AnnotationDefault */ @@ -210,7 +208,6 @@ private Attributes() { /** * {@return Attribute mapper for the {@code AnnotationDefault} attribute} - * @since 23 */ public static AttributeMapper annotationDefault() { return AnnotationDefaultMapper.INSTANCE; @@ -218,7 +215,6 @@ public static AttributeMapper annotationDefault() { /** * {@return Attribute mapper for the {@code BootstrapMethods} attribute} - * @since 23 */ public static AttributeMapper bootstrapMethods() { return BootstrapMethodsMapper.INSTANCE; @@ -227,7 +223,6 @@ public static AttributeMapper bootstrapMethods() { /** * {@return Attribute mapper for the {@code CharacterRangeTable} attribute} * The mapper permits multiple instances in a given location. - * @since 23 */ public static AttributeMapper characterRangeTable() { return CharacterRangeTableMapper.INSTANCE; @@ -235,7 +230,6 @@ public static AttributeMapper characterRangeTable( /** * {@return Attribute mapper for the {@code Code} attribute} - * @since 23 */ public static AttributeMapper code() { return CodeMapper.INSTANCE; @@ -243,7 +237,6 @@ public static AttributeMapper code() { /** * {@return Attribute mapper for the {@code CompilationID} attribute} - * @since 23 */ public static AttributeMapper compilationId() { return CompilationIDMapper.INSTANCE; @@ -251,7 +244,6 @@ public static AttributeMapper compilationId() { /** * {@return Attribute mapper for the {@code ConstantValue} attribute} - * @since 23 */ public static AttributeMapper constantValue() { return ConstantValueMapper.INSTANCE; @@ -260,7 +252,6 @@ public static AttributeMapper constantValue() { /** * {@return Attribute mapper for the {@code Deprecated} attribute} * The mapper permits multiple instances in a given location. - * @since 23 */ public static AttributeMapper deprecated() { return DeprecatedMapper.INSTANCE; @@ -268,7 +259,6 @@ public static AttributeMapper deprecated() { /** * {@return Attribute mapper for the {@code EnclosingMethod} attribute} - * @since 23 */ public static AttributeMapper enclosingMethod() { return EnclosingMethodMapper.INSTANCE; @@ -276,7 +266,6 @@ public static AttributeMapper enclosingMethod() { /** * {@return Attribute mapper for the {@code Exceptions} attribute} - * @since 23 */ public static AttributeMapper exceptions() { return ExceptionsMapper.INSTANCE; @@ -284,7 +273,6 @@ public static AttributeMapper exceptions() { /** * {@return Attribute mapper for the {@code InnerClasses} attribute} - * @since 23 */ public static AttributeMapper innerClasses() { return InnerClassesMapper.INSTANCE; @@ -293,7 +281,6 @@ public static AttributeMapper innerClasses() { /** * {@return Attribute mapper for the {@code LineNumberTable} attribute} * The mapper permits multiple instances in a given location. - * @since 23 */ public static AttributeMapper lineNumberTable() { return LineNumberTableMapper.INSTANCE; @@ -310,7 +297,6 @@ public static AttributeMapper loadableDescriptors( /** * {@return Attribute mapper for the {@code LocalVariableTable} attribute} * The mapper permits multiple instances in a given location. - * @since 23 */ public static AttributeMapper localVariableTable() { return LocalVariableTableMapper.INSTANCE; @@ -319,7 +305,6 @@ public static AttributeMapper localVariableTable() /** * {@return Attribute mapper for the {@code LocalVariableTypeTable} attribute} * The mapper permits multiple instances in a given location. - * @since 23 */ public static AttributeMapper localVariableTypeTable() { return LocalVariableTypeTableMapper.INSTANCE; @@ -327,7 +312,6 @@ public static AttributeMapper localVariableType /** * {@return Attribute mapper for the {@code MethodParameters} attribute} - * @since 23 */ public static AttributeMapper methodParameters() { return MethodParametersMapper.INSTANCE; @@ -335,7 +319,6 @@ public static AttributeMapper methodParameters() { /** * {@return Attribute mapper for the {@code Module} attribute} - * @since 23 */ public static AttributeMapper module() { return ModuleMapper.INSTANCE; @@ -343,7 +326,6 @@ public static AttributeMapper module() { /** * {@return Attribute mapper for the {@code ModuleHashes} attribute} - * @since 23 */ public static AttributeMapper moduleHashes() { return ModuleHashesMapper.INSTANCE; @@ -351,7 +333,6 @@ public static AttributeMapper moduleHashes() { /** * {@return Attribute mapper for the {@code ModuleMainClass} attribute} - * @since 23 */ public static AttributeMapper moduleMainClass() { return ModuleMainClassMapper.INSTANCE; @@ -359,7 +340,6 @@ public static AttributeMapper moduleMainClass() { /** * {@return Attribute mapper for the {@code ModulePackages} attribute} - * @since 23 */ public static AttributeMapper modulePackages() { return ModulePackagesMapper.INSTANCE; @@ -367,7 +347,6 @@ public static AttributeMapper modulePackages() { /** * {@return Attribute mapper for the {@code ModuleResolution} attribute} - * @since 23 */ public static AttributeMapper moduleResolution() { return ModuleResolutionMapper.INSTANCE; @@ -375,7 +354,6 @@ public static AttributeMapper moduleResolution() { /** * {@return Attribute mapper for the {@code ModuleTarget} attribute} - * @since 23 */ public static AttributeMapper moduleTarget() { return ModuleTargetMapper.INSTANCE; @@ -383,7 +361,6 @@ public static AttributeMapper moduleTarget() { /** * {@return Attribute mapper for the {@code NestHost} attribute} - * @since 23 */ public static AttributeMapper nestHost() { return NestHostMapper.INSTANCE; @@ -391,7 +368,6 @@ public static AttributeMapper nestHost() { /** * {@return Attribute mapper for the {@code NestMembers} attribute} - * @since 23 */ public static AttributeMapper nestMembers() { return NestMembersMapper.INSTANCE; @@ -399,7 +375,6 @@ public static AttributeMapper nestMembers() { /** * {@return Attribute mapper for the {@code PermittedSubclasses} attribute} - * @since 23 */ public static AttributeMapper permittedSubclasses() { return PermittedSubclassesMapper.INSTANCE; @@ -407,7 +382,6 @@ public static AttributeMapper permittedSubclasses( /** * {@return Attribute mapper for the {@code Record} attribute} - * @since 23 */ public static AttributeMapper record() { return RecordMapper.INSTANCE; @@ -415,7 +389,6 @@ public static AttributeMapper record() { /** * {@return Attribute mapper for the {@code RuntimeInvisibleAnnotations} attribute} - * @since 23 */ public static AttributeMapper runtimeInvisibleAnnotations() { return RuntimeInvisibleAnnotationsMapper.INSTANCE; @@ -423,7 +396,6 @@ public static AttributeMapper runtimeInvis /** * {@return Attribute mapper for the {@code RuntimeInvisibleParameterAnnotations} attribute} - * @since 23 */ public static AttributeMapper runtimeInvisibleParameterAnnotations() { return RuntimeInvisibleParameterAnnotationsMapper.INSTANCE; @@ -431,7 +403,6 @@ public static AttributeMapper run /** * {@return Attribute mapper for the {@code RuntimeInvisibleTypeAnnotations} attribute} - * @since 23 */ public static AttributeMapper runtimeInvisibleTypeAnnotations() { return RuntimeInvisibleTypeAnnotationsMapper.INSTANCE; @@ -439,7 +410,6 @@ public static AttributeMapper runtimeI /** * {@return Attribute mapper for the {@code RuntimeVisibleAnnotations} attribute} - * @since 23 */ public static AttributeMapper runtimeVisibleAnnotations() { return RuntimeVisibleAnnotationsMapper.INSTANCE; @@ -447,7 +417,6 @@ public static AttributeMapper runtimeVisible /** * {@return Attribute mapper for the {@code RuntimeVisibleParameterAnnotations} attribute} - * @since 23 */ public static AttributeMapper runtimeVisibleParameterAnnotations() { return RuntimeVisibleParameterAnnotationsMapper.INSTANCE; @@ -455,7 +424,6 @@ public static AttributeMapper runti /** * {@return Attribute mapper for the {@code RuntimeVisibleTypeAnnotations} attribute} - * @since 23 */ public static AttributeMapper runtimeVisibleTypeAnnotations() { return RuntimeVisibleTypeAnnotationsMapper.INSTANCE; @@ -463,7 +431,6 @@ public static AttributeMapper runtimeVis /** * {@return Attribute mapper for the {@code Signature} attribute} - * @since 23 */ public static AttributeMapper signature() { return SignatureMapper.INSTANCE; @@ -471,7 +438,6 @@ public static AttributeMapper signature() { /** * {@return Attribute mapper for the {@code SourceDebugExtension} attribute} - * @since 23 */ public static AttributeMapper sourceDebugExtension() { return SourceDebugExtensionMapper.INSTANCE; @@ -479,7 +445,6 @@ public static AttributeMapper sourceDebugExtensio /** * {@return Attribute mapper for the {@code SourceFile} attribute} - * @since 23 */ public static AttributeMapper sourceFile() { return SourceFileMapper.INSTANCE; @@ -487,7 +452,6 @@ public static AttributeMapper sourceFile() { /** * {@return Attribute mapper for the {@code SourceID} attribute} - * @since 23 */ public static AttributeMapper sourceId() { return SourceIDMapper.INSTANCE; @@ -495,7 +459,6 @@ public static AttributeMapper sourceId() { /** * {@return Attribute mapper for the {@code StackMapTable} attribute} - * @since 23 */ public static AttributeMapper stackMapTable() { return StackMapTableMapper.INSTANCE; @@ -504,7 +467,6 @@ public static AttributeMapper stackMapTable() { /** * {@return Attribute mapper for the {@code Synthetic} attribute} * The mapper permits multiple instances in a given location. - * @since 23 */ public static AttributeMapper synthetic() { return SyntheticMapper.INSTANCE; diff --git a/src/java.base/share/classes/java/lang/classfile/BootstrapMethodEntry.java b/src/java.base/share/classes/java/lang/classfile/BootstrapMethodEntry.java index 964976e0fd5..1608e77bee6 100644 --- a/src/java.base/share/classes/java/lang/classfile/BootstrapMethodEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/BootstrapMethodEntry.java @@ -31,7 +31,6 @@ import java.util.List; import jdk.internal.classfile.impl.BootstrapMethodEntryImpl; -import jdk.internal.javac.PreviewFeature; /** * Models an entry in the bootstrap method table. The bootstrap method table @@ -39,9 +38,8 @@ * the {@link ConstantPool}, since the bootstrap method table is logically * part of the constant pool. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface BootstrapMethodEntry permits BootstrapMethodEntryImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/BufWriter.java b/src/java.base/share/classes/java/lang/classfile/BufWriter.java index d60447c1388..c6779583eb1 100644 --- a/src/java.base/share/classes/java/lang/classfile/BufWriter.java +++ b/src/java.base/share/classes/java/lang/classfile/BufWriter.java @@ -29,16 +29,14 @@ import java.lang.classfile.constantpool.PoolEntry; import jdk.internal.classfile.impl.BufWriterImpl; -import jdk.internal.javac.PreviewFeature; /** * Supports writing portions of a classfile to a growable buffer. Methods * are provided to write various standard entities (e.g., {@code u2}, {@code u4}) * to the end of the buffer, as well as to create constant pool entries. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface BufWriter permits BufWriterImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/ClassBuilder.java b/src/java.base/share/classes/java/lang/classfile/ClassBuilder.java index 71f1cc53194..996c63ddd01 100644 --- a/src/java.base/share/classes/java/lang/classfile/ClassBuilder.java +++ b/src/java.base/share/classes/java/lang/classfile/ClassBuilder.java @@ -39,7 +39,6 @@ import jdk.internal.classfile.impl.ChainedClassBuilder; import jdk.internal.classfile.impl.DirectClassBuilder; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * A builder for classfiles. Builders are not created directly; they are passed @@ -50,9 +49,8 @@ * * @see ClassTransform * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ClassBuilder extends ClassFileBuilder permits ChainedClassBuilder, DirectClassBuilder { diff --git a/src/java.base/share/classes/java/lang/classfile/ClassElement.java b/src/java.base/share/classes/java/lang/classfile/ClassElement.java index 5c0201b070e..7f4786e62aa 100644 --- a/src/java.base/share/classes/java/lang/classfile/ClassElement.java +++ b/src/java.base/share/classes/java/lang/classfile/ClassElement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +26,13 @@ import java.lang.classfile.attribute.*; -import jdk.internal.javac.PreviewFeature; - /** * A marker interface for elements that can appear when traversing * a {@link ClassModel} or be presented to a {@link ClassBuilder}. * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ClassElement extends ClassFileElement permits AccessFlags, Superclass, Interfaces, ClassFileVersion, FieldModel, MethodModel, diff --git a/src/java.base/share/classes/java/lang/classfile/ClassFile.java b/src/java.base/share/classes/java/lang/classfile/ClassFile.java index 337f3a0e878..7d4c7aa2965 100644 --- a/src/java.base/share/classes/java/lang/classfile/ClassFile.java +++ b/src/java.base/share/classes/java/lang/classfile/ClassFile.java @@ -43,7 +43,6 @@ import jdk.internal.classfile.impl.ClassFileImpl; import jdk.internal.classfile.impl.TemporaryConstantPool; -import jdk.internal.javac.PreviewFeature; import static java.util.Objects.requireNonNull; import static jdk.internal.constant.ConstantUtils.CD_module_info; @@ -53,9 +52,8 @@ * A {@code ClassFile} has a set of options that condition how parsing and * generation is done. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ClassFile permits ClassFileImpl { @@ -84,9 +82,8 @@ static ClassFile of(Option... options) { * An option that affects the parsing and writing of classfiles. * * @sealedGraph - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface Option { } @@ -94,9 +91,8 @@ sealed interface Option { * Option describing attribute mappers for custom attributes. * Default is only to process standard attributes. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface AttributeMapperOption extends Option permits ClassFileImpl.AttributeMapperOptionImpl { @@ -119,9 +115,8 @@ static AttributeMapperOption of(Function> attribut * Option describing the class hierarchy resolver to use when generating * stack maps. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface ClassHierarchyResolverOption extends Option permits ClassFileImpl.ClassHierarchyResolverOptionImpl { @@ -150,9 +145,8 @@ static ClassHierarchyResolverOption of(ClassHierarchyResolver classHierarchyReso * Default is {@code SHARED_POOL} to preserve the original constant * pool. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) enum ConstantPoolSharingOption implements Option { /** Preserves the original constant pool when transforming classfile */ @@ -167,9 +161,8 @@ enum ConstantPoolSharingOption implements Option { * Default is {@code PATCH_DEAD_CODE} to automatically patch out unreachable * code with NOPs. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) enum DeadCodeOption implements Option { /** Patch unreachable code */ @@ -188,9 +181,8 @@ enum DeadCodeOption implements Option { * Setting this option to {@code DROP_DEAD_LABELS} filters the above * elements instead. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) enum DeadLabelsOption implements Option { /** Fail on unresolved labels */ @@ -207,9 +199,8 @@ enum DeadLabelsOption implements Option { * reduce the overhead of parsing or transforming classfiles. * Default is {@code PASS_DEBUG} to process debug elements. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) enum DebugElementsOption implements Option { /** Process debug elements */ @@ -225,9 +216,8 @@ enum DebugElementsOption implements Option { * classfiles. * Default is {@code PASS_LINE_NUMBERS} to process line numbers. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) enum LineNumbersOption implements Option { /** Process line numbers */ @@ -243,9 +233,8 @@ enum LineNumbersOption implements Option { * Default is {@code FIX_SHORT_JUMPS} to automatically rewrite jump * instructions. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) enum ShortJumpsOption implements Option { /** Automatically convert short jumps to long when necessary */ @@ -262,9 +251,8 @@ enum ShortJumpsOption implements Option { * {@link #JAVA_6_VERSION} the stack maps may not be generated. * @jvms 4.10.1 Verification by Type Checking * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) enum StackMapsOption implements Option { /** Generate stack maps when required */ @@ -284,9 +272,8 @@ enum StackMapsOption implements Option { * Default is {@code PASS_ALL_ATTRIBUTES} to process all original attributes. * @see AttributeMapper.AttributeStability * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) enum AttributesProcessingOption implements Option { /** Process all original attributes during transformation */ @@ -651,16 +638,10 @@ default List verify(Path path) throws IOException { /** The class major version of JAVA_22. */ int JAVA_22_VERSION = 66; - /** - * The class major version of JAVA_23. - * @since 23 - */ + /** The class major version of JAVA_23. */ int JAVA_23_VERSION = 67; - /** - * The class major version of JAVA_24. - * @since 24 - */ + /** The class major version of JAVA_24. */ int JAVA_24_VERSION = 68; /** diff --git a/src/java.base/share/classes/java/lang/classfile/ClassFileBuilder.java b/src/java.base/share/classes/java/lang/classfile/ClassFileBuilder.java index 8b3f6544fff..01eeefd0b9b 100644 --- a/src/java.base/share/classes/java/lang/classfile/ClassFileBuilder.java +++ b/src/java.base/share/classes/java/lang/classfile/ClassFileBuilder.java @@ -29,7 +29,6 @@ import java.util.function.Consumer; import jdk.internal.classfile.impl.TransformImpl; -import jdk.internal.javac.PreviewFeature; /** * A builder for a classfile or portion of a classfile. Builders are rarely @@ -44,9 +43,8 @@ * @see ClassFileTransform * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ClassFileBuilder> extends Consumer permits ClassBuilder, FieldBuilder, MethodBuilder, CodeBuilder { diff --git a/src/java.base/share/classes/java/lang/classfile/ClassFileElement.java b/src/java.base/share/classes/java/lang/classfile/ClassFileElement.java index a4a8203038f..ed84eb39d53 100644 --- a/src/java.base/share/classes/java/lang/classfile/ClassFileElement.java +++ b/src/java.base/share/classes/java/lang/classfile/ClassFileElement.java @@ -24,8 +24,6 @@ */ package java.lang.classfile; -import jdk.internal.javac.PreviewFeature; - /** * Immutable model for a portion of (or the entirety of) a classfile. Elements * that model parts of the classfile that have attributes will implement {@link @@ -35,9 +33,8 @@ * will implement {@link ClassElement}, {@link MethodElement}, etc. * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ClassFileElement permits AttributedElement, CompoundElement, Attribute, ClassElement, CodeElement, FieldElement, MethodElement { diff --git a/src/java.base/share/classes/java/lang/classfile/ClassFileTransform.java b/src/java.base/share/classes/java/lang/classfile/ClassFileTransform.java index b9c5210881c..9fdafdf4331 100644 --- a/src/java.base/share/classes/java/lang/classfile/ClassFileTransform.java +++ b/src/java.base/share/classes/java/lang/classfile/ClassFileTransform.java @@ -27,8 +27,6 @@ import java.lang.classfile.attribute.RuntimeVisibleAnnotationsAttribute; import java.util.function.Supplier; -import jdk.internal.javac.PreviewFeature; - /** * A transformation on streams of elements. Transforms are used during * transformation of classfile entities; a transform is provided to a method like @@ -73,9 +71,8 @@ * @param the builder type * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ClassFileTransform< C extends ClassFileTransform, E extends ClassFileElement, diff --git a/src/java.base/share/classes/java/lang/classfile/ClassFileVersion.java b/src/java.base/share/classes/java/lang/classfile/ClassFileVersion.java index b6ef3e57f61..1916a185cc8 100644 --- a/src/java.base/share/classes/java/lang/classfile/ClassFileVersion.java +++ b/src/java.base/share/classes/java/lang/classfile/ClassFileVersion.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +25,14 @@ package java.lang.classfile; import jdk.internal.classfile.impl.ClassFileVersionImpl; -import jdk.internal.javac.PreviewFeature; /** * Models the classfile version information for a class. Delivered as a {@link * java.lang.classfile.ClassElement} when traversing the elements of a {@link * ClassModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ClassFileVersion extends ClassElement permits ClassFileVersionImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/ClassHierarchyResolver.java b/src/java.base/share/classes/java/lang/classfile/ClassHierarchyResolver.java index c2719e7aae0..2c612854a64 100644 --- a/src/java.base/share/classes/java/lang/classfile/ClassHierarchyResolver.java +++ b/src/java.base/share/classes/java/lang/classfile/ClassHierarchyResolver.java @@ -37,7 +37,6 @@ import jdk.internal.classfile.impl.ClassHierarchyImpl.ClassLoadingClassHierarchyResolver; import jdk.internal.classfile.impl.ClassHierarchyImpl.StaticClassHierarchyResolver; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; import static java.lang.constant.ConstantDescs.CD_Object; import static java.util.Objects.requireNonNull; @@ -46,9 +45,8 @@ * Provides class hierarchy information for generating correct stack maps * during code building. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) @FunctionalInterface public interface ClassHierarchyResolver { @@ -71,9 +69,8 @@ static ClassHierarchyResolver defaultResolver() { /** * Information about a resolved class. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface ClassHierarchyInfo permits ClassHierarchyImpl.ClassHierarchyInfoImpl { /** diff --git a/src/java.base/share/classes/java/lang/classfile/ClassModel.java b/src/java.base/share/classes/java/lang/classfile/ClassModel.java index 915b662b488..db804348cfe 100644 --- a/src/java.base/share/classes/java/lang/classfile/ClassModel.java +++ b/src/java.base/share/classes/java/lang/classfile/ClassModel.java @@ -31,16 +31,14 @@ import java.util.Optional; import jdk.internal.classfile.impl.ClassImpl; -import jdk.internal.javac.PreviewFeature; /** * Models a classfile. The contents of the classfile can be traversed via * a streaming view, or via random access (e.g., * {@link #flags()}), or by freely mixing the two. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ClassModel extends CompoundElement, AttributedElement permits ClassImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/ClassReader.java b/src/java.base/share/classes/java/lang/classfile/ClassReader.java index 58ee2aae5e5..93f2ac5c810 100644 --- a/src/java.base/share/classes/java/lang/classfile/ClassReader.java +++ b/src/java.base/share/classes/java/lang/classfile/ClassReader.java @@ -33,7 +33,6 @@ import java.util.function.Function; import jdk.internal.classfile.impl.ClassReaderImpl; -import jdk.internal.javac.PreviewFeature; /** * Supports reading from a classfile. Methods are provided to read data of @@ -42,9 +41,8 @@ * Encapsulates additional reading context such as mappers for custom attributes * and processing options. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ClassReader extends ConstantPool permits ClassReaderImpl { @@ -122,7 +120,6 @@ public sealed interface ClassReader extends ConstantPool * @param cls the entry type * @throws ConstantPoolException if the index is out of range of the * constant pool size, or zero, or the entry is not of the given type - * @since 23 */ T readEntryOrNull(int offset, Class cls); diff --git a/src/java.base/share/classes/java/lang/classfile/ClassSignature.java b/src/java.base/share/classes/java/lang/classfile/ClassSignature.java index 5a57144c4ab..0e1329fd167 100644 --- a/src/java.base/share/classes/java/lang/classfile/ClassSignature.java +++ b/src/java.base/share/classes/java/lang/classfile/ClassSignature.java @@ -27,27 +27,21 @@ import java.util.List; import jdk.internal.classfile.impl.SignaturesImpl; -import jdk.internal.javac.PreviewFeature; import static java.util.Objects.requireNonNull; /** * Models the generic signature of a class file, as defined by JVMS {@jvms 4.7.9}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ClassSignature permits SignaturesImpl.ClassSignatureImpl { /** {@return the type parameters of this class} */ List typeParameters(); - /** - * {@return the instantiation of the superclass in this signature} - * - * @since 23 - */ + /** {@return the instantiation of the superclass in this signature} */ Signature.ClassTypeSig superclassSignature(); /** {@return the instantiation of the interfaces in this signature} */ @@ -60,7 +54,6 @@ public sealed interface ClassSignature * {@return a class signature} * @param superclassSignature the superclass * @param superinterfaceSignatures the interfaces - * @since 23 */ public static ClassSignature of(Signature.ClassTypeSig superclassSignature, Signature.ClassTypeSig... superinterfaceSignatures) { @@ -72,7 +65,6 @@ public static ClassSignature of(Signature.ClassTypeSig superclassSignature, * @param typeParameters the type parameters * @param superclassSignature the superclass * @param superinterfaceSignatures the interfaces - * @since 23 */ public static ClassSignature of(List typeParameters, Signature.ClassTypeSig superclassSignature, diff --git a/src/java.base/share/classes/java/lang/classfile/ClassTransform.java b/src/java.base/share/classes/java/lang/classfile/ClassTransform.java index f512683a9b6..82b61a15089 100644 --- a/src/java.base/share/classes/java/lang/classfile/ClassTransform.java +++ b/src/java.base/share/classes/java/lang/classfile/ClassTransform.java @@ -30,7 +30,6 @@ import java.util.function.Supplier; import jdk.internal.classfile.impl.TransformImpl; -import jdk.internal.javac.PreviewFeature; import static java.util.Objects.requireNonNull; @@ -39,9 +38,8 @@ * * @see ClassFileTransform * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) @FunctionalInterface public non-sealed interface ClassTransform extends ClassFileTransform { diff --git a/src/java.base/share/classes/java/lang/classfile/CodeBuilder.java b/src/java.base/share/classes/java/lang/classfile/CodeBuilder.java index 11e83550d23..1a074c1554a 100644 --- a/src/java.base/share/classes/java/lang/classfile/CodeBuilder.java +++ b/src/java.base/share/classes/java/lang/classfile/CodeBuilder.java @@ -39,7 +39,6 @@ import java.util.function.Consumer; import jdk.internal.classfile.impl.*; -import jdk.internal.javac.PreviewFeature; import static java.util.Objects.requireNonNull; import static jdk.internal.classfile.impl.BytecodeHelpers.handleDescToHandleInfo; @@ -75,9 +74,8 @@ * * @see CodeTransform * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface CodeBuilder extends ClassFileBuilder permits CodeBuilder.BlockCodeBuilder, ChainedCodeBuilder, TerminalCodeBuilder, NonterminalCodeBuilder { @@ -149,9 +147,8 @@ default CodeBuilder transforming(CodeTransform transform, Consumer /** * A builder for blocks of code. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface BlockCodeBuilder extends CodeBuilder permits BlockCodeBuilderImpl { /** @@ -290,9 +287,8 @@ default CodeBuilder ifThenElse(Opcode opcode, * * @see #trying * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface CatchBuilder permits CatchBuilderImpl { /** * Adds a catch block that catches an exception of the given type. @@ -385,7 +381,6 @@ default CodeBuilder trying(Consumer tryHandler, * @return this builder * @throws IllegalArgumentException if {@code tk} is {@link TypeKind#VOID void} * or {@code slot} is out of range - * @since 23 */ default CodeBuilder loadLocal(TypeKind tk, int slot) { return with(LoadInstruction.of(tk, slot)); @@ -398,7 +393,6 @@ default CodeBuilder loadLocal(TypeKind tk, int slot) { * @return this builder * @throws IllegalArgumentException if {@code tk} is {@link TypeKind#VOID void} * or {@code slot} is out of range - * @since 23 */ default CodeBuilder storeLocal(TypeKind tk, int slot) { return with(StoreInstruction.of(tk, slot)); @@ -410,7 +404,6 @@ default CodeBuilder storeLocal(TypeKind tk, int slot) { * @param op the branch opcode * @param target the branch target * @return this builder - * @since 23 */ default CodeBuilder branch(Opcode op, Label target) { return with(BranchInstruction.of(op, target)); @@ -420,7 +413,6 @@ default CodeBuilder branch(Opcode op, Label target) { * Generate return instruction * @param tk the return type * @return this builder - * @since 23 */ default CodeBuilder return_(TypeKind tk) { return with(ReturnInstruction.of(tk)); @@ -432,7 +424,6 @@ default CodeBuilder return_(TypeKind tk) { * @param opcode the field access opcode * @param ref the field reference * @return this builder - * @since 23 */ default CodeBuilder fieldAccess(Opcode opcode, FieldRefEntry ref) { return with(FieldInstruction.of(opcode, ref)); @@ -446,7 +437,6 @@ default CodeBuilder fieldAccess(Opcode opcode, FieldRefEntry ref) { * @param name the field name * @param type the field type * @return this builder - * @since 23 */ default CodeBuilder fieldAccess(Opcode opcode, ClassDesc owner, String name, ClassDesc type) { return fieldAccess(opcode, constantPool().fieldRefEntry(owner, name, type)); @@ -458,7 +448,6 @@ default CodeBuilder fieldAccess(Opcode opcode, ClassDesc owner, String name, Cla * @param opcode the invoke opcode * @param ref the interface method or method reference * @return this builder - * @since 23 */ default CodeBuilder invoke(Opcode opcode, MemberRefEntry ref) { return with(InvokeInstruction.of(opcode, ref)); @@ -473,7 +462,6 @@ default CodeBuilder invoke(Opcode opcode, MemberRefEntry ref) { * @param desc the method type * @param isInterface the interface method invocation indication * @return this builder - * @since 23 */ default CodeBuilder invoke(Opcode opcode, ClassDesc owner, String name, MethodTypeDesc desc, boolean isInterface) { return invoke(opcode, @@ -485,7 +473,6 @@ default CodeBuilder invoke(Opcode opcode, ClassDesc owner, String name, MethodTy * Generate an instruction to load from an array * @param tk the array element type * @return this builder - * @since 23 */ default CodeBuilder arrayLoad(TypeKind tk) { Opcode opcode = BytecodeHelpers.arrayLoadOpcode(tk); @@ -496,7 +483,6 @@ default CodeBuilder arrayLoad(TypeKind tk) { * Generate an instruction to store into an array * @param tk the array element type * @return this builder - * @since 23 */ default CodeBuilder arrayStore(TypeKind tk) { Opcode opcode = BytecodeHelpers.arrayStoreOpcode(tk); @@ -510,7 +496,6 @@ default CodeBuilder arrayStore(TypeKind tk) { * @return this builder * @throws IllegalArgumentException for conversions of {@link TypeKind#VOID void} or * {@link TypeKind#REFERENCE reference} - * @since 23 */ default CodeBuilder conversion(TypeKind fromType, TypeKind toType) { var computationalFrom = fromType.asLoadable(); @@ -566,7 +551,6 @@ default CodeBuilder conversion(TypeKind fromType, TypeKind toType) { * Generate an instruction pushing a constant onto the operand stack * @param value the constant value * @return this builder - * @since 23 */ default CodeBuilder loadConstant(ConstantDesc value) { //avoid switch expressions here @@ -1740,7 +1724,6 @@ default CodeBuilder ineg() { * * @param target the target type * @return this builder - * @since 23 */ default CodeBuilder instanceOf(ClassEntry target) { return with(TypeCheckInstruction.of(Opcode.INSTANCEOF, target)); @@ -1756,7 +1739,6 @@ default CodeBuilder instanceOf(ClassEntry target) { * @param target the target type * @return this builder * @throws IllegalArgumentException if {@code target} represents a primitive type - * @since 23 */ default CodeBuilder instanceOf(ClassDesc target) { return instanceOf(constantPool().classEntry(target)); diff --git a/src/java.base/share/classes/java/lang/classfile/CodeElement.java b/src/java.base/share/classes/java/lang/classfile/CodeElement.java index 1cec4b8e604..63669d41014 100644 --- a/src/java.base/share/classes/java/lang/classfile/CodeElement.java +++ b/src/java.base/share/classes/java/lang/classfile/CodeElement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,8 +28,6 @@ import java.lang.classfile.attribute.RuntimeVisibleTypeAnnotationsAttribute; import java.lang.classfile.attribute.StackMapTableAttribute; -import jdk.internal.javac.PreviewFeature; - /** * A marker interface for elements that can appear when traversing * a {@link CodeModel} or be presented to a {@link CodeBuilder}. Code elements @@ -39,9 +37,8 @@ * exception metadata, label target metadata, etc. * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface CodeElement extends ClassFileElement permits Instruction, PseudoInstruction, CustomAttribute, RuntimeVisibleTypeAnnotationsAttribute, RuntimeInvisibleTypeAnnotationsAttribute, diff --git a/src/java.base/share/classes/java/lang/classfile/CodeModel.java b/src/java.base/share/classes/java/lang/classfile/CodeModel.java index 759aacc18c9..644f7660564 100644 --- a/src/java.base/share/classes/java/lang/classfile/CodeModel.java +++ b/src/java.base/share/classes/java/lang/classfile/CodeModel.java @@ -31,15 +31,13 @@ import java.util.Optional; import jdk.internal.classfile.impl.BufferedCodeBuilder; -import jdk.internal.javac.PreviewFeature; /** * Models the body of a method (the {@code Code} attribute). The instructions * of the method body are accessed via a streaming view. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface CodeModel extends CompoundElement, AttributedElement, MethodElement permits CodeAttribute, BufferedCodeBuilder.Model { diff --git a/src/java.base/share/classes/java/lang/classfile/CodeTransform.java b/src/java.base/share/classes/java/lang/classfile/CodeTransform.java index 0474e0c9c67..b76c02bf5fb 100644 --- a/src/java.base/share/classes/java/lang/classfile/CodeTransform.java +++ b/src/java.base/share/classes/java/lang/classfile/CodeTransform.java @@ -28,7 +28,6 @@ import java.util.function.Supplier; import jdk.internal.classfile.impl.TransformImpl; -import jdk.internal.javac.PreviewFeature; import static java.util.Objects.requireNonNull; @@ -37,9 +36,8 @@ * * @see ClassFileTransform * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) @FunctionalInterface public non-sealed interface CodeTransform extends ClassFileTransform { diff --git a/src/java.base/share/classes/java/lang/classfile/CompoundElement.java b/src/java.base/share/classes/java/lang/classfile/CompoundElement.java index 5dfeac6f00d..38d149623e1 100644 --- a/src/java.base/share/classes/java/lang/classfile/CompoundElement.java +++ b/src/java.base/share/classes/java/lang/classfile/CompoundElement.java @@ -34,8 +34,6 @@ import java.util.stream.Stream; import java.util.stream.StreamSupport; -import jdk.internal.javac.PreviewFeature; - /** * A {@link ClassFileElement} that has complex structure defined in terms of * other classfile elements, such as a method, field, method body, or entire @@ -46,9 +44,8 @@ * @param the element type * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface CompoundElement extends ClassFileElement, Iterable permits ClassModel, CodeModel, FieldModel, MethodModel, jdk.internal.classfile.impl.AbstractUnboundModel { diff --git a/src/java.base/share/classes/java/lang/classfile/CustomAttribute.java b/src/java.base/share/classes/java/lang/classfile/CustomAttribute.java index 9fe492dc22c..f47ce9f055b 100644 --- a/src/java.base/share/classes/java/lang/classfile/CustomAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/CustomAttribute.java @@ -24,7 +24,8 @@ */ package java.lang.classfile; -import jdk.internal.javac.PreviewFeature; +import java.lang.classfile.constantpool.Utf8Entry; +import jdk.internal.classfile.impl.TemporaryConstantPool; /** * Models a non-standard attribute of a classfile. Clients should extend @@ -33,9 +34,8 @@ * format and the {@linkplain CustomAttribute} representation. * @param the custom attribute type * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public abstract non-sealed class CustomAttribute> implements Attribute, CodeElement, ClassElement, MethodElement, FieldElement { @@ -55,8 +55,8 @@ public final AttributeMapper attributeMapper() { } @Override - public final String attributeName() { - return mapper.name(); + public Utf8Entry attributeName() { + return TemporaryConstantPool.INSTANCE.utf8Entry(mapper.name()); } @Override diff --git a/src/java.base/share/classes/java/lang/classfile/FieldBuilder.java b/src/java.base/share/classes/java/lang/classfile/FieldBuilder.java index d3183644657..c473e09cab7 100644 --- a/src/java.base/share/classes/java/lang/classfile/FieldBuilder.java +++ b/src/java.base/share/classes/java/lang/classfile/FieldBuilder.java @@ -32,7 +32,6 @@ import jdk.internal.classfile.impl.AccessFlagsImpl; import jdk.internal.classfile.impl.ChainedFieldBuilder; import jdk.internal.classfile.impl.TerminalFieldBuilder; -import jdk.internal.javac.PreviewFeature; /** * A builder for fields. Builders are not created directly; they are passed @@ -43,9 +42,8 @@ * * @see FieldTransform * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface FieldBuilder extends ClassFileBuilder permits TerminalFieldBuilder, ChainedFieldBuilder { diff --git a/src/java.base/share/classes/java/lang/classfile/FieldElement.java b/src/java.base/share/classes/java/lang/classfile/FieldElement.java index b4af9971981..a2c1b22751e 100644 --- a/src/java.base/share/classes/java/lang/classfile/FieldElement.java +++ b/src/java.base/share/classes/java/lang/classfile/FieldElement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +26,13 @@ import java.lang.classfile.attribute.*; -import jdk.internal.javac.PreviewFeature; - /** * A marker interface for elements that can appear when traversing * a {@link FieldModel} or be presented to a {@link FieldBuilder}. * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface FieldElement extends ClassFileElement permits AccessFlags, CustomAttribute, ConstantValueAttribute, DeprecatedAttribute, diff --git a/src/java.base/share/classes/java/lang/classfile/FieldModel.java b/src/java.base/share/classes/java/lang/classfile/FieldModel.java index c45f3e88d5d..89fa1e192b0 100644 --- a/src/java.base/share/classes/java/lang/classfile/FieldModel.java +++ b/src/java.base/share/classes/java/lang/classfile/FieldModel.java @@ -32,16 +32,14 @@ import jdk.internal.classfile.impl.BufferedFieldBuilder; import jdk.internal.classfile.impl.FieldImpl; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a field. The contents of the field can be traversed via * a streaming view, or via random access (e.g., * {@link #flags()}), or by freely mixing the two. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface FieldModel extends CompoundElement, AttributedElement, ClassElement permits BufferedFieldBuilder.Model, FieldImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/FieldTransform.java b/src/java.base/share/classes/java/lang/classfile/FieldTransform.java index 78a6f5ead2f..90313ae48f0 100644 --- a/src/java.base/share/classes/java/lang/classfile/FieldTransform.java +++ b/src/java.base/share/classes/java/lang/classfile/FieldTransform.java @@ -29,7 +29,6 @@ import java.util.function.Supplier; import jdk.internal.classfile.impl.TransformImpl; -import jdk.internal.javac.PreviewFeature; import static java.util.Objects.requireNonNull; @@ -38,9 +37,8 @@ * * @see ClassFileTransform * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) @FunctionalInterface public non-sealed interface FieldTransform extends ClassFileTransform { diff --git a/src/java.base/share/classes/java/lang/classfile/Instruction.java b/src/java.base/share/classes/java/lang/classfile/Instruction.java index 210c1e1b0da..2fe0ec5a588 100644 --- a/src/java.base/share/classes/java/lang/classfile/Instruction.java +++ b/src/java.base/share/classes/java/lang/classfile/Instruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,14 +28,12 @@ import java.lang.classfile.instruction.*; import jdk.internal.classfile.impl.AbstractInstruction; -import jdk.internal.javac.PreviewFeature; /** * Models an executable instruction in a method body. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface Instruction extends CodeElement permits ArrayLoadInstruction, ArrayStoreInstruction, BranchInstruction, ConstantInstruction, ConvertInstruction, DiscontinuedInstruction, diff --git a/src/java.base/share/classes/java/lang/classfile/Interfaces.java b/src/java.base/share/classes/java/lang/classfile/Interfaces.java index ff1dda17de8..2c0e5b2e54b 100644 --- a/src/java.base/share/classes/java/lang/classfile/Interfaces.java +++ b/src/java.base/share/classes/java/lang/classfile/Interfaces.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,15 +31,13 @@ import jdk.internal.classfile.impl.InterfacesImpl; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models the interfaces of a class. Delivered as a {@link * java.lang.classfile.ClassElement} when traversing a {@link ClassModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface Interfaces extends ClassElement permits InterfacesImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/Label.java b/src/java.base/share/classes/java/lang/classfile/Label.java index 5069b935935..e958e116084 100644 --- a/src/java.base/share/classes/java/lang/classfile/Label.java +++ b/src/java.base/share/classes/java/lang/classfile/Label.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,7 +25,6 @@ package java.lang.classfile; import jdk.internal.classfile.impl.LabelImpl; -import jdk.internal.javac.PreviewFeature; /** * A marker for a position within the instructions of a method body. The @@ -40,9 +39,8 @@ * can be bound to the current position within a {@linkplain CodeBuilder} via * {@link CodeBuilder#labelBinding(Label)} or {@link CodeBuilder#with(ClassFileElement)}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface Label permits LabelImpl { } diff --git a/src/java.base/share/classes/java/lang/classfile/MethodBuilder.java b/src/java.base/share/classes/java/lang/classfile/MethodBuilder.java index 6607d19b0ac..747cbe2e107 100644 --- a/src/java.base/share/classes/java/lang/classfile/MethodBuilder.java +++ b/src/java.base/share/classes/java/lang/classfile/MethodBuilder.java @@ -32,7 +32,6 @@ import jdk.internal.classfile.impl.AccessFlagsImpl; import jdk.internal.classfile.impl.ChainedMethodBuilder; import jdk.internal.classfile.impl.TerminalMethodBuilder; -import jdk.internal.javac.PreviewFeature; /** * A builder for methods. Builders are not created directly; they are passed @@ -43,9 +42,8 @@ * * @see MethodTransform * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface MethodBuilder extends ClassFileBuilder permits ChainedMethodBuilder, TerminalMethodBuilder { diff --git a/src/java.base/share/classes/java/lang/classfile/MethodElement.java b/src/java.base/share/classes/java/lang/classfile/MethodElement.java index dd23548c360..77254a6a82c 100644 --- a/src/java.base/share/classes/java/lang/classfile/MethodElement.java +++ b/src/java.base/share/classes/java/lang/classfile/MethodElement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +26,13 @@ import java.lang.classfile.attribute.*; -import jdk.internal.javac.PreviewFeature; - /** * A marker interface for elements that can appear when traversing * a {@link MethodModel} or be presented to a {@link MethodBuilder}. * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface MethodElement extends ClassFileElement permits AccessFlags, CodeModel, CustomAttribute, diff --git a/src/java.base/share/classes/java/lang/classfile/MethodModel.java b/src/java.base/share/classes/java/lang/classfile/MethodModel.java index 568036e464d..d88051a5eb3 100644 --- a/src/java.base/share/classes/java/lang/classfile/MethodModel.java +++ b/src/java.base/share/classes/java/lang/classfile/MethodModel.java @@ -32,16 +32,14 @@ import jdk.internal.classfile.impl.BufferedMethodBuilder; import jdk.internal.classfile.impl.MethodImpl; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a method. The contents of the method can be traversed via * a streaming view, or via random access (e.g., * {@link #flags()}), or by freely mixing the two. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface MethodModel extends CompoundElement, AttributedElement, ClassElement permits BufferedMethodBuilder.Model, MethodImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/MethodSignature.java b/src/java.base/share/classes/java/lang/classfile/MethodSignature.java index 7235c368a45..e3889395e32 100644 --- a/src/java.base/share/classes/java/lang/classfile/MethodSignature.java +++ b/src/java.base/share/classes/java/lang/classfile/MethodSignature.java @@ -29,16 +29,14 @@ import jdk.internal.classfile.impl.SignaturesImpl; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; import static java.util.Objects.requireNonNull; /** * Models the generic signature of a method, as defined by JVMS {@jvms 4.7.9}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface MethodSignature permits SignaturesImpl.MethodSignatureImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/MethodTransform.java b/src/java.base/share/classes/java/lang/classfile/MethodTransform.java index bf5786f3dc7..865fadbae87 100644 --- a/src/java.base/share/classes/java/lang/classfile/MethodTransform.java +++ b/src/java.base/share/classes/java/lang/classfile/MethodTransform.java @@ -29,7 +29,6 @@ import java.util.function.Supplier; import jdk.internal.classfile.impl.TransformImpl; -import jdk.internal.javac.PreviewFeature; import static java.util.Objects.requireNonNull; @@ -38,9 +37,8 @@ * * @see ClassFileTransform * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) @FunctionalInterface public non-sealed interface MethodTransform extends ClassFileTransform { diff --git a/src/java.base/share/classes/java/lang/classfile/Opcode.java b/src/java.base/share/classes/java/lang/classfile/Opcode.java index 735510dbcea..4d333400001 100644 --- a/src/java.base/share/classes/java/lang/classfile/Opcode.java +++ b/src/java.base/share/classes/java/lang/classfile/Opcode.java @@ -25,7 +25,6 @@ package java.lang.classfile; import jdk.internal.classfile.impl.RawBytecodeHelper; -import jdk.internal.javac.PreviewFeature; /** * Describes the opcodes of the JVM instruction set, as described in JVMS {@jvms 6.5}. @@ -35,9 +34,8 @@ * @see Instruction * @see PseudoInstruction * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public enum Opcode { /** Do nothing */ @@ -697,9 +695,8 @@ public enum Opcode { /** * Kinds of opcodes. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public static enum Kind { /** diff --git a/src/java.base/share/classes/java/lang/classfile/PseudoInstruction.java b/src/java.base/share/classes/java/lang/classfile/PseudoInstruction.java index b152756acfd..456bce04c80 100644 --- a/src/java.base/share/classes/java/lang/classfile/PseudoInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/PseudoInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,7 +33,6 @@ import java.lang.classfile.instruction.LocalVariableType; import jdk.internal.classfile.impl.AbstractPseudoInstruction; -import jdk.internal.javac.PreviewFeature; /** * Models metadata about a {@link CodeAttribute}, such as entries in the @@ -43,9 +42,8 @@ * pseudo-instructions can be disabled by modifying the value of classfile * options (e.g., {@link ClassFile.DebugElementsOption}). * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface PseudoInstruction extends CodeElement permits CharacterRange, ExceptionCatch, LabelTarget, LineNumber, LocalVariable, LocalVariableType, AbstractPseudoInstruction { diff --git a/src/java.base/share/classes/java/lang/classfile/Signature.java b/src/java.base/share/classes/java/lang/classfile/Signature.java index 7255a41528c..ad2dca0ad46 100644 --- a/src/java.base/share/classes/java/lang/classfile/Signature.java +++ b/src/java.base/share/classes/java/lang/classfile/Signature.java @@ -30,7 +30,6 @@ import jdk.internal.classfile.impl.SignaturesImpl; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; import static java.util.Objects.requireNonNull; @@ -38,9 +37,8 @@ * Models generic Java type signatures, as defined in JVMS {@jvms 4.7.9.1}. * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface Signature { /** {@return the raw signature string} */ @@ -71,9 +69,8 @@ public static Signature of(ClassDesc classDesc) { /** * Models the signature of a primitive type or void * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface BaseTypeSig extends Signature permits SignaturesImpl.BaseTypeSigImpl { @@ -108,9 +105,8 @@ public static BaseTypeSig of(char baseType) { * type variable, or array type. * * @sealedGraph - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface RefTypeSig extends Signature permits ArrayTypeSig, ClassTypeSig, TypeVarSig { @@ -119,9 +115,8 @@ public sealed interface RefTypeSig /** * Models the signature of a possibly-parameterized class or interface type. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ClassTypeSig extends RefTypeSig, ThrowableSig permits SignaturesImpl.ClassTypeSigImpl { @@ -187,31 +182,27 @@ public static ClassTypeSig of(ClassTypeSig outerType, String className, TypeArg. * Models the type argument. * * @sealedGraph - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface TypeArg { /** * Models an unbounded type argument {@code *}. - * @since 23 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface Unbounded extends TypeArg permits SignaturesImpl.UnboundedTypeArgImpl { } /** * Models a type argument with an explicit bound type. - * @since 23 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface Bounded extends TypeArg permits SignaturesImpl.TypeArgImpl { /** * Models a type argument's wildcard indicator. - * @since 23 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public enum WildcardIndicator { /** @@ -243,7 +234,6 @@ public enum WildcardIndicator { /** * {@return a bounded type arg} * @param boundType the bound - * @since 23 */ public static TypeArg.Bounded of(RefTypeSig boundType) { requireNonNull(boundType); @@ -252,7 +242,6 @@ public static TypeArg.Bounded of(RefTypeSig boundType) { /** * {@return an unbounded type arg} - * @since 23 */ public static TypeArg.Unbounded unbounded() { return SignaturesImpl.UnboundedTypeArgImpl.INSTANCE; @@ -261,7 +250,6 @@ public static TypeArg.Unbounded unbounded() { /** * {@return an upper-bounded type arg} * @param boundType the upper bound - * @since 23 */ public static TypeArg.Bounded extendsOf(RefTypeSig boundType) { requireNonNull(boundType); @@ -271,7 +259,6 @@ public static TypeArg.Bounded extendsOf(RefTypeSig boundType) { /** * {@return a lower-bounded type arg} * @param boundType the lower bound - * @since 23 */ public static TypeArg.Bounded superOf(RefTypeSig boundType) { requireNonNull(boundType); @@ -282,7 +269,6 @@ public static TypeArg.Bounded superOf(RefTypeSig boundType) { * {@return a bounded type arg} * @param wildcard the wild card * @param boundType optional bound type - * @since 23 */ public static TypeArg.Bounded bounded(Bounded.WildcardIndicator wildcard, RefTypeSig boundType) { requireNonNull(wildcard); @@ -294,9 +280,8 @@ public static TypeArg.Bounded bounded(Bounded.WildcardIndicator wildcard, RefTyp /** * Models the signature of a type variable. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface TypeVarSig extends RefTypeSig, ThrowableSig permits SignaturesImpl.TypeVarSigImpl { @@ -316,9 +301,8 @@ public static TypeVarSig of(String identifier) { /** * Models the signature of an array type. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ArrayTypeSig extends RefTypeSig permits SignaturesImpl.ArrayTypeSigImpl { @@ -352,9 +336,8 @@ public static ArrayTypeSig of(int dims, Signature componentSignature) { /** * Models a signature for a type parameter of a generic class or method. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface TypeParam permits SignaturesImpl.TypeParamImpl { @@ -398,9 +381,8 @@ public static TypeParam of(String identifier, Optional classBound, R * Models a signature for a throwable type. * * @sealedGraph - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ThrowableSig extends Signature { } } diff --git a/src/java.base/share/classes/java/lang/classfile/Superclass.java b/src/java.base/share/classes/java/lang/classfile/Superclass.java index a69fac6341a..fe30fe8a8e3 100644 --- a/src/java.base/share/classes/java/lang/classfile/Superclass.java +++ b/src/java.base/share/classes/java/lang/classfile/Superclass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,15 +27,13 @@ import java.lang.classfile.constantpool.ClassEntry; import jdk.internal.classfile.impl.SuperclassImpl; -import jdk.internal.javac.PreviewFeature; /** * Models the superclass of a class. Delivered as a {@link * java.lang.classfile.ClassElement} when traversing a {@link ClassModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface Superclass extends ClassElement permits SuperclassImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/TypeAnnotation.java b/src/java.base/share/classes/java/lang/classfile/TypeAnnotation.java index 38e5ea09a93..9353b30a643 100644 --- a/src/java.base/share/classes/java/lang/classfile/TypeAnnotation.java +++ b/src/java.base/share/classes/java/lang/classfile/TypeAnnotation.java @@ -31,7 +31,6 @@ import jdk.internal.classfile.impl.TargetInfoImpl; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; import static java.lang.classfile.TypeAnnotation.TargetInfo.*; @@ -52,18 +51,16 @@ * @see RuntimeVisibleTypeAnnotationsAttribute * @see RuntimeInvisibleTypeAnnotationsAttribute * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface TypeAnnotation permits UnboundAttribute.UnboundTypeAnnotation { /** * The kind of target on which the annotation appears, as defined in JVMS {@jvms 4.7.20.1}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public enum TargetType { /** For annotations on a class type parameter declaration. */ CLASS_TYPE_PARAMETER(TARGET_CLASS_TYPE_PARAMETER, 1), @@ -193,9 +190,8 @@ static TypeAnnotation of(TargetInfo targetInfo, List targetPa * Specifies which type in a declaration or expression is being annotated. * * @sealedGraph - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface TargetInfo { /** @@ -611,9 +607,8 @@ static TypeArgumentTarget ofMethodReferenceTypeArgument(Label target, int typeAr * parameter of a generic class, generic interface, generic method, or * generic constructor. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface TypeParameterTarget extends TargetInfo permits TargetInfoImpl.TypeParameterTargetImpl { @@ -630,9 +625,8 @@ sealed interface TypeParameterTarget extends TargetInfo * Indicates that an annotation appears on a type in the extends or implements * clause of a class or interface declaration. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface SupertypeTarget extends TargetInfo permits TargetInfoImpl.SupertypeTargetImpl { @@ -654,9 +648,8 @@ sealed interface SupertypeTarget extends TargetInfo * type parameter declaration of a generic class, interface, method, or * constructor. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface TypeParameterBoundTarget extends TargetInfo permits TargetInfoImpl.TypeParameterBoundTargetImpl { @@ -680,9 +673,8 @@ sealed interface TypeParameterBoundTarget extends TargetInfo * declaration, the return type of a method, the type of a newly constructed * object, or the receiver type of a method or constructor. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface EmptyTarget extends TargetInfo permits TargetInfoImpl.EmptyTargetImpl { } @@ -691,9 +683,8 @@ sealed interface EmptyTarget extends TargetInfo * Indicates that an annotation appears on the type in a formal parameter * declaration of a method, constructor, or lambda expression. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface FormalParameterTarget extends TargetInfo permits TargetInfoImpl.FormalParameterTargetImpl { @@ -710,9 +701,8 @@ sealed interface FormalParameterTarget extends TargetInfo * Indicates that an annotation appears on the i'th type in the throws * clause of a method or constructor declaration. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface ThrowsTarget extends TargetInfo permits TargetInfoImpl.ThrowsTargetImpl { @@ -730,9 +720,8 @@ sealed interface ThrowsTarget extends TargetInfo * Indicates that an annotation appears on the type in a local variable declaration, * including a variable declared as a resource in a try-with-resources statement. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface LocalVarTarget extends TargetInfo permits TargetInfoImpl.LocalVarTargetImpl { @@ -747,9 +736,8 @@ sealed interface LocalVarTarget extends TargetInfo * has a value, and the index into the local variable array of the current * frame at which that local variable can be found. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface LocalVarTargetInfo permits TargetInfoImpl.LocalVarTargetInfoImpl { @@ -794,9 +782,8 @@ static LocalVarTargetInfo of(Label startLabel, Label endLabel, int index) { * Indicates that an annotation appears on the i'th type in an exception parameter * declaration. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface CatchTarget extends TargetInfo permits TargetInfoImpl.CatchTargetImpl { @@ -813,9 +800,8 @@ sealed interface CatchTarget extends TargetInfo * Indicates that an annotation appears on either the type in an instanceof expression * or a new expression, or the type before the :: in a method reference expression. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface OffsetTarget extends TargetInfo permits TargetInfoImpl.OffsetTargetImpl { @@ -835,9 +821,8 @@ sealed interface OffsetTarget extends TargetInfo * expression, an explicit constructor invocation statement, a method invocation expression, or a method reference * expression. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface TypeArgumentTarget extends TargetInfo permits TargetInfoImpl.TypeArgumentTargetImpl { @@ -871,18 +856,16 @@ sealed interface TypeArgumentTarget extends TargetInfo * JVMS: Type_path structure identifies which part of the type is annotated, * as defined in JVMS {@jvms 4.7.20.2} * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface TypePathComponent permits UnboundAttribute.TypePathComponentImpl { /** * Type path kind, as defined in JVMS {@jvms 4.7.20.2} * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public enum Kind { /** Annotation is deeper in an array type */ diff --git a/src/java.base/share/classes/java/lang/classfile/TypeKind.java b/src/java.base/share/classes/java/lang/classfile/TypeKind.java index bdbea7c8c54..5a6475aa801 100644 --- a/src/java.base/share/classes/java/lang/classfile/TypeKind.java +++ b/src/java.base/share/classes/java/lang/classfile/TypeKind.java @@ -30,7 +30,6 @@ import java.lang.constant.ConstantDescs; import java.lang.invoke.TypeDescriptor; -import jdk.internal.javac.PreviewFeature; import jdk.internal.vm.annotation.Stable; /** @@ -54,9 +53,8 @@ * * @jvms 2.2 Data Types * @jvms 2.11.1 Types and the Java Virtual Machine - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public enum TypeKind { // Elements are grouped so frequently used switch ranges such as // primitives (boolean - double) and computational (int - void) are together. @@ -166,7 +164,6 @@ private ClassDesc fetchUpperBound() { /** * {@return the code used by the {@link Opcode#NEWARRAY newarray} instruction to create an array * of this component type, or {@code -1} if this type is not supported by {@code newarray}} - * @since 23 * @jvms 6.5.newarray newarray */ public int newarrayCode() { @@ -198,7 +195,6 @@ public TypeKind asLoadable() { * newarray}} * @param newarrayCode the operand of the {@code newarray} instruction * @throws IllegalArgumentException if the code is invalid - * @since 23 * @jvms 6.5.newarray newarray */ public static TypeKind fromNewarrayCode(int newarrayCode) { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/AnnotationDefaultAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/AnnotationDefaultAttribute.java index 4f147b0d63a..206c0a84087 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/AnnotationDefaultAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/AnnotationDefaultAttribute.java @@ -32,7 +32,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code AnnotationDefault} attribute (JVMS {@jvms 4.7.22}), which can @@ -46,9 +45,8 @@ *

* The attribute was introduced in the Java SE Platform version 5.0. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface AnnotationDefaultAttribute extends Attribute, MethodElement permits BoundAttribute.BoundAnnotationDefaultAttr, diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/BootstrapMethodsAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/BootstrapMethodsAttribute.java index 26ef1d3ddaf..bbea96dc162 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/BootstrapMethodsAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/BootstrapMethodsAttribute.java @@ -32,7 +32,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code BootstrapMethods} attribute (JVMS {@jvms 4.7.23}), which serves as @@ -45,9 +44,8 @@ *

* The attribute was introduced in the Java SE Platform version 7. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface BootstrapMethodsAttribute extends Attribute permits BoundAttribute.BoundBootstrapMethodsAttribute, diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/CharacterRangeInfo.java b/src/java.base/share/classes/java/lang/classfile/attribute/CharacterRangeInfo.java index 126ba1037ce..ab37c372c29 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/CharacterRangeInfo.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/CharacterRangeInfo.java @@ -27,14 +27,12 @@ import java.lang.classfile.instruction.CharacterRange; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models a single character range in the {@link CharacterRangeTableAttribute}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface CharacterRangeInfo permits UnboundAttribute.UnboundCharacterRangeInfo { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/CharacterRangeTableAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/CharacterRangeTableAttribute.java index a4b79be62f0..42a8443f2f6 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/CharacterRangeTableAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/CharacterRangeTableAttribute.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * The CharacterRangeTable attribute is an optional variable-length attribute in @@ -58,9 +57,8 @@ *

* The attribute permits multiple instances in a given location. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface CharacterRangeTableAttribute extends Attribute permits BoundAttribute.BoundCharacterRangeTableAttribute, diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/CodeAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/CodeAttribute.java index 3342c2648ed..9bc9e975d12 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/CodeAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/CodeAttribute.java @@ -30,7 +30,6 @@ import java.lang.classfile.Label; import jdk.internal.classfile.impl.BoundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code Code} attribute (JVMS {@jvms 4.7.3}), appears on non-native, @@ -42,9 +41,8 @@ * Subsequent occurrence of the attribute takes precedence during the attributed * element build or transformation. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface CodeAttribute extends Attribute, CodeModel permits BoundAttribute.BoundCodeAttribute { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/CompilationIDAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/CompilationIDAttribute.java index 292b449c628..8311a8e045c 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/CompilationIDAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/CompilationIDAttribute.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code CompilationID} attribute (@@@ need reference), which can @@ -44,9 +43,8 @@ * Subsequent occurrence of the attribute takes precedence during the attributed * element build or transformation. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface CompilationIDAttribute extends Attribute, ClassElement permits BoundAttribute.BoundCompilationIDAttribute, diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/ConstantValueAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/ConstantValueAttribute.java index cd874648551..54f4742ab0c 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/ConstantValueAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/ConstantValueAttribute.java @@ -32,7 +32,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code ConstantValue} attribute (JVMS {@jvms 4.7.2}), which can appear on @@ -44,9 +43,8 @@ * Subsequent occurrence of the attribute takes precedence during the attributed * element build or transformation. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ConstantValueAttribute extends Attribute, FieldElement permits BoundAttribute.BoundConstantValueAttribute, diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/DeprecatedAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/DeprecatedAttribute.java index 47c85c4b6c1..9e470711e1f 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/DeprecatedAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/DeprecatedAttribute.java @@ -31,7 +31,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code Deprecated} attribute (JVMS {@jvms 4.7.15}), which can appear on @@ -41,9 +40,8 @@ *

* The attribute permits multiple instances in a given location. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface DeprecatedAttribute extends Attribute, ClassElement, MethodElement, FieldElement diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/EnclosingMethodAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/EnclosingMethodAttribute.java index c760fdee04b..06ded8c82a5 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/EnclosingMethodAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/EnclosingMethodAttribute.java @@ -37,7 +37,6 @@ import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code EnclosingMethod} attribute (JVMS {@jvms 4.7.7}), which can appear @@ -51,9 +50,8 @@ *

* The attribute was introduced in the Java SE Platform version 5.0. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface EnclosingMethodAttribute extends Attribute, ClassElement permits BoundAttribute.BoundEnclosingMethodAttribute, diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/ExceptionsAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/ExceptionsAttribute.java index 91f07d94de9..67732e10e81 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/ExceptionsAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/ExceptionsAttribute.java @@ -34,7 +34,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code Exceptions} attribute (JVMS {@jvms 4.7.5}), which can appear on @@ -46,9 +45,8 @@ * Subsequent occurrence of the attribute takes precedence during the attributed * element build or transformation. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ExceptionsAttribute extends Attribute, MethodElement permits BoundAttribute.BoundExceptionsAttribute, diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/InnerClassInfo.java b/src/java.base/share/classes/java/lang/classfile/attribute/InnerClassInfo.java index fca8cce7faa..6965d5fdfd2 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/InnerClassInfo.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/InnerClassInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,14 +34,12 @@ import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a single inner class in the {@link InnerClassesAttribute}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface InnerClassInfo permits UnboundAttribute.UnboundInnerClassInfo { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/InnerClassesAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/InnerClassesAttribute.java index 3b5d63822c4..463a29f9398 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/InnerClassesAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/InnerClassesAttribute.java @@ -31,7 +31,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code InnerClasses} attribute (JVMS {@jvms 4.7.6}), which can @@ -43,9 +42,8 @@ * Subsequent occurrence of the attribute takes precedence during the attributed * element build or transformation. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface InnerClassesAttribute extends Attribute, ClassElement permits BoundAttribute.BoundInnerClassesAttribute, diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/LineNumberInfo.java b/src/java.base/share/classes/java/lang/classfile/attribute/LineNumberInfo.java index 6e83284f6b1..7e148cec9c1 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/LineNumberInfo.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/LineNumberInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,14 +25,12 @@ package java.lang.classfile.attribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models a single line number in the {@link LineNumberTableAttribute}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface LineNumberInfo permits UnboundAttribute.UnboundLineNumberInfo { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/LineNumberTableAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/LineNumberTableAttribute.java index bb636a8113f..1c00745218a 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/LineNumberTableAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/LineNumberTableAttribute.java @@ -29,7 +29,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code LineNumberTable} attribute (JVMS {@jvms 4.7.12}), which can appear @@ -41,9 +40,8 @@ *

* The attribute permits multiple instances in a given location. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface LineNumberTableAttribute extends Attribute permits BoundAttribute.BoundLineNumberTableAttribute, diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/LocalVariableInfo.java b/src/java.base/share/classes/java/lang/classfile/attribute/LocalVariableInfo.java index 177fc842483..2b4030b46a6 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/LocalVariableInfo.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/LocalVariableInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,14 +30,12 @@ import jdk.internal.classfile.impl.BoundLocalVariable; import jdk.internal.classfile.impl.UnboundAttribute; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a single local variable in the {@link LocalVariableTableAttribute}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface LocalVariableInfo permits UnboundAttribute.UnboundLocalVariableInfo, BoundLocalVariable { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/LocalVariableTableAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/LocalVariableTableAttribute.java index ad4e732073e..8f44ab2905f 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/LocalVariableTableAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/LocalVariableTableAttribute.java @@ -29,7 +29,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code LocalVariableTable} attribute (JVMS {@jvms 4.7.13}), which can appear @@ -41,9 +40,8 @@ *

* The attribute permits multiple instances in a given location. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface LocalVariableTableAttribute extends Attribute permits BoundAttribute.BoundLocalVariableTableAttribute, UnboundAttribute.UnboundLocalVariableTableAttribute { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/LocalVariableTypeInfo.java b/src/java.base/share/classes/java/lang/classfile/attribute/LocalVariableTypeInfo.java index 6ba5b409b5b..e7a137102ae 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/LocalVariableTypeInfo.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/LocalVariableTypeInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,14 +28,12 @@ import jdk.internal.classfile.impl.BoundLocalVariableType; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models a single local variable in the {@link LocalVariableTypeTableAttribute}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface LocalVariableTypeInfo permits UnboundAttribute.UnboundLocalVariableTypeInfo, BoundLocalVariableType { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/LocalVariableTypeTableAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/LocalVariableTypeTableAttribute.java index 084b72d6838..2bf7b7a87b3 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/LocalVariableTypeTableAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/LocalVariableTypeTableAttribute.java @@ -30,7 +30,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code LocalVariableTypeTable} attribute (JVMS {@jvms 4.7.14}), which can appear @@ -44,9 +43,8 @@ *

* The attribute was introduced in the Java SE Platform version 5.0. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface LocalVariableTypeTableAttribute extends Attribute permits BoundAttribute.BoundLocalVariableTypeTableAttribute, UnboundAttribute.UnboundLocalVariableTypeTableAttribute { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/MethodParameterInfo.java b/src/java.base/share/classes/java/lang/classfile/attribute/MethodParameterInfo.java index b0961bf1476..35301a30284 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/MethodParameterInfo.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/MethodParameterInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,14 +33,12 @@ import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a single method parameter in the {@link MethodParametersAttribute}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface MethodParameterInfo permits UnboundAttribute.UnboundMethodParameterInfo { /** diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/MethodParametersAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/MethodParametersAttribute.java index 43a43d25bb7..3b3bacbbca5 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/MethodParametersAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/MethodParametersAttribute.java @@ -31,7 +31,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code MethodParameters} attribute (JVMS {@jvms 4.7.24}), which can @@ -45,9 +44,8 @@ *

* The attribute was introduced in the Java SE Platform version 8. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface MethodParametersAttribute extends Attribute, MethodElement permits BoundAttribute.BoundMethodParametersAttribute, diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleAttribute.java index 7091bbd5c42..07e0f2baa12 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleAttribute.java @@ -43,7 +43,6 @@ import jdk.internal.classfile.impl.ModuleAttributeBuilderImpl; import jdk.internal.classfile.impl.UnboundAttribute; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code Module} attribute (JVMS {@jvms 4.7.25}), which can @@ -57,9 +56,8 @@ *

* The attribute was introduced in the Java SE Platform version 9. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ModuleAttribute extends Attribute, ClassElement permits BoundAttribute.BoundModuleAttribute, UnboundAttribute.UnboundModuleAttribute { @@ -172,9 +170,8 @@ static ModuleAttribute of(ModuleEntry moduleName, /** * A builder for module attributes. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ModuleAttributeBuilder permits ModuleAttributeBuilderImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleExportInfo.java b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleExportInfo.java index 4a534894e9e..69290c55994 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleExportInfo.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleExportInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,14 +37,12 @@ import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a single "exports" declaration in the {@link ModuleAttribute}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ModuleExportInfo permits UnboundAttribute.UnboundModuleExportInfo { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleHashInfo.java b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleHashInfo.java index 0c85dd14125..07616757daa 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleHashInfo.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleHashInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,14 +29,12 @@ import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models hash information for a single module in the {@link ModuleHashesAttribute}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ModuleHashInfo permits UnboundAttribute.UnboundModuleHashInfo { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleHashesAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleHashesAttribute.java index 0d2eb701484..918d18bda1e 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleHashesAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleHashesAttribute.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,7 +33,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code ModuleHashes} attribute, which can @@ -68,9 +67,8 @@ * Subsequent occurrence of the attribute takes precedence during the attributed * element build or transformation. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ModuleHashesAttribute extends Attribute, ClassElement permits BoundAttribute.BoundModuleHashesAttribute, UnboundAttribute.UnboundModuleHashesAttribute { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleMainClassAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleMainClassAttribute.java index 67d6e5cc15c..7f06eb0f95b 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleMainClassAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleMainClassAttribute.java @@ -33,7 +33,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code ModuleMainClass} attribute (JVMS {@jvms 4.7.27}), which can @@ -47,9 +46,8 @@ *

* The attribute was introduced in the Java SE Platform version 9. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ModuleMainClassAttribute extends Attribute, ClassElement permits BoundAttribute.BoundModuleMainClassAttribute, UnboundAttribute.UnboundModuleMainClassAttribute { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleOpenInfo.java b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleOpenInfo.java index 7c5fe948d78..a16c9973627 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleOpenInfo.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleOpenInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,14 +36,12 @@ import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a single "opens" declaration in the {@link ModuleAttribute}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ModuleOpenInfo permits UnboundAttribute.UnboundModuleOpenInfo { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/ModulePackagesAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/ModulePackagesAttribute.java index f2b34ad107d..ec0a65742b4 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/ModulePackagesAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/ModulePackagesAttribute.java @@ -34,7 +34,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code ModulePackages} attribute (JVMS {@jvms 4.7.26}), which can @@ -48,9 +47,8 @@ *

* The attribute was introduced in the Java SE Platform version 9. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ModulePackagesAttribute extends Attribute, ClassElement permits BoundAttribute.BoundModulePackagesAttribute, diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleProvideInfo.java b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleProvideInfo.java index 266c73de04f..ce68848d4dc 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleProvideInfo.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleProvideInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,14 +32,12 @@ import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a single "provides" declaration in the {@link ModuleAttribute}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ModuleProvideInfo permits UnboundAttribute.UnboundModuleProvideInfo { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleRequireInfo.java b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleRequireInfo.java index d072d0fead8..578a783f277 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleRequireInfo.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleRequireInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,14 +35,12 @@ import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a single "requires" declaration in the {@link ModuleAttribute}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ModuleRequireInfo permits UnboundAttribute.UnboundModuleRequiresInfo { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleResolutionAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleResolutionAttribute.java index a6b17fa4041..3457cb8073e 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleResolutionAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleResolutionAttribute.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code ModuleResolution} attribute, which can @@ -63,9 +62,8 @@ * Subsequent occurrence of the attribute takes precedence during the attributed * element build or transformation. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ModuleResolutionAttribute extends Attribute, ClassElement permits BoundAttribute.BoundModuleResolutionAttribute, UnboundAttribute.UnboundModuleResolutionAttribute { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleTargetAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleTargetAttribute.java index 226412eccf3..ac390c3d391 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/ModuleTargetAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/ModuleTargetAttribute.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code ModuleTarget} attribute, which can @@ -58,9 +57,8 @@ * Subsequent occurrence of the attribute takes precedence during the attributed * element build or transformation. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ModuleTargetAttribute extends Attribute, ClassElement permits BoundAttribute.BoundModuleTargetAttribute, UnboundAttribute.UnboundModuleTargetAttribute { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/NestHostAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/NestHostAttribute.java index 6b69f9cbe08..ccfb61242cd 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/NestHostAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/NestHostAttribute.java @@ -33,7 +33,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code NestHost} attribute (JVMS {@jvms 4.7.28}), which can @@ -47,9 +46,8 @@ *

* The attribute was introduced in the Java SE Platform version 11. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface NestHostAttribute extends Attribute, ClassElement permits BoundAttribute.BoundNestHostAttribute, UnboundAttribute.UnboundNestHostAttribute { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/NestMembersAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/NestMembersAttribute.java index 8826b4953a5..b01c05542de 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/NestMembersAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/NestMembersAttribute.java @@ -34,7 +34,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}), which can @@ -48,9 +47,8 @@ *

* The attribute was introduced in the Java SE Platform version 11. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface NestMembersAttribute extends Attribute, ClassElement permits BoundAttribute.BoundNestMembersAttribute, UnboundAttribute.UnboundNestMembersAttribute { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/PermittedSubclassesAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/PermittedSubclassesAttribute.java index 1242bc6e045..dac63c73435 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/PermittedSubclassesAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/PermittedSubclassesAttribute.java @@ -34,7 +34,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code PermittedSubclasses} attribute (JVMS {@jvms 4.7.31}), which can @@ -48,9 +47,8 @@ *

* The attribute was introduced in the Java SE Platform version 17. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface PermittedSubclassesAttribute extends Attribute, ClassElement permits BoundAttribute.BoundPermittedSubclassesAttribute, UnboundAttribute.UnboundPermittedSubclassesAttribute { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/RecordAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/RecordAttribute.java index 7ef3b6f41b6..b0c4fa7c61c 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/RecordAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/RecordAttribute.java @@ -31,7 +31,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code Record} attribute (JVMS {@jvms 4.7.30}), which can @@ -45,9 +44,8 @@ *

* The attribute was introduced in the Java SE Platform version 16. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface RecordAttribute extends Attribute, ClassElement permits BoundAttribute.BoundRecordAttribute, UnboundAttribute.UnboundRecordAttribute { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/RecordComponentInfo.java b/src/java.base/share/classes/java/lang/classfile/attribute/RecordComponentInfo.java index ef6385653ed..73e4497915e 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/RecordComponentInfo.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/RecordComponentInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,14 +34,12 @@ import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a single record component in the {@link java.lang.classfile.attribute.RecordAttribute}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface RecordComponentInfo extends AttributedElement permits BoundRecordComponentInfo, UnboundAttribute.UnboundRecordComponentInfo { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeInvisibleAnnotationsAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeInvisibleAnnotationsAttribute.java index 05635af4beb..58903859464 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeInvisibleAnnotationsAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeInvisibleAnnotationsAttribute.java @@ -34,7 +34,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code RuntimeInvisibleAnnotations} attribute (JVMS {@jvms 4.7.17}), which @@ -48,9 +47,8 @@ *

* The attribute was introduced in the Java SE Platform version 5.0. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface RuntimeInvisibleAnnotationsAttribute extends Attribute, ClassElement, MethodElement, FieldElement diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeInvisibleParameterAnnotationsAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeInvisibleParameterAnnotationsAttribute.java index edb82c49900..f1c02b77e1e 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeInvisibleParameterAnnotationsAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeInvisibleParameterAnnotationsAttribute.java @@ -33,7 +33,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code RuntimeInvisibleParameterAnnotations} attribute @@ -46,9 +45,8 @@ *

* The attribute was introduced in the Java SE Platform version 5.0. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface RuntimeInvisibleParameterAnnotationsAttribute extends Attribute, MethodElement permits BoundAttribute.BoundRuntimeInvisibleParameterAnnotationsAttribute, diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeInvisibleTypeAnnotationsAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeInvisibleTypeAnnotationsAttribute.java index df3a035d620..7500d39fc19 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeInvisibleTypeAnnotationsAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeInvisibleTypeAnnotationsAttribute.java @@ -35,7 +35,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code RuntimeInvisibleTypeAnnotations} attribute (JVMS {@jvms 4.7.21}), which @@ -50,9 +49,8 @@ *

* The attribute was introduced in the Java SE Platform version 8. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface RuntimeInvisibleTypeAnnotationsAttribute extends Attribute, ClassElement, MethodElement, FieldElement, CodeElement diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeVisibleAnnotationsAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeVisibleAnnotationsAttribute.java index 69095188818..d41fcf3794b 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeVisibleAnnotationsAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeVisibleAnnotationsAttribute.java @@ -34,7 +34,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code RuntimeVisibleAnnotations} attribute (JVMS {@jvms 4.7.16}), which @@ -48,9 +47,8 @@ *

* The attribute was introduced in the Java SE Platform version 5.0. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface RuntimeVisibleAnnotationsAttribute extends Attribute, ClassElement, MethodElement, FieldElement diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeVisibleParameterAnnotationsAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeVisibleParameterAnnotationsAttribute.java index ef58d21f14a..5ed9817eeb9 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeVisibleParameterAnnotationsAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeVisibleParameterAnnotationsAttribute.java @@ -33,7 +33,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code RuntimeVisibleParameterAnnotations} attribute (JVMS {@jvms 4.7.18}), which @@ -46,9 +45,8 @@ *

* The attribute was introduced in the Java SE Platform version 5.0. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface RuntimeVisibleParameterAnnotationsAttribute extends Attribute, MethodElement permits BoundAttribute.BoundRuntimeVisibleParameterAnnotationsAttribute, diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeVisibleTypeAnnotationsAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeVisibleTypeAnnotationsAttribute.java index 20dc89d700c..a4e780c4536 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeVisibleTypeAnnotationsAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/RuntimeVisibleTypeAnnotationsAttribute.java @@ -35,7 +35,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code RuntimeVisibleTypeAnnotations} attribute (JVMS {@jvms 4.7.20}), which @@ -50,9 +49,8 @@ *

* The attribute was introduced in the Java SE Platform version 8. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface RuntimeVisibleTypeAnnotationsAttribute extends Attribute, ClassElement, MethodElement, FieldElement, CodeElement diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/SignatureAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/SignatureAttribute.java index ca4cc62852a..8f06e16a1b1 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/SignatureAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/SignatureAttribute.java @@ -31,7 +31,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code Signature} attribute (JVMS {@jvms 4.7.9}), which @@ -46,9 +45,8 @@ *

* The attribute was introduced in the Java SE Platform version 5.0. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface SignatureAttribute extends Attribute, ClassElement, MethodElement, FieldElement diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/SourceDebugExtensionAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/SourceDebugExtensionAttribute.java index e181b7fb14a..0e6b7267263 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/SourceDebugExtensionAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/SourceDebugExtensionAttribute.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code SourceDebugExtension} attribute. @@ -43,9 +42,8 @@ *

* The attribute was introduced in the Java SE Platform version 5.0. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface SourceDebugExtensionAttribute extends Attribute, ClassElement permits BoundAttribute.BoundSourceDebugExtensionAttribute, UnboundAttribute.UnboundSourceDebugExtensionAttribute { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/SourceFileAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/SourceFileAttribute.java index d6c40058e7b..70f3d1e72ce 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/SourceFileAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/SourceFileAttribute.java @@ -33,7 +33,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code SourceFile} attribute (JVMS {@jvms 4.7.10}), which @@ -44,9 +43,8 @@ * Subsequent occurrence of the attribute takes precedence during the attributed * element build or transformation. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface SourceFileAttribute extends Attribute, ClassElement permits BoundAttribute.BoundSourceFileAttribute, UnboundAttribute.UnboundSourceFileAttribute { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/SourceIDAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/SourceIDAttribute.java index 69ff3bf57fd..71fd9d5b059 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/SourceIDAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/SourceIDAttribute.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,7 +33,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code SourceID} attribute, which can @@ -44,9 +43,8 @@ * Subsequent occurrence of the attribute takes precedence during the attributed * element build or transformation. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface SourceIDAttribute extends Attribute, ClassElement permits BoundAttribute.BoundSourceIDAttribute, UnboundAttribute.UnboundSourceIDAttribute { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/StackMapFrameInfo.java b/src/java.base/share/classes/java/lang/classfile/attribute/StackMapFrameInfo.java index d041a73c58a..920db8ac9d7 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/StackMapFrameInfo.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/StackMapFrameInfo.java @@ -32,14 +32,12 @@ import jdk.internal.classfile.impl.StackMapDecoder; import jdk.internal.classfile.impl.TemporaryConstantPool; -import jdk.internal.javac.PreviewFeature; /** * Models stack map frame of {@code StackMapTable} attribute (JVMS {@jvms 4.7.4}). * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface StackMapFrameInfo permits StackMapDecoder.StackMapFrameImpl { @@ -79,9 +77,8 @@ public static StackMapFrameInfo of(Label target, /** * The type of a stack value. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface VerificationTypeInfo { /** The {@link #tag() tag} for verification type info {@link SimpleVerificationTypeInfo#TOP TOP}. */ @@ -124,9 +121,8 @@ sealed interface VerificationTypeInfo { /** * A simple stack value. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public enum SimpleVerificationTypeInfo implements VerificationTypeInfo { /** verification type top */ @@ -166,9 +162,8 @@ public int tag() { /** * A stack value for an object type. Its {@link #tag() tag} is {@value #ITEM_OBJECT}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface ObjectVerificationTypeInfo extends VerificationTypeInfo permits StackMapDecoder.ObjectVerificationTypeInfoImpl { @@ -205,9 +200,8 @@ default ClassDesc classSymbol() { /** * An uninitialized stack value. Its {@link #tag() tag} is {@value #ITEM_UNINITIALIZED}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface UninitializedVerificationTypeInfo extends VerificationTypeInfo permits StackMapDecoder.UninitializedVerificationTypeInfoImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/StackMapTableAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/StackMapTableAttribute.java index a8aef4795d7..0d577fb6cd5 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/StackMapTableAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/StackMapTableAttribute.java @@ -31,7 +31,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code StackMapTable} attribute (JVMS {@jvms 4.7.4}), which can appear @@ -43,9 +42,8 @@ *

* The attribute was introduced in the Java SE Platform version 6. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface StackMapTableAttribute extends Attribute, CodeElement permits BoundAttribute.BoundStackMapTableAttribute, UnboundAttribute.UnboundStackMapTableAttribute { diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/SyntheticAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/SyntheticAttribute.java index e5b5da7fbfe..1e6b706ec08 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/SyntheticAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/SyntheticAttribute.java @@ -32,7 +32,6 @@ import jdk.internal.classfile.impl.BoundAttribute; import jdk.internal.classfile.impl.UnboundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models the {@code Synthetic} attribute (JVMS {@jvms 4.7.8}), which can appear on @@ -42,9 +41,8 @@ *

* The attribute permits multiple instances in a given location. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface SyntheticAttribute extends Attribute, ClassElement, MethodElement, FieldElement diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/UnknownAttribute.java b/src/java.base/share/classes/java/lang/classfile/attribute/UnknownAttribute.java index 5c1369e1308..ad47f35a856 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/UnknownAttribute.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/UnknownAttribute.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,12 @@ import java.lang.classfile.MethodElement; import jdk.internal.classfile.impl.BoundAttribute; -import jdk.internal.javac.PreviewFeature; /** * Models an unknown attribute on a class, method, or field. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface UnknownAttribute extends Attribute, ClassElement, MethodElement, FieldElement diff --git a/src/java.base/share/classes/java/lang/classfile/attribute/package-info.java b/src/java.base/share/classes/java/lang/classfile/attribute/package-info.java index 3047ef659e5..08bd28cbc58 100644 --- a/src/java.base/share/classes/java/lang/classfile/attribute/package-info.java +++ b/src/java.base/share/classes/java/lang/classfile/attribute/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved. * 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,9 +28,7 @@ * * The {@code java.lang.classfile.attribute} package contains interfaces describing classfile attributes. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) package java.lang.classfile.attribute; -import jdk.internal.javac.PreviewFeature; diff --git a/src/java.base/share/classes/java/lang/classfile/components/ClassPrinter.java b/src/java.base/share/classes/java/lang/classfile/components/ClassPrinter.java index 85768cbe6a4..7237dc54580 100644 --- a/src/java.base/share/classes/java/lang/classfile/components/ClassPrinter.java +++ b/src/java.base/share/classes/java/lang/classfile/components/ClassPrinter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,7 +36,6 @@ import java.util.stream.Stream; import jdk.internal.classfile.impl.ClassPrinterImpl; -import jdk.internal.javac.PreviewFeature; /** * A printer of classfiles and its elements. @@ -60,9 +59,8 @@ * Another use case for {@link ClassPrinter} is to simplify writing of automated tests: * {@snippet lang="java" class="PackageSnippets" region="printNodesInTest"} * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public final class ClassPrinter { private ClassPrinter() { @@ -71,9 +69,8 @@ private ClassPrinter() { /** * Level of detail to print or export. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public enum Verbosity { /** @@ -106,9 +103,8 @@ public enum Verbosity { /** * Named, traversable, and printable node parent. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface Node { /** @@ -151,9 +147,8 @@ default void toYaml(Consumer out) { /** * A leaf node holding single printable value. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface LeafNode extends Node permits ClassPrinterImpl.LeafNodeImpl { @@ -167,9 +162,8 @@ public sealed interface LeafNode extends Node /** * A tree node holding {@link List} of nested nodes. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ListNode extends Node, List permits ClassPrinterImpl.ListNodeImpl { } @@ -179,9 +173,8 @@ public sealed interface ListNode extends Node, List *

* Each {@link Map.Entry#getKey()} == {@link Map.Entry#getValue()}.{@link #name()}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface MapNode extends Node, Map permits ClassPrinterImpl.MapNodeImpl { } diff --git a/src/java.base/share/classes/java/lang/classfile/components/ClassRemapper.java b/src/java.base/share/classes/java/lang/classfile/components/ClassRemapper.java index 4f7bd3199d5..4a2808ad4f0 100644 --- a/src/java.base/share/classes/java/lang/classfile/components/ClassRemapper.java +++ b/src/java.base/share/classes/java/lang/classfile/components/ClassRemapper.java @@ -35,7 +35,6 @@ import java.util.function.Function; import jdk.internal.classfile.impl.ClassRemapperImpl; -import jdk.internal.javac.PreviewFeature; import static java.util.Objects.requireNonNull; @@ -55,9 +54,8 @@ * Arrays of reference types are always decomposed, mapped as the base reference * types and composed back to arrays. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ClassRemapper extends ClassTransform permits ClassRemapperImpl { /** diff --git a/src/java.base/share/classes/java/lang/classfile/components/CodeLocalsShifter.java b/src/java.base/share/classes/java/lang/classfile/components/CodeLocalsShifter.java index 49838722461..9db85f54a45 100644 --- a/src/java.base/share/classes/java/lang/classfile/components/CodeLocalsShifter.java +++ b/src/java.base/share/classes/java/lang/classfile/components/CodeLocalsShifter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,6 @@ import java.lang.reflect.AccessFlag; import jdk.internal.classfile.impl.CodeLocalsShifterImpl; -import jdk.internal.javac.PreviewFeature; /** * {@link CodeLocalsShifter} is a {@link CodeTransform} shifting locals to @@ -39,9 +38,8 @@ * Locals pointing to the receiver or to method arguments slots are never shifted. * All locals pointing beyond the method arguments are re-indexed in order of appearance. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface CodeLocalsShifter extends CodeTransform permits CodeLocalsShifterImpl { /** diff --git a/src/java.base/share/classes/java/lang/classfile/components/CodeRelabeler.java b/src/java.base/share/classes/java/lang/classfile/components/CodeRelabeler.java index 247d712e4f3..4ef82adfdb9 100644 --- a/src/java.base/share/classes/java/lang/classfile/components/CodeRelabeler.java +++ b/src/java.base/share/classes/java/lang/classfile/components/CodeRelabeler.java @@ -32,7 +32,6 @@ import java.util.function.BiFunction; import jdk.internal.classfile.impl.CodeRelabelerImpl; -import jdk.internal.javac.PreviewFeature; import static java.util.Objects.requireNonNull; @@ -46,9 +45,8 @@ * Repeated injection of the same code block must be relabeled, so each instance of * {@link java.lang.classfile.Label} is bound in the target bytecode exactly once. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface CodeRelabeler extends CodeTransform permits CodeRelabelerImpl { /** diff --git a/src/java.base/share/classes/java/lang/classfile/components/CodeStackTracker.java b/src/java.base/share/classes/java/lang/classfile/components/CodeStackTracker.java index 1ee0b0948e1..3761e53ff19 100644 --- a/src/java.base/share/classes/java/lang/classfile/components/CodeStackTracker.java +++ b/src/java.base/share/classes/java/lang/classfile/components/CodeStackTracker.java @@ -31,7 +31,6 @@ import java.util.Optional; import jdk.internal.classfile.impl.CodeStackTrackerImpl; -import jdk.internal.javac.PreviewFeature; /** * {@link CodeStackTracker} is a {@link CodeTransform} tracking stack content @@ -51,9 +50,8 @@ * }); * } * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface CodeStackTracker extends CodeTransform permits CodeStackTrackerImpl { /** diff --git a/src/java.base/share/classes/java/lang/classfile/components/package-info.java b/src/java.base/share/classes/java/lang/classfile/components/package-info.java index 98a0095587d..be650f4c77c 100644 --- a/src/java.base/share/classes/java/lang/classfile/components/package-info.java +++ b/src/java.base/share/classes/java/lang/classfile/components/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -111,9 +111,7 @@ * instrumenting transformation: * {@snippet lang="java" class="PackageSnippets" region="classInstrumentation"} * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) package java.lang.classfile.components; -import jdk.internal.javac.PreviewFeature; diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/AnnotationConstantValueEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/AnnotationConstantValueEntry.java index 6365fc3636a..5255ceb1ef7 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/AnnotationConstantValueEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/AnnotationConstantValueEntry.java @@ -27,8 +27,6 @@ import java.lang.classfile.AnnotationValue; import java.lang.constant.ConstantDesc; -import jdk.internal.javac.PreviewFeature; - /** * A constant pool entry that may be used by annotation constant values, * which includes the four kinds of primitive constants and UTF8 constants. @@ -43,9 +41,8 @@ * * @see AnnotationValue.OfConstant * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface AnnotationConstantValueEntry extends PoolEntry permits DoubleEntry, FloatEntry, IntegerEntry, LongEntry, Utf8Entry { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/ClassEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/ClassEntry.java index 9e5f1f52049..2a3bd95da22 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/ClassEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/ClassEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +28,14 @@ import java.lang.constant.ConstantDesc; import jdk.internal.classfile.impl.AbstractPoolEntry; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code CONSTANT_Class_info} constant in the constant pool of a * classfile. * @jvms 4.4.1 The CONSTANT_Class_info Structure * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ClassEntry extends LoadableConstantEntry permits AbstractPoolEntry.ClassEntryImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantDynamicEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantDynamicEntry.java index 7c55a09f3f4..72050cd9b8f 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantDynamicEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantDynamicEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +31,14 @@ import jdk.internal.classfile.impl.AbstractPoolEntry; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code CONSTANT_Dynamic_info} constant in the constant pool of a * classfile. * @jvms 4.4.10 The CONSTANT_Dynamic_info and CONSTANT_InvokeDynamic_info Structures * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ConstantDynamicEntry extends DynamicConstantPoolEntry, LoadableConstantEntry permits AbstractPoolEntry.ConstantDynamicEntryImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantPool.java b/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantPool.java index 0225f6ec77d..91dc8906b7b 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantPool.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantPool.java @@ -30,17 +30,14 @@ import java.util.Iterator; import java.util.NoSuchElementException; -import jdk.internal.javac.PreviewFeature; - /** * Provides read access to the constant pool and bootstrap method table of a * classfile. * @jvms 4.4 The Constant Pool * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ConstantPool extends Iterable permits ClassReader, ConstantPoolBuilder { @@ -70,7 +67,6 @@ public sealed interface ConstantPool extends Iterable * @param cls the entry type * @throws ConstantPoolException if the index is out of range of the * constant pool, or the entry is not of the given type - * @since 23 */ T entryByIndex(int index, Class cls); diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantPoolBuilder.java b/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantPoolBuilder.java index 0ce4a6868c8..2dc2a390bd1 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantPoolBuilder.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantPoolBuilder.java @@ -35,7 +35,6 @@ import jdk.internal.classfile.impl.SplitConstantPool; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; import static java.util.Objects.requireNonNull; @@ -48,9 +47,8 @@ * The {@linkplain ConstantPoolBuilder} also provides access to some of the * state of the {@linkplain ClassBuilder}, such as classfile processing options. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ConstantPoolBuilder extends ConstantPool permits SplitConstantPool, TemporaryConstantPool { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantPoolException.java b/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantPoolException.java index 260c9af64d4..ce5ed26c4c9 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantPoolException.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantPoolException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved. * 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,15 +24,13 @@ */ package java.lang.classfile.constantpool; -import jdk.internal.javac.PreviewFeature; /** * Thrown to indicate that requested entry cannot be obtained from the constant * pool. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public class ConstantPoolException extends IllegalArgumentException { @java.io.Serial diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantValueEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantValueEntry.java index 924d0aca710..ae746042aa4 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantValueEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/ConstantValueEntry.java @@ -27,17 +27,14 @@ import java.lang.classfile.Attributes; import java.lang.constant.ConstantDesc; -import jdk.internal.javac.PreviewFeature; - /** * Models a constant pool entry that can be used as the constant in a * {@link Attributes#constantValue() ConstantValue} attribute; this includes the four * primitive constant types and {@linkplain String} constants. * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ConstantValueEntry extends LoadableConstantEntry permits DoubleEntry, FloatEntry, IntegerEntry, LongEntry, StringEntry { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/DoubleEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/DoubleEntry.java index 8dd4ba1ffd9..ebc3a837bb0 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/DoubleEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/DoubleEntry.java @@ -27,16 +27,14 @@ import java.lang.classfile.TypeKind; import jdk.internal.classfile.impl.AbstractPoolEntry; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code CONSTANT_Double_info} constant in the constant pool of a * classfile. * @jvms 4.4.5 The CONSTANT_Long_info and CONSTANT_Double_info Structures * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface DoubleEntry extends AnnotationConstantValueEntry, ConstantValueEntry permits AbstractPoolEntry.DoubleEntryImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/DynamicConstantPoolEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/DynamicConstantPoolEntry.java index ac763049410..3ec4fbbdbee 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/DynamicConstantPoolEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/DynamicConstantPoolEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,17 +26,14 @@ import java.lang.classfile.BootstrapMethodEntry; -import jdk.internal.javac.PreviewFeature; - /** * Models a dynamic constant pool entry, which is either {@link ConstantDynamicEntry} * or {@link InvokeDynamicEntry}. * @jvms 4.4.10 The CONSTANT_Dynamic_info and CONSTANT_InvokeDynamic_info Structures * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface DynamicConstantPoolEntry extends PoolEntry permits ConstantDynamicEntry, InvokeDynamicEntry { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/FieldRefEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/FieldRefEntry.java index ab122f410b6..47f5b6710d8 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/FieldRefEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/FieldRefEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +28,14 @@ import jdk.internal.classfile.impl.AbstractPoolEntry; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code CONSTANT_Fieldref_info} constant in the constant pool of a * classfile. * @jvms 4.4.2 The CONSTANT_Fieldref_info, CONSTANT_Methodref_info, and CONSTANT_InterfaceMethodref_info Structures * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface FieldRefEntry extends MemberRefEntry permits AbstractPoolEntry.FieldRefEntryImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/FloatEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/FloatEntry.java index 7a91dd11153..eeb44e92b7c 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/FloatEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/FloatEntry.java @@ -27,16 +27,14 @@ import java.lang.classfile.TypeKind; import jdk.internal.classfile.impl.AbstractPoolEntry; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code CONSTANT_Float_info} constant in the constant pool of a * classfile. * @jvms 4.4.4 The CONSTANT_Integer_info and CONSTANT_Float_info Structures * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface FloatEntry extends AnnotationConstantValueEntry, ConstantValueEntry permits AbstractPoolEntry.FloatEntryImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/IntegerEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/IntegerEntry.java index 7cd21e37db8..908f17d1cb7 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/IntegerEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/IntegerEntry.java @@ -27,16 +27,14 @@ import java.lang.classfile.TypeKind; import jdk.internal.classfile.impl.AbstractPoolEntry; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code CONSTANT_Integer_info} constant in the constant pool of a * classfile. * @jvms 4.4.4 The CONSTANT_Integer_info and CONSTANT_Float_info Structures * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface IntegerEntry extends AnnotationConstantValueEntry, ConstantValueEntry permits AbstractPoolEntry.IntegerEntryImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/InterfaceMethodRefEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/InterfaceMethodRefEntry.java index 8f15053e5b7..7b1a94f123a 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/InterfaceMethodRefEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/InterfaceMethodRefEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +28,14 @@ import jdk.internal.classfile.impl.AbstractPoolEntry; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code CONSTANT_InterfaceMethodRef_info} constant in the constant pool of a * classfile. * @jvms 4.4.2 The CONSTANT_Fieldref_info, CONSTANT_Methodref_info, and CONSTANT_InterfaceMethodref_info Structures * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface InterfaceMethodRefEntry extends MemberRefEntry permits AbstractPoolEntry.InterfaceMethodRefEntryImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/InvokeDynamicEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/InvokeDynamicEntry.java index f06c3d4c782..0cc8b6823df 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/InvokeDynamicEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/InvokeDynamicEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,15 +30,13 @@ import jdk.internal.classfile.impl.AbstractPoolEntry; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a constant pool entry for a dynamic call site. * @jvms 4.4.10 The CONSTANT_Dynamic_info and CONSTANT_InvokeDynamic_info Structures * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface InvokeDynamicEntry extends DynamicConstantPoolEntry permits AbstractPoolEntry.InvokeDynamicEntryImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/LoadableConstantEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/LoadableConstantEntry.java index c963e2425ea..32f85f64c7e 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/LoadableConstantEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/LoadableConstantEntry.java @@ -27,16 +27,13 @@ import java.lang.classfile.TypeKind; import java.lang.constant.ConstantDesc; -import jdk.internal.javac.PreviewFeature; - /** * Marker interface for constant pool entries suitable for loading via the * {@code LDC} instructions. * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface LoadableConstantEntry extends PoolEntry permits ClassEntry, ConstantDynamicEntry, ConstantValueEntry, MethodHandleEntry, MethodTypeEntry { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/LongEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/LongEntry.java index 75e02b19441..cd38dcfe014 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/LongEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/LongEntry.java @@ -27,16 +27,14 @@ import java.lang.classfile.TypeKind; import jdk.internal.classfile.impl.AbstractPoolEntry; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code CONSTANT_Long_info} constant in the constant pool of a * classfile. * @jvms 4.4.5 The CONSTANT_Long_info and CONSTANT_Double_info Structures * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface LongEntry extends AnnotationConstantValueEntry, ConstantValueEntry permits AbstractPoolEntry.LongEntryImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/MemberRefEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/MemberRefEntry.java index 7c9292c8f04..12d68796dd7 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/MemberRefEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/MemberRefEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +25,14 @@ package java.lang.classfile.constantpool; import jdk.internal.classfile.impl.AbstractPoolEntry; -import jdk.internal.javac.PreviewFeature; /** * Models a member reference constant in the constant pool of a classfile, * which includes references to fields, methods, and interface methods. * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface MemberRefEntry extends PoolEntry permits FieldRefEntry, InterfaceMethodRefEntry, MethodRefEntry, AbstractPoolEntry.AbstractMemberRefEntry { /** diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/MethodHandleEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/MethodHandleEntry.java index 37ec30648ab..d2e08ef178c 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/MethodHandleEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/MethodHandleEntry.java @@ -28,16 +28,14 @@ import java.lang.constant.DirectMethodHandleDesc; import jdk.internal.classfile.impl.AbstractPoolEntry; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code CONSTANT_MethodHandle_info} constant in the constant pool of a * classfile. * @jvms 4.4.8 The CONSTANT_MethodHandle_info Structure * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface MethodHandleEntry extends LoadableConstantEntry permits AbstractPoolEntry.MethodHandleEntryImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/MethodRefEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/MethodRefEntry.java index ff3f5e5220c..5be9e88fa2f 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/MethodRefEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/MethodRefEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +28,14 @@ import jdk.internal.classfile.impl.AbstractPoolEntry; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code CONSTANT_MethodRef_info} constant in the constant pool of a * classfile. * @jvms 4.4.2 The CONSTANT_Fieldref_info, CONSTANT_Methodref_info, and CONSTANT_InterfaceMethodref_info Structures * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface MethodRefEntry extends MemberRefEntry permits AbstractPoolEntry.MethodRefEntryImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/MethodTypeEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/MethodTypeEntry.java index d626aeb4900..b6fad856358 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/MethodTypeEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/MethodTypeEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +28,14 @@ import java.lang.constant.MethodTypeDesc; import jdk.internal.classfile.impl.AbstractPoolEntry; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code CONSTANT_MethodType_info} constant in the constant pool of a * classfile. * @jvms 4.4.9 The CONSTANT_MethodType_info Structure * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface MethodTypeEntry extends LoadableConstantEntry permits AbstractPoolEntry.MethodTypeEntryImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/ModuleEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/ModuleEntry.java index db7aa1f76fe..d0cdae5678f 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/ModuleEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/ModuleEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +27,14 @@ import java.lang.constant.ModuleDesc; import jdk.internal.classfile.impl.AbstractPoolEntry; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code CONSTANT_Module_info} constant in the constant pool of a * classfile. * @jvms 4.4.11 The CONSTANT_Module_info Structure * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ModuleEntry extends PoolEntry permits AbstractPoolEntry.ModuleEntryImpl { /** diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/NameAndTypeEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/NameAndTypeEntry.java index d4beff2aff7..eff7e3456d1 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/NameAndTypeEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/NameAndTypeEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +25,14 @@ package java.lang.classfile.constantpool; import jdk.internal.classfile.impl.AbstractPoolEntry; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code CONSTANT_NameAndType_info} constant in the constant pool of a * classfile. * @jvms 4.4.6 The CONSTANT_NameAndType_info Structure * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface NameAndTypeEntry extends PoolEntry permits AbstractPoolEntry.NameAndTypeEntryImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/PackageEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/PackageEntry.java index 5725d411028..54ea2fc38e5 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/PackageEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/PackageEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +27,14 @@ import java.lang.constant.PackageDesc; import jdk.internal.classfile.impl.AbstractPoolEntry; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code CONSTANT_Package_info} constant in the constant pool of a * classfile. * @jvms 4.4.12 The CONSTANT_Package_info Structure * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface PackageEntry extends PoolEntry permits AbstractPoolEntry.PackageEntryImpl { /** diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/PoolEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/PoolEntry.java index d2af4c7c11a..fdb8b497ff9 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/PoolEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/PoolEntry.java @@ -24,15 +24,12 @@ */ package java.lang.classfile.constantpool; -import jdk.internal.javac.PreviewFeature; - /** * Models an entry in the constant pool of a classfile. * * @sealedGraph - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface PoolEntry permits AnnotationConstantValueEntry, DynamicConstantPoolEntry, LoadableConstantEntry, MemberRefEntry, ModuleEntry, NameAndTypeEntry, diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/StringEntry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/StringEntry.java index 65f75a6a062..03ff7652f67 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/StringEntry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/StringEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +25,14 @@ package java.lang.classfile.constantpool; import jdk.internal.classfile.impl.AbstractPoolEntry; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code CONSTANT_String_info} constant in the constant pool of a * classfile. * @jvms 4.4.3 The CONSTANT_String_info Structure * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface StringEntry extends ConstantValueEntry permits AbstractPoolEntry.StringEntryImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/Utf8Entry.java b/src/java.base/share/classes/java/lang/classfile/constantpool/Utf8Entry.java index b379854cfcb..db03bf6a403 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/Utf8Entry.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/Utf8Entry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +25,14 @@ package java.lang.classfile.constantpool; import jdk.internal.classfile.impl.AbstractPoolEntry; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code CONSTANT_UTF8_info} constant in the constant pool of a * classfile. * @jvms 4.4.7 The CONSTANT_Utf8_info Structure * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface Utf8Entry extends CharSequence, AnnotationConstantValueEntry permits AbstractPoolEntry.Utf8EntryImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/constantpool/package-info.java b/src/java.base/share/classes/java/lang/classfile/constantpool/package-info.java index 1ba2b63b6a1..83039c6565c 100644 --- a/src/java.base/share/classes/java/lang/classfile/constantpool/package-info.java +++ b/src/java.base/share/classes/java/lang/classfile/constantpool/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved. * 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,9 +28,7 @@ * * The {@code java.lang.classfile.constantpool} package contains interfaces describing classfile constant pool entries. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) package java.lang.classfile.constantpool; -import jdk.internal.javac.PreviewFeature; diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/ArrayLoadInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/ArrayLoadInstruction.java index b66627ef212..cc0e0b89f80 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/ArrayLoadInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/ArrayLoadInstruction.java @@ -32,7 +32,6 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models an array load instruction in the {@code code} array of a {@code Code} @@ -40,9 +39,8 @@ * Opcode.Kind#ARRAY_LOAD}. Delivered as a {@link CodeElement} when * traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ArrayLoadInstruction extends Instruction permits AbstractInstruction.UnboundArrayLoadInstruction { /** diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/ArrayStoreInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/ArrayStoreInstruction.java index f009cfca361..c350b3a5928 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/ArrayStoreInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/ArrayStoreInstruction.java @@ -32,7 +32,6 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models an array store instruction in the {@code code} array of a {@code Code} @@ -40,9 +39,8 @@ * Opcode.Kind#ARRAY_STORE}. Delivered as a {@link CodeElement} when * traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ArrayStoreInstruction extends Instruction permits AbstractInstruction.UnboundArrayStoreInstruction { /** diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/BranchInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/BranchInstruction.java index 6b2142fa0e1..2fdc00fced1 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/BranchInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/BranchInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,6 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a branching instruction (conditional or unconditional) in the {@code @@ -40,9 +39,8 @@ * {@code kind} of {@link Opcode.Kind#BRANCH}. Delivered as a {@link * CodeElement} when traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface BranchInstruction extends Instruction permits AbstractInstruction.BoundBranchInstruction, AbstractInstruction.UnboundBranchInstruction { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/CharacterRange.java b/src/java.base/share/classes/java/lang/classfile/instruction/CharacterRange.java index 3d04473ab37..d47639d7dd7 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/CharacterRange.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/CharacterRange.java @@ -34,7 +34,6 @@ import jdk.internal.classfile.impl.AbstractPseudoInstruction; import jdk.internal.classfile.impl.BoundCharacterRange; -import jdk.internal.javac.PreviewFeature; /** * A pseudo-instruction which models a single entry in the @@ -42,9 +41,8 @@ * during traversal of the elements of a {@link CodeModel}, according to * the setting of the {@link ClassFile.DebugElementsOption} option. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface CharacterRange extends PseudoInstruction permits AbstractPseudoInstruction.UnboundCharacterRange, BoundCharacterRange { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/ConstantInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/ConstantInstruction.java index c41793c614e..312c1868f19 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/ConstantInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/ConstantInstruction.java @@ -35,7 +35,6 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.BytecodeHelpers; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a constant-load instruction in the {@code code} array of a {@code @@ -45,9 +44,8 @@ * a {@code kind} of {@link Opcode.Kind#CONSTANT}. Delivered as a {@link * CodeElement} when traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ConstantInstruction extends Instruction { /** @@ -64,9 +62,8 @@ public sealed interface ConstantInstruction extends Instruction { * Models an "intrinsic constant" instruction (e.g., {@code * iconst_0}). * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface IntrinsicConstantInstruction extends ConstantInstruction permits AbstractInstruction.UnboundIntrinsicConstantInstruction { @@ -83,9 +80,8 @@ default TypeKind typeKind() { * Models an "argument constant" instruction (e.g., {@code * bipush}). * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface ArgumentConstantInstruction extends ConstantInstruction permits AbstractInstruction.BoundArgumentConstantInstruction, AbstractInstruction.UnboundArgumentConstantInstruction { @@ -106,9 +102,8 @@ default TypeKind typeKind() { * Models a "load constant" instruction (e.g., {@code * ldc}). * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface LoadConstantInstruction extends ConstantInstruction permits AbstractInstruction.BoundLoadConstantInstruction, AbstractInstruction.UnboundLoadConstantInstruction { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/ConvertInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/ConvertInstruction.java index ec48c2f4663..468685779b9 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/ConvertInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/ConvertInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,7 +33,6 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.BytecodeHelpers; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a primitive conversion instruction in the {@code code} array of a @@ -41,9 +40,8 @@ * a {@code kind} of {@link Opcode.Kind#CONVERT}. Delivered as a {@link * CodeElement} when traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ConvertInstruction extends Instruction permits AbstractInstruction.UnboundConvertInstruction { /** diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/DiscontinuedInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/DiscontinuedInstruction.java index 0e4718a1c77..4e8ddcef385 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/DiscontinuedInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/DiscontinuedInstruction.java @@ -33,16 +33,14 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.BytecodeHelpers; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models instruction discontinued from the {@code code} array of a {@code Code} * attribute. Delivered as a {@link CodeElement} when traversing the elements of * a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface DiscontinuedInstruction extends Instruction { /** @@ -52,9 +50,8 @@ public sealed interface DiscontinuedInstruction extends Instruction { * {@link Opcode.Kind#DISCONTINUED_JSR}. Delivered as a {@link CodeElement} * when traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface JsrInstruction extends DiscontinuedInstruction permits AbstractInstruction.BoundJsrInstruction, AbstractInstruction.UnboundJsrInstruction { @@ -95,9 +92,8 @@ static JsrInstruction of(Label target) { * {@link Opcode.Kind#DISCONTINUED_RET}. Delivered as a {@link CodeElement} * when traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ - @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) sealed interface RetInstruction extends DiscontinuedInstruction permits AbstractInstruction.BoundRetInstruction, AbstractInstruction.UnboundRetInstruction { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/ExceptionCatch.java b/src/java.base/share/classes/java/lang/classfile/instruction/ExceptionCatch.java index 22b6f632abc..885f029d108 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/ExceptionCatch.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/ExceptionCatch.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,6 @@ import java.util.Optional; import jdk.internal.classfile.impl.AbstractPseudoInstruction; -import jdk.internal.javac.PreviewFeature; /** * A pseudo-instruction modeling an entry in the exception table of a code @@ -42,9 +41,8 @@ * * @see PseudoInstruction * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ExceptionCatch extends PseudoInstruction permits AbstractPseudoInstruction.ExceptionCatchImpl { /** diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/FieldInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/FieldInstruction.java index c8a82fe7dfa..b547abd18ab 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/FieldInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/FieldInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,7 +37,6 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a field access instruction in the {@code code} array of a {@code Code} @@ -45,9 +44,8 @@ * Opcode.Kind#FIELD_ACCESS}. Delivered as a {@link CodeElement} when * traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface FieldInstruction extends Instruction permits AbstractInstruction.BoundFieldInstruction, AbstractInstruction.UnboundFieldInstruction { /** diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/IncrementInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/IncrementInstruction.java index 74fd6a4465a..7ea516c7cc5 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/IncrementInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/IncrementInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,6 @@ import java.lang.classfile.Opcode; import jdk.internal.classfile.impl.AbstractInstruction; -import jdk.internal.javac.PreviewFeature; /** * Models a local variable increment instruction in the {@code code} array of a @@ -38,9 +37,8 @@ * {@link Opcode.Kind#INCREMENT}. Delivered as a {@link CodeElement} when * traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface IncrementInstruction extends Instruction permits AbstractInstruction.BoundIncrementInstruction, AbstractInstruction.UnboundIncrementInstruction { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/InvokeDynamicInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/InvokeDynamicInstruction.java index 6df960b88fa..43907b2a518 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/InvokeDynamicInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/InvokeDynamicInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,16 +38,14 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models an {@code invokedynamic} instruction in the {@code code} array of a * {@code Code} attribute. Delivered as a {@link CodeElement} when traversing * the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface InvokeDynamicInstruction extends Instruction permits AbstractInstruction.BoundInvokeDynamicInstruction, AbstractInstruction.UnboundInvokeDynamicInstruction { /** diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/InvokeInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/InvokeInstruction.java index 41ca5fd1519..904a17375ac 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/InvokeInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/InvokeInstruction.java @@ -39,7 +39,6 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a method invocation instruction in the {@code code} array of a {@code @@ -47,9 +46,8 @@ * will have a {@code kind} of {@link Opcode.Kind#INVOKE}. Delivered as a * {@link CodeElement} when traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface InvokeInstruction extends Instruction permits AbstractInstruction.BoundInvokeInterfaceInstruction, AbstractInstruction.BoundInvokeInstruction, AbstractInstruction.UnboundInvokeInstruction { /** diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/LabelTarget.java b/src/java.base/share/classes/java/lang/classfile/instruction/LabelTarget.java index 8682d0ee508..bc1deffc98b 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/LabelTarget.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/LabelTarget.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,6 @@ import java.lang.classfile.PseudoInstruction; import jdk.internal.classfile.impl.LabelImpl; -import jdk.internal.javac.PreviewFeature; /** * A pseudo-instruction which indicates that the specified label corresponds to @@ -39,9 +38,8 @@ * * @see PseudoInstruction * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface LabelTarget extends PseudoInstruction permits LabelImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/LineNumber.java b/src/java.base/share/classes/java/lang/classfile/instruction/LineNumber.java index a06e7cfceba..a9a497708c0 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/LineNumber.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/LineNumber.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,6 @@ import java.lang.classfile.attribute.LineNumberTableAttribute; import jdk.internal.classfile.impl.LineNumberImpl; -import jdk.internal.javac.PreviewFeature; /** * A pseudo-instruction which models a single entry in the @@ -41,9 +40,8 @@ * * @see PseudoInstruction * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface LineNumber extends PseudoInstruction permits LineNumberImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/LoadInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/LoadInstruction.java index ce6463ef924..c499dcc9944 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/LoadInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/LoadInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,7 +33,6 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.BytecodeHelpers; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a local variable load instruction in the {@code code} array of a @@ -41,9 +40,8 @@ * {@link Opcode.Kind#LOAD}. Delivered as a {@link CodeElement} when * traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface LoadInstruction extends Instruction permits AbstractInstruction.BoundLoadInstruction, AbstractInstruction.UnboundLoadInstruction { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/LocalVariable.java b/src/java.base/share/classes/java/lang/classfile/instruction/LocalVariable.java index 390034bd666..0f8cb672e51 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/LocalVariable.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/LocalVariable.java @@ -37,7 +37,6 @@ import jdk.internal.classfile.impl.BoundLocalVariable; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * A pseudo-instruction which models a single entry in the @@ -47,9 +46,8 @@ * * @see PseudoInstruction * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface LocalVariable extends PseudoInstruction permits AbstractPseudoInstruction.UnboundLocalVariable, BoundLocalVariable { /** diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/LocalVariableType.java b/src/java.base/share/classes/java/lang/classfile/instruction/LocalVariableType.java index d0d2cd1581f..c9427491733 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/LocalVariableType.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/LocalVariableType.java @@ -36,7 +36,6 @@ import jdk.internal.classfile.impl.AbstractPseudoInstruction; import jdk.internal.classfile.impl.BoundLocalVariableType; import jdk.internal.classfile.impl.TemporaryConstantPool; -import jdk.internal.javac.PreviewFeature; /** * A pseudo-instruction which models a single entry in the {@link @@ -44,9 +43,8 @@ * traversal of the elements of a {@link CodeModel}, according to the setting of * the {@link ClassFile.DebugElementsOption} option. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface LocalVariableType extends PseudoInstruction permits AbstractPseudoInstruction.UnboundLocalVariableType, BoundLocalVariableType { /** diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/LookupSwitchInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/LookupSwitchInstruction.java index ce6c0cce109..7b286e9cfd2 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/LookupSwitchInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/LookupSwitchInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +31,14 @@ import java.util.List; import jdk.internal.classfile.impl.AbstractInstruction; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code lookupswitch} instruction in the {@code code} array of a * {@code Code} attribute. Delivered as a {@link CodeElement} when traversing * the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface LookupSwitchInstruction extends Instruction permits AbstractInstruction.BoundLookupSwitchInstruction, AbstractInstruction.UnboundLookupSwitchInstruction { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/MonitorInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/MonitorInstruction.java index 9bec7805339..1c8268cddd6 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/MonitorInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/MonitorInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +31,14 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code monitorenter} or {@code monitorexit} instruction in the * {@code code} array of a {@code Code} attribute. Delivered as a {@link * CodeElement} when traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface MonitorInstruction extends Instruction permits AbstractInstruction.UnboundMonitorInstruction { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/NewMultiArrayInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/NewMultiArrayInstruction.java index f5e0129205c..4a1f6cfd170 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/NewMultiArrayInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/NewMultiArrayInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +31,14 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.BytecodeHelpers; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code multianewarray} invocation instruction in the {@code code} * array of a {@code Code} attribute. Delivered as a {@link CodeElement} * when traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface NewMultiArrayInstruction extends Instruction permits AbstractInstruction.BoundNewMultidimensionalArrayInstruction, AbstractInstruction.UnboundNewMultidimensionalArrayInstruction { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/NewObjectInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/NewObjectInstruction.java index e6e8fc64d17..f063733b64f 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/NewObjectInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/NewObjectInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +30,14 @@ import java.lang.classfile.constantpool.ClassEntry; import jdk.internal.classfile.impl.AbstractInstruction; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code new} instruction in the {@code code} array of a {@code Code} * attribute. Delivered as a {@link CodeElement} when traversing the elements * of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface NewObjectInstruction extends Instruction permits AbstractInstruction.BoundNewObjectInstruction, AbstractInstruction.UnboundNewObjectInstruction { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/NewPrimitiveArrayInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/NewPrimitiveArrayInstruction.java index 4adc7536c2c..411bf7f6b55 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/NewPrimitiveArrayInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/NewPrimitiveArrayInstruction.java @@ -30,16 +30,14 @@ import java.lang.classfile.TypeKind; import jdk.internal.classfile.impl.AbstractInstruction; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code newarray} invocation instruction in the {@code code} * array of a {@code Code} attribute. Delivered as a {@link CodeElement} * when traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface NewPrimitiveArrayInstruction extends Instruction permits AbstractInstruction.BoundNewPrimitiveArrayInstruction, AbstractInstruction.UnboundNewPrimitiveArrayInstruction { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/NewReferenceArrayInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/NewReferenceArrayInstruction.java index b622f915c46..c85ed9dd3d9 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/NewReferenceArrayInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/NewReferenceArrayInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +30,14 @@ import java.lang.classfile.constantpool.ClassEntry; import jdk.internal.classfile.impl.AbstractInstruction; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code anewarray} invocation instruction in the {@code code} * array of a {@code Code} attribute. Delivered as a {@link CodeElement} * when traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface NewReferenceArrayInstruction extends Instruction permits AbstractInstruction.BoundNewReferenceArrayInstruction, AbstractInstruction.UnboundNewReferenceArrayInstruction { /** diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/NopInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/NopInstruction.java index 3183ad88816..3c11803109a 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/NopInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/NopInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +29,14 @@ import java.lang.classfile.Instruction; import jdk.internal.classfile.impl.AbstractInstruction; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code nop} invocation instruction in the {@code code} * array of a {@code Code} attribute. Delivered as a {@link CodeElement} * when traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface NopInstruction extends Instruction permits AbstractInstruction.UnboundNopInstruction { /** diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/OperatorInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/OperatorInstruction.java index 602f34ec03e..d1eb8aa1a3d 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/OperatorInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/OperatorInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,6 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models an arithmetic operator instruction in the {@code code} array of a @@ -40,9 +39,8 @@ * {@link Opcode.Kind#OPERATOR}. Delivered as a {@link CodeElement} when * traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface OperatorInstruction extends Instruction permits AbstractInstruction.UnboundOperatorInstruction { /** diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/ReturnInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/ReturnInstruction.java index 6596404a582..3bbb96b1cbe 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/ReturnInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/ReturnInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,7 +33,6 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.BytecodeHelpers; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a return-from-method instruction in the {@code code} array of a @@ -41,9 +40,8 @@ * {@link Opcode.Kind#RETURN}. Delivered as a {@link CodeElement} when * traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ReturnInstruction extends Instruction permits AbstractInstruction.UnboundReturnInstruction { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/StackInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/StackInstruction.java index 17e9496652b..b01b206e368 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/StackInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/StackInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,6 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a stack manipulation instruction in the {@code code} array of a @@ -39,9 +38,8 @@ * {@link Opcode.Kind#STACK}. Delivered as a {@link CodeElement} when * traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface StackInstruction extends Instruction permits AbstractInstruction.UnboundStackInstruction { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/StoreInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/StoreInstruction.java index 68bf54e61c2..1d7bdce1fdf 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/StoreInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/StoreInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,7 +33,6 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.BytecodeHelpers; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models a local variable store instruction in the {@code code} array of a @@ -41,9 +40,8 @@ * {@link Opcode.Kind#STORE}. Delivered as a {@link CodeElement} when * traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface StoreInstruction extends Instruction permits AbstractInstruction.BoundStoreInstruction, AbstractInstruction.UnboundStoreInstruction { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/SwitchCase.java b/src/java.base/share/classes/java/lang/classfile/instruction/SwitchCase.java index 6149945532b..3f5f91031b6 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/SwitchCase.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/SwitchCase.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,6 @@ import java.lang.classfile.Label; import jdk.internal.classfile.impl.AbstractInstruction; -import jdk.internal.javac.PreviewFeature; /** * Models a single case in a {@code lookupswitch} or {@code tableswitch} @@ -36,9 +35,8 @@ * @see LookupSwitchInstruction * @see TableSwitchInstruction * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface SwitchCase permits AbstractInstruction.SwitchCaseImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/TableSwitchInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/TableSwitchInstruction.java index a8bce119db2..bbe7a4d6c0c 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/TableSwitchInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/TableSwitchInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +31,14 @@ import java.util.List; import jdk.internal.classfile.impl.AbstractInstruction; -import jdk.internal.javac.PreviewFeature; /** * Models a {@code tableswitch} instruction in the {@code code} array of a * {@code Code} attribute. Delivered as a {@link CodeElement} when traversing * the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface TableSwitchInstruction extends Instruction permits AbstractInstruction.BoundTableSwitchInstruction, AbstractInstruction.UnboundTableSwitchInstruction { /** diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/ThrowInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/ThrowInstruction.java index 68d861ba06d..ec6fdc38626 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/ThrowInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/ThrowInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +29,14 @@ import java.lang.classfile.Instruction; import jdk.internal.classfile.impl.AbstractInstruction; -import jdk.internal.javac.PreviewFeature; /** * Models an {@code athrow} instruction in the {@code code} array of a * {@code Code} attribute. Delivered as a {@link CodeElement} when traversing * the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface ThrowInstruction extends Instruction permits AbstractInstruction.UnboundThrowInstruction { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/TypeCheckInstruction.java b/src/java.base/share/classes/java/lang/classfile/instruction/TypeCheckInstruction.java index a4b9818a4be..032e7a8462b 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/TypeCheckInstruction.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/TypeCheckInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +34,14 @@ import jdk.internal.classfile.impl.AbstractInstruction; import jdk.internal.classfile.impl.TemporaryConstantPool; import jdk.internal.classfile.impl.Util; -import jdk.internal.javac.PreviewFeature; /** * Models an {@code instanceof} or {@code checkcast} instruction in the {@code * code} array of a {@code Code} attribute. Delivered as a {@link CodeElement} * when traversing the elements of a {@link CodeModel}. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) public sealed interface TypeCheckInstruction extends Instruction permits AbstractInstruction.BoundTypeCheckInstruction, AbstractInstruction.UnboundTypeCheckInstruction { diff --git a/src/java.base/share/classes/java/lang/classfile/instruction/package-info.java b/src/java.base/share/classes/java/lang/classfile/instruction/package-info.java index 2bb35494da0..d2a36e16615 100644 --- a/src/java.base/share/classes/java/lang/classfile/instruction/package-info.java +++ b/src/java.base/share/classes/java/lang/classfile/instruction/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved. * 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,9 +28,7 @@ * * The {@code java.lang.classfile.attribute} package contains interfaces describing code instructions. * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) package java.lang.classfile.instruction; -import jdk.internal.javac.PreviewFeature; diff --git a/src/java.base/share/classes/java/lang/classfile/package-info.java b/src/java.base/share/classes/java/lang/classfile/package-info.java index d5ca9dbe515..b08e1a0c256 100644 --- a/src/java.base/share/classes/java/lang/classfile/package-info.java +++ b/src/java.base/share/classes/java/lang/classfile/package-info.java @@ -547,9 +547,6 @@ * | CharacterRange(int rangeStart, int rangeEnd, int flags, Label startScope, Label endScope) * } * - * @since 22 + * @since 24 */ -@PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) package java.lang.classfile; - -import jdk.internal.javac.PreviewFeature; diff --git a/src/java.base/share/classes/java/lang/invoke/LambdaFormEditor.java b/src/java.base/share/classes/java/lang/invoke/LambdaFormEditor.java index 4de0d9c95cb..8d84c5f8096 100644 --- a/src/java.base/share/classes/java/lang/invoke/LambdaFormEditor.java +++ b/src/java.base/share/classes/java/lang/invoke/LambdaFormEditor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,6 +38,7 @@ import static java.lang.invoke.MethodHandleImpl.Intrinsic; import static java.lang.invoke.MethodHandleImpl.NF_loop; import static java.lang.invoke.MethodHandleImpl.makeIntrinsic; +import static java.lang.invoke.MethodHandleNatives.USE_SOFT_CACHE; /** Transforms on LFs. * A lambda-form editor can derive new LFs from its base LF. @@ -89,12 +90,17 @@ static LambdaFormEditor lambdaFormEditor(LambdaForm lambdaForm) { * Tightly coupled with the TransformKey class, which is used to lookup existing * Transforms. */ - private static final class Transform extends SoftReference { + private static final class Transform { + final Object cache; final long packedBytes; final byte[] fullBytes; private Transform(long packedBytes, byte[] fullBytes, LambdaForm result) { - super(result); + if (USE_SOFT_CACHE) { + cache = new SoftReference(result); + } else { + cache = result; + } this.packedBytes = packedBytes; this.fullBytes = fullBytes; } @@ -135,6 +141,15 @@ public String toString() { } return buf.toString(); } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public LambdaForm get() { + if (cache instanceof LambdaForm lf) { + return lf; + } else { + return ((SoftReference)cache).get(); + } + } } /** diff --git a/src/java.base/share/classes/java/lang/invoke/MethodHandleNatives.java b/src/java.base/share/classes/java/lang/invoke/MethodHandleNatives.java index 701783d6bce..9f8a91323a6 100644 --- a/src/java.base/share/classes/java/lang/invoke/MethodHandleNatives.java +++ b/src/java.base/share/classes/java/lang/invoke/MethodHandleNatives.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,9 +34,11 @@ import jdk.internal.misc.VM; import jdk.internal.ref.CleanerFactory; import sun.invoke.util.Wrapper; +import sun.security.action.GetPropertyAction; import java.lang.invoke.MethodHandles.Lookup; import java.lang.reflect.Field; +import java.util.Properties; import static java.lang.invoke.MethodHandleNatives.Constants.*; import static java.lang.invoke.MethodHandleStatics.TRACE_METHOD_LINKAGE; @@ -699,6 +701,22 @@ static boolean canBeCalledVirtual(MemberName symbolicRef, Class definingClass symbolicRefClass.isInterface()); // Mdef implements Msym } + //--- AOTCache support + + /** + * In normal execution, this is set to true, so that LambdaFormEditor and MethodTypeForm will + * use soft references to allow class unloading. + * + * When dumping the AOTCache, this is set to false so that no cached heap objects will + * contain soft references (which are not yet supported by AOTCache - see JDK-8341587). AOTCache + * only stores LambdaFormEditors and MethodTypeForms for classes in the boot/platform/app loaders. + * Such classes will never be unloaded, so it's OK to use hard references. + */ + // The system property java.lang.invoke.MethodHandleNatives.USE_SOFT_CACHE is + // from -XX:AOTCache which OpenJ9 doesn't support. + // Set it to the default value true. + static final boolean USE_SOFT_CACHE = true; + /** * Inform the VM that a MemberName belonging to class c has been collected. */ diff --git a/src/java.base/share/classes/java/lang/invoke/MethodType.java b/src/java.base/share/classes/java/lang/invoke/MethodType.java index 2b3843b09e3..5e1c0f8581c 100644 --- a/src/java.base/share/classes/java/lang/invoke/MethodType.java +++ b/src/java.base/share/classes/java/lang/invoke/MethodType.java @@ -31,6 +31,8 @@ import java.util.Arrays; import java.util.Collections; import java.util.function.Supplier; +import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; @@ -40,6 +42,7 @@ import jdk.internal.util.ReferencedKeySet; import jdk.internal.util.ReferenceKey; +import jdk.internal.misc.CDS; import jdk.internal.vm.annotation.Stable; import sun.invoke.util.BytecodeDescriptor; import sun.invoke.util.VerifyType; @@ -391,6 +394,17 @@ private static MethodType makeImpl(Class rtype, Class[] ptypes, boolean tr ptypes = NO_PTYPES; trusted = true; } MethodType primordialMT = new MethodType(rtype, ptypes); + if (archivedMethodTypes != null) { + // If this JVM process reads from archivedMethodTypes, it never + // modifies the table. So there's no need for synchronization. + // See copyInternTable() below. + assert CDS.isUsingArchive(); + MethodType mt = archivedMethodTypes.get(primordialMT); + if (mt != null) { + return mt; + } + } + MethodType mt = internTable.get(primordialMT); if (mt != null) return mt; @@ -409,7 +423,9 @@ private static MethodType makeImpl(Class rtype, Class[] ptypes, boolean tr mt.form = MethodTypeForm.findForm(mt); return internTable.intern(mt); } + private static final @Stable MethodType[] objectOnlyTypes = new MethodType[20]; + private static @Stable HashMap archivedMethodTypes; /** * Finds or creates a method type whose components are {@code Object} with an optional trailing {@code Object[]} array. @@ -1380,4 +1396,30 @@ private Object readResolve() { wrapAlt = null; return mt; } + + static HashMap copyInternTable() { + HashMap copy = new HashMap<>(); + + for (Iterator i = internTable.iterator(); i.hasNext(); ) { + MethodType t = i.next(); + copy.put(t, t); + } + + return copy; + } + + // This is called from C code, at the very end of Java code execution + // during the AOT cache assembly phase. + static void createArchivedObjects() { + // After the archivedMethodTypes field is assigned, this table + // is never modified. So we don't need synchronization when reading from + // it (which happens only in a future JVM process, never in the current process). + // + // @implNote CDS.isDumpingStaticArchive() is mutually exclusive with + // CDS.isUsingArchive(); at most one of them can return true for any given JVM + // process. + assert CDS.isDumpingStaticArchive(); + archivedMethodTypes = copyInternTable(); + internTable.clear(); + } } diff --git a/src/java.base/share/classes/java/lang/invoke/MethodTypeForm.java b/src/java.base/share/classes/java/lang/invoke/MethodTypeForm.java index 09377618797..69545478ec4 100644 --- a/src/java.base/share/classes/java/lang/invoke/MethodTypeForm.java +++ b/src/java.base/share/classes/java/lang/invoke/MethodTypeForm.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ import java.lang.ref.SoftReference; import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; +import static java.lang.invoke.MethodHandleNatives.USE_SOFT_CACHE; /** * Shared information for a group of method types, which differ @@ -51,7 +52,7 @@ final class MethodTypeForm { final MethodType basicType; // the canonical erasure, with primitives simplified // Cached adapter information: - final SoftReference[] methodHandles; + private final Object[] methodHandles; // Indexes into methodHandles: static final int @@ -61,7 +62,7 @@ final class MethodTypeForm { MH_LIMIT = 3; // Cached lambda form information, for basic types only: - final SoftReference[] lambdaForms; + private final Object[] lambdaForms; // Indexes into lambdaForms: static final int @@ -109,39 +110,55 @@ public MethodType basicType() { return basicType; } + @SuppressWarnings({"rawtypes", "unchecked"}) public MethodHandle cachedMethodHandle(int which) { - SoftReference entry = methodHandles[which]; - return (entry != null) ? entry.get() : null; + Object entry = methodHandles[which]; + if (entry == null) { + return null; + } else if (entry instanceof MethodHandle mh) { + return mh; + } else { + return ((SoftReference)entry).get(); + } } public synchronized MethodHandle setCachedMethodHandle(int which, MethodHandle mh) { // Simulate a CAS, to avoid racy duplication of results. - SoftReference entry = methodHandles[which]; - if (entry != null) { - MethodHandle prev = entry.get(); - if (prev != null) { - return prev; - } + MethodHandle prev = cachedMethodHandle(which); + if (prev != null) { + return prev; + } + if (USE_SOFT_CACHE) { + methodHandles[which] = new SoftReference<>(mh); + } else { + methodHandles[which] = mh; } - methodHandles[which] = new SoftReference<>(mh); return mh; } + @SuppressWarnings({"rawtypes", "unchecked"}) public LambdaForm cachedLambdaForm(int which) { - SoftReference entry = lambdaForms[which]; - return (entry != null) ? entry.get() : null; + Object entry = lambdaForms[which]; + if (entry == null) { + return null; + } else if (entry instanceof LambdaForm lf) { + return lf; + } else { + return ((SoftReference)entry).get(); + } } public synchronized LambdaForm setCachedLambdaForm(int which, LambdaForm form) { // Simulate a CAS, to avoid racy duplication of results. - SoftReference entry = lambdaForms[which]; - if (entry != null) { - LambdaForm prev = entry.get(); - if (prev != null) { - return prev; - } + LambdaForm prev = cachedLambdaForm(which); + if (prev != null) { + return prev; + } + if (USE_SOFT_CACHE) { + lambdaForms[which] = new SoftReference<>(form); + } else { + lambdaForms[which] = form; } - lambdaForms[which] = new SoftReference<>(form); return form; } @@ -191,8 +208,8 @@ protected MethodTypeForm(MethodType erasedType) { this.primitiveCount = primitiveCount; this.parameterSlotCount = (short)pslotCount; - this.lambdaForms = new SoftReference[LF_LIMIT]; - this.methodHandles = new SoftReference[MH_LIMIT]; + this.lambdaForms = new Object[LF_LIMIT]; + this.methodHandles = new Object[MH_LIMIT]; } else { this.basicType = MethodType.methodType(basicReturnType, basicPtypes, true); // fill in rest of data from the basic type: diff --git a/src/java.base/share/classes/java/lang/invoke/StringConcatFactory.java b/src/java.base/share/classes/java/lang/invoke/StringConcatFactory.java index 2f5b8f2407e..7e91057cbf4 100644 --- a/src/java.base/share/classes/java/lang/invoke/StringConcatFactory.java +++ b/src/java.base/share/classes/java/lang/invoke/StringConcatFactory.java @@ -1080,6 +1080,8 @@ private StringConcatFactory() { * without copying. */ private static final class InlineHiddenClassStrategy { + // The CLASS_NAME prefix must be the same as used by HeapShared::is_string_concat_klass() + // in the HotSpot code. static final String CLASS_NAME = "java.lang.String$$StringConcat"; static final String METHOD_NAME = "concat"; diff --git a/src/java.base/share/classes/java/lang/module/ModuleFinder.java b/src/java.base/share/classes/java/lang/module/ModuleFinder.java index 6b2e9228ad5..bc470633039 100644 --- a/src/java.base/share/classes/java/lang/module/ModuleFinder.java +++ b/src/java.base/share/classes/java/lang/module/ModuleFinder.java @@ -26,9 +26,6 @@ package java.lang.module; import java.nio.file.Path; -import java.security.AccessController; -import java.security.Permission; -import java.security.PrivilegedAction; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -130,16 +127,8 @@ public interface ModuleFinder { * * @return A {@code ModuleFinder} that locates the system modules */ - @SuppressWarnings("removal") static ModuleFinder ofSystem() { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(new RuntimePermission("accessSystemModules")); - PrivilegedAction pa = SystemModuleFinders::ofSystem; - return AccessController.doPrivileged(pa); - } else { - return SystemModuleFinders.ofSystem(); - } + return SystemModuleFinders.ofSystem(); } /** diff --git a/src/java.base/share/classes/java/net/Authenticator.java b/src/java.base/share/classes/java/net/Authenticator.java index 0935366abc1..9ac504f9a62 100644 --- a/src/java.base/share/classes/java/net/Authenticator.java +++ b/src/java.base/share/classes/java/net/Authenticator.java @@ -112,14 +112,6 @@ private void reset() { * any previously set authenticator is removed. */ public static synchronized void setDefault(Authenticator a) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - NetPermission setDefaultPermission - = new NetPermission("setDefaultAuthenticator"); - sm.checkPermission(setDefaultPermission); - } - theAuthenticator = a; } @@ -130,13 +122,6 @@ public static synchronized void setDefault(Authenticator a) { * @since 9 */ public static Authenticator getDefault() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - NetPermission requestPermission - = new NetPermission("requestPasswordAuthentication"); - sm.checkPermission(requestPermission); - } return theAuthenticator; } @@ -161,14 +146,6 @@ public static PasswordAuthentication requestPasswordAuthentication( String prompt, String scheme) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - NetPermission requestPermission - = new NetPermission("requestPasswordAuthentication"); - sm.checkPermission(requestPermission); - } - Authenticator a = theAuthenticator; if (a == null) { return null; @@ -212,14 +189,6 @@ public static PasswordAuthentication requestPasswordAuthentication( String prompt, String scheme) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - NetPermission requestPermission - = new NetPermission("requestPasswordAuthentication"); - sm.checkPermission(requestPermission); - } - Authenticator a = theAuthenticator; if (a == null) { return null; @@ -267,14 +236,6 @@ public static PasswordAuthentication requestPasswordAuthentication( URL url, RequestorType reqType) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - NetPermission requestPermission - = new NetPermission("requestPasswordAuthentication"); - sm.checkPermission(requestPermission); - } - Authenticator a = theAuthenticator; if (a == null) { return null; @@ -328,14 +289,6 @@ public static PasswordAuthentication requestPasswordAuthentication( URL url, RequestorType reqType) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - NetPermission requestPermission - = new NetPermission("requestPasswordAuthentication"); - sm.checkPermission(requestPermission); - } - Authenticator a = authenticator == null ? theAuthenticator : authenticator; if (a == null) { return null; diff --git a/src/java.base/share/classes/java/net/CookieHandler.java b/src/java.base/share/classes/java/net/CookieHandler.java index 4b5e3ebedd8..ec20c860591 100644 --- a/src/java.base/share/classes/java/net/CookieHandler.java +++ b/src/java.base/share/classes/java/net/CookieHandler.java @@ -28,7 +28,6 @@ import java.util.Map; import java.util.List; import java.io.IOException; -import sun.security.util.SecurityConstants; /** * A CookieHandler object provides a callback mechanism to hook up a @@ -73,11 +72,6 @@ public CookieHandler() {} * @see #setDefault(CookieHandler) */ public static synchronized CookieHandler getDefault() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(SecurityConstants.GET_COOKIEHANDLER_PERMISSION); - } return cookieHandler; } @@ -91,11 +85,6 @@ public static synchronized CookieHandler getDefault() { * @see #getDefault() */ public static synchronized void setDefault(CookieHandler cHandler) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(SecurityConstants.SET_COOKIEHANDLER_PERMISSION); - } cookieHandler = cHandler; } diff --git a/src/java.base/share/classes/java/net/ResponseCache.java b/src/java.base/share/classes/java/net/ResponseCache.java index 292c1b7610d..3339f41883b 100644 --- a/src/java.base/share/classes/java/net/ResponseCache.java +++ b/src/java.base/share/classes/java/net/ResponseCache.java @@ -28,7 +28,6 @@ import java.io.IOException; import java.util.Map; import java.util.List; -import sun.security.util.SecurityConstants; /** * Represents implementations of URLConnection caches. An instance of @@ -84,11 +83,6 @@ public ResponseCache() {} * @since 1.5 */ public static synchronized ResponseCache getDefault() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(SecurityConstants.GET_RESPONSECACHE_PERMISSION); - } return theResponseCache; } @@ -104,11 +98,6 @@ public static synchronized ResponseCache getDefault() { * @since 1.5 */ public static synchronized void setDefault(ResponseCache responseCache) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(SecurityConstants.SET_RESPONSECACHE_PERMISSION); - } theResponseCache = responseCache; } diff --git a/src/java.base/share/classes/java/util/Arrays.java b/src/java.base/share/classes/java/util/Arrays.java index de10505fdab..268b233adbc 100644 --- a/src/java.base/share/classes/java/util/Arrays.java +++ b/src/java.base/share/classes/java/util/Arrays.java @@ -1017,11 +1017,8 @@ public static void parallelSort(T[] a, int fromIndex, int toIndex, * circular dependencies. To be removed in a future release. */ static final class LegacyMergeSort { - @SuppressWarnings("removal") private static final boolean userRequested = - java.security.AccessController.doPrivileged( - new sun.security.action.GetBooleanAction( - "java.util.Arrays.useLegacyMergeSort")).booleanValue(); + Boolean.getBoolean("java.util.Arrays.useLegacyMergeSort"); } /** diff --git a/src/java.base/share/classes/java/util/Calendar.java b/src/java.base/share/classes/java/util/Calendar.java index 7ac98c02297..7cf389df42b 100644 --- a/src/java.base/share/classes/java/util/Calendar.java +++ b/src/java.base/share/classes/java/util/Calendar.java @@ -43,12 +43,6 @@ import java.io.ObjectOutputStream; import java.io.OptionalDataException; import java.io.Serializable; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PermissionCollection; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.security.ProtectionDomain; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.time.Instant; @@ -3564,25 +3558,9 @@ private synchronized void writeObject(ObjectOutputStream stream) } } - @SuppressWarnings("removal") - private static class CalendarAccessControlContext { - private static final AccessControlContext INSTANCE; - static { - RuntimePermission perm = new RuntimePermission("accessClassInPackage.sun.util.calendar"); - PermissionCollection perms = perm.newPermissionCollection(); - perms.add(perm); - INSTANCE = new AccessControlContext(new ProtectionDomain[] { - new ProtectionDomain(null, perms) - }); - } - private CalendarAccessControlContext() { - } - } - /** * Reconstitutes this object from a stream (i.e., deserialize it). */ - @SuppressWarnings("removal") @java.io.Serial private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException @@ -3617,16 +3595,8 @@ else if (serialVersionOnStream >= 0) // If there's a ZoneInfo object, use it for zone. ZoneInfo zi = null; try { - zi = AccessController.doPrivileged( - new PrivilegedExceptionAction<>() { - @Override - public ZoneInfo run() throws Exception { - return (ZoneInfo) input.readObject(); - } - }, - CalendarAccessControlContext.INSTANCE); - } catch (PrivilegedActionException pae) { - Exception e = pae.getException(); + zi = (ZoneInfo) input.readObject(); + } catch (Exception e) { if (!(e instanceof OptionalDataException)) { if (e instanceof RuntimeException) { throw (RuntimeException) e; diff --git a/src/java.base/share/classes/java/util/Currency.java b/src/java.base/share/classes/java/util/Currency.java index 0bc86f3281e..b639855b3bf 100644 --- a/src/java.base/share/classes/java/util/Currency.java +++ b/src/java.base/share/classes/java/util/Currency.java @@ -32,8 +32,6 @@ import java.io.InputStream; import java.io.IOException; import java.io.Serializable; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.concurrent.ConcurrentHashMap; @@ -213,63 +211,57 @@ public final class Currency implements Serializable { initStatic(); } - @SuppressWarnings("removal") private static void initStatic() { - AccessController.doPrivileged(new PrivilegedAction<>() { - @Override - public Void run() { - try { - try (InputStream in = getClass().getResourceAsStream("/java/util/currency.data")) { - if (in == null) { - throw new InternalError("Currency data not found"); - } - DataInputStream dis = new DataInputStream(new BufferedInputStream(in)); - if (dis.readInt() != MAGIC_NUMBER) { - throw new InternalError("Currency data is possibly corrupted"); - } - formatVersion = dis.readInt(); - if (formatVersion != VALID_FORMAT_VERSION) { - throw new InternalError("Currency data format is incorrect"); - } - dataVersion = dis.readInt(); - mainTable = readIntArray(dis, A_TO_Z * A_TO_Z); - int scCount = dis.readInt(); - specialCasesList = readSpecialCases(dis, scCount); - int ocCount = dis.readInt(); - otherCurrenciesList = readOtherCurrencies(dis, ocCount); - } - } catch (IOException e) { - throw new InternalError(e); - } - // look for the properties file for overrides - String propsFile = System.getProperty("java.util.currency.data"); - if (propsFile == null) { - propsFile = StaticProperty.javaHome() + File.separator + "lib" + - File.separator + "currency.properties"; + try { + try (InputStream in = Currency.class.getResourceAsStream("/java/util/currency.data")) { + if (in == null) { + throw new InternalError("Currency data not found"); } - try { - File propFile = new File(propsFile); - if (propFile.exists()) { - Properties props = new Properties(); - try (FileReader fr = new FileReader(propFile)) { - props.load(fr); - } - Pattern propertiesPattern = - Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*" + - "(\\d+)\\s*,?\\s*(\\d{4}-\\d{2}-\\d{2}T\\d{2}:" + - "\\d{2}:\\d{2})?"); - List currencyEntries - = getValidCurrencyData(props, propertiesPattern); - currencyEntries.forEach(Currency::replaceCurrencyData); - } - } catch (IOException e) { - CurrencyProperty.info("currency.properties is ignored" - + " because of an IOException", e); + DataInputStream dis = new DataInputStream(new BufferedInputStream(in)); + if (dis.readInt() != MAGIC_NUMBER) { + throw new InternalError("Currency data is possibly corrupted"); } - return null; + formatVersion = dis.readInt(); + if (formatVersion != VALID_FORMAT_VERSION) { + throw new InternalError("Currency data format is incorrect"); + } + dataVersion = dis.readInt(); + mainTable = readIntArray(dis, A_TO_Z * A_TO_Z); + int scCount = dis.readInt(); + specialCasesList = readSpecialCases(dis, scCount); + int ocCount = dis.readInt(); + otherCurrenciesList = readOtherCurrencies(dis, ocCount); } - }); + } catch (IOException e) { + throw new InternalError(e); + } + + // look for the properties file for overrides + String propsFile = System.getProperty("java.util.currency.data"); + if (propsFile == null) { + propsFile = StaticProperty.javaHome() + File.separator + "lib" + + File.separator + "currency.properties"; + } + try { + File propFile = new File(propsFile); + if (propFile.exists()) { + Properties props = new Properties(); + try (FileReader fr = new FileReader(propFile)) { + props.load(fr); + } + Pattern propertiesPattern = + Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*" + + "(\\d+)\\s*,?\\s*(\\d{4}-\\d{2}-\\d{2}T\\d{2}:" + + "\\d{2}:\\d{2})?"); + List currencyEntries + = getValidCurrencyData(props, propertiesPattern); + currencyEntries.forEach(Currency::replaceCurrencyData); + } + } catch (IOException e) { + CurrencyProperty.info("currency.properties is ignored" + + " because of an IOException", e); + } } /** diff --git a/src/java.base/share/classes/java/util/Locale.java b/src/java.base/share/classes/java/util/Locale.java index 600b20de639..c055c160367 100644 --- a/src/java.base/share/classes/java/util/Locale.java +++ b/src/java.base/share/classes/java/util/Locale.java @@ -1216,10 +1216,6 @@ public static synchronized void setDefault(Locale.Category category, if (newLocale == null) throw new NullPointerException("Can't set default locale to NULL"); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) sm.checkPermission(new PropertyPermission - ("user.language", "write")); switch (category) { case DISPLAY: defaultDisplayLocale = newLocale; diff --git a/src/java.base/share/classes/java/util/Properties.java b/src/java.base/share/classes/java/util/Properties.java index 45ca0363660..015cdbc7107 100644 --- a/src/java.base/share/classes/java/util/Properties.java +++ b/src/java.base/share/classes/java/util/Properties.java @@ -949,9 +949,6 @@ private void store0(BufferedWriter bw, String comments, boolean escUnicode) } private static void writeDateComment(BufferedWriter bw) throws IOException { - // value of java.properties.date system property isn't sensitive - // and so doesn't need any security manager checks to make the value accessible - // to the callers String sysPropVal = StaticProperty.javaPropertiesDate(); if (sysPropVal != null && !sysPropVal.isEmpty()) { writeComments(bw, sysPropVal); diff --git a/src/java.base/share/classes/java/util/PropertyResourceBundle.java b/src/java.base/share/classes/java/util/PropertyResourceBundle.java index 02391fa2de2..aba65cbcd88 100644 --- a/src/java.base/share/classes/java/util/PropertyResourceBundle.java +++ b/src/java.base/share/classes/java/util/PropertyResourceBundle.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -46,7 +46,6 @@ import java.nio.charset.MalformedInputException; import java.nio.charset.UnmappableCharacterException; import sun.nio.cs.ISO_8859_1; -import sun.security.action.GetPropertyAction; import sun.util.PropertyResourceBundleCharset; import sun.util.ResourceBundleEnumeration; @@ -132,9 +131,9 @@ public class PropertyResourceBundle extends ResourceBundle { // Check whether the strict encoding is specified. // The possible encoding is either "ISO-8859-1" or "UTF-8". - private static final String encoding = GetPropertyAction - .privilegedGetProperty("java.util.PropertyResourceBundle.encoding", "") - .toUpperCase(Locale.ROOT); + private static final String encoding = + System.getProperty("java.util.PropertyResourceBundle.encoding", "") + .toUpperCase(Locale.ROOT); /** * Creates a property resource bundle from an {@link java.io.InputStream diff --git a/src/java.base/share/classes/java/util/ResourceBundle.java b/src/java.base/share/classes/java/util/ResourceBundle.java index 83f58b8506f..989cc09f388 100644 --- a/src/java.base/share/classes/java/util/ResourceBundle.java +++ b/src/java.base/share/classes/java/util/ResourceBundle.java @@ -42,7 +42,6 @@ import java.io.IOException; import java.io.InputStream; -import java.io.UncheckedIOException; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; @@ -53,10 +52,6 @@ import java.net.JarURLConnection; import java.net.URL; import java.net.URLConnection; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.jar.JarEntry; @@ -70,12 +65,9 @@ import jdk.internal.reflect.CallerSensitive; import jdk.internal.reflect.Reflection; import jdk.internal.util.ReferencedKeyMap; -import sun.security.action.GetPropertyAction; import sun.util.locale.BaseLocale; import sun.util.resources.Bundles; -import static sun.security.util.SecurityConstants.GET_CLASSLOADER_PERMISSION; - /** * @@ -581,10 +573,8 @@ public Locale getLocale() { return locale; } - @SuppressWarnings("removal") private static ClassLoader getLoader(Module module) { - PrivilegedAction pa = module::getClassLoader; - return AccessController.doPrivileged(pa); + return module.getClassLoader(); } /** @@ -1506,15 +1496,12 @@ private static Control getDefaultControl(Module targetModule, String baseName) { } private static class ResourceBundleControlProviderHolder { - private static final PrivilegedAction> pa = - () -> ServiceLoader.load(ResourceBundleControlProvider.class, - ClassLoader.getSystemClassLoader()).stream() - .map(ServiceLoader.Provider::get) - .toList(); - @SuppressWarnings("removal") private static final List CONTROL_PROVIDERS = - AccessController.doPrivileged(pa); + ServiceLoader.load(ResourceBundleControlProvider.class, + ClassLoader.getSystemClassLoader()).stream() + .map(ServiceLoader.Provider::get) + .toList(); private static Control getControl(String baseName) { return CONTROL_PROVIDERS.isEmpty() ? @@ -1594,13 +1581,6 @@ private static ResourceBundle getBundleFromModule(Class caller, Control control) { Objects.requireNonNull(module); Module callerModule = getCallerModule(caller); - if (callerModule != module) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(GET_CLASSLOADER_PERMISSION); - } - } return getBundleImpl(callerModule, module, baseName, locale, control); } @@ -1885,7 +1865,6 @@ private static ServiceLoader getServiceLoader(Module mod * Returns the service type of the given baseName that is visible * to the given class loader */ - @SuppressWarnings("removal") private static Class getResourceBundleProviderType(String baseName, ClassLoader loader) { @@ -1900,27 +1879,20 @@ private static ServiceLoader getServiceLoader(Module mod // Use the class loader of the getBundle caller so that the caller's // visibility of the provider type is checked. - return AccessController.doPrivileged( - new PrivilegedAction<>() { - @Override - public Class run() { - try { - Class c = Class.forName(providerName, false, loader); - if (ResourceBundleProvider.class.isAssignableFrom(c)) { - @SuppressWarnings("unchecked") - Class s = (Class) c; - return s; - } - } catch (ClassNotFoundException e) {} - return null; - } - }); + try { + Class c = Class.forName(providerName, false, loader); + if (ResourceBundleProvider.class.isAssignableFrom(c)) { + @SuppressWarnings("unchecked") + Class s = (Class) c; + return s; + } + } catch (ClassNotFoundException _) {} + return null; } /** * Loads ResourceBundle from service providers. */ - @SuppressWarnings("removal") private static ResourceBundle loadBundleFromProviders(String baseName, Locale locale, ServiceLoader providers, @@ -1928,34 +1900,28 @@ private static ResourceBundle loadBundleFromProviders(String baseName, { if (providers == null) return null; - return AccessController.doPrivileged( - new PrivilegedAction<>() { - public ResourceBundle run() { - for (Iterator itr = providers.iterator(); itr.hasNext(); ) { - try { - ResourceBundleProvider provider = itr.next(); - if (cacheKey != null && cacheKey.callerHasProvider == null - && cacheKey.getModule() == provider.getClass().getModule()) { - cacheKey.callerHasProvider = Boolean.TRUE; - } - ResourceBundle bundle = provider.getBundle(baseName, locale); - trace("provider %s %s locale: %s bundle: %s%n", provider, baseName, locale, bundle); - if (bundle != null) { - return bundle; - } - } catch (ServiceConfigurationError | SecurityException e) { - if (cacheKey != null) { - cacheKey.setCause(e); - } - } - } - if (cacheKey != null && cacheKey.callerHasProvider == null) { - cacheKey.callerHasProvider = Boolean.FALSE; - } - return null; - } - }); - + for (Iterator itr = providers.iterator(); itr.hasNext(); ) { + try { + ResourceBundleProvider provider = itr.next(); + if (cacheKey != null && cacheKey.callerHasProvider == null + && cacheKey.getModule() == provider.getClass().getModule()) { + cacheKey.callerHasProvider = Boolean.TRUE; + } + ResourceBundle bundle = provider.getBundle(baseName, locale); + trace("provider %s %s locale: %s bundle: %s%n", provider, baseName, locale, bundle); + if (bundle != null) { + return bundle; + } + } catch (ServiceConfigurationError e) { + if (cacheKey != null) { + cacheKey.setCause(e); + } + } + } + if (cacheKey != null && cacheKey.callerHasProvider == null) { + cacheKey.callerHasProvider = Boolean.FALSE; + } + return null; } /* @@ -3153,7 +3119,6 @@ public ResourceBundle newBundle(String baseName, Locale locale, String format, return bundle; } - @SuppressWarnings("removal") private ResourceBundle newBundle0(String bundleName, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { @@ -3177,28 +3142,20 @@ private ResourceBundle newBundle0(String bundleName, String format, bundleClass.getName() + " in " + m.toString()); } try { - Constructor ctor = AccessController.doPrivileged( - new PrivilegedExceptionAction<>() { - @Override - public Constructor run() throws NoSuchMethodException { - return bundleClass.getDeclaredConstructor(); - } - }); + Constructor ctor = bundleClass.getDeclaredConstructor(); if (!Modifier.isPublic(ctor.getModifiers())) { throw new IllegalAccessException("no-arg constructor in " + bundleClass.getName() + " is not publicly accessible."); } // java.base may not be able to read the bundleClass's module. - PrivilegedAction pa1 = () -> { ctor.setAccessible(true); return null; }; - AccessController.doPrivileged(pa1); + ctor.setAccessible(true); bundle = ctor.newInstance((Object[]) null); } catch (InvocationTargetException e) { uncheckedThrow(e); - } catch (PrivilegedActionException e) { - assert e.getCause() instanceof NoSuchMethodException; + } catch (NoSuchMethodException e) { throw new InstantiationException("public no-arg constructor " + - "does not exist in " + bundleClass.getName()); + "does not exist in " + bundleClass.getName()); } } else { throw new ClassCastException(c.getName() @@ -3212,27 +3169,16 @@ public Constructor run() throws NoSuchMethodException { return bundle; } - final boolean reloadFlag = reload; - InputStream stream = null; - try { - stream = AccessController.doPrivileged( - new PrivilegedExceptionAction<>() { - public InputStream run() throws IOException { - URL url = loader.getResource(resourceName); - if (url == null) return null; - - URLConnection connection = url.openConnection(); - if (reloadFlag) { - // Disable caches to get fresh data for - // reloading. - connection.setUseCaches(false); - } - return connection.getInputStream(); - } - }); - } catch (PrivilegedActionException e) { - throw (IOException) e.getCause(); + URL url = loader.getResource(resourceName); + if (url == null) return null; + + URLConnection connection = url.openConnection(); + if (reload) { + // Disable caches to get fresh data for + // reloading. + connection.setUseCaches(false); } + InputStream stream = connection.getInputStream(); if (stream != null) { try { bundle = new PropertyResourceBundle(stream); @@ -3563,7 +3509,6 @@ private static class ResourceBundleProviderHelper { /** * Returns a new ResourceBundle instance of the given bundleClass */ - @SuppressWarnings("removal") static ResourceBundle newResourceBundle(Class bundleClass) { try { @SuppressWarnings("unchecked") @@ -3573,8 +3518,7 @@ static ResourceBundle newResourceBundle(Class bundleCl return null; } // java.base may not be able to read the bundleClass's module. - PrivilegedAction pa = () -> { ctor.setAccessible(true); return null;}; - AccessController.doPrivileged(pa); + ctor.setAccessible(true); try { return ctor.newInstance((Object[]) null); } catch (InvocationTargetException e) { @@ -3602,9 +3546,7 @@ static ResourceBundle loadResourceBundle(Module callerModule, { String bundleName = Control.INSTANCE.toBundleName(baseName, locale); try { - PrivilegedAction> pa = () -> Class.forName(module, bundleName); - @SuppressWarnings("removal") - Class c = AccessController.doPrivileged(pa, null, GET_CLASSLOADER_PERMISSION); + Class c = Class.forName(module, bundleName); trace("local in %s %s caller %s: %s%n", module, bundleName, callerModule, c); if (c == null) { @@ -3662,56 +3604,46 @@ static ResourceBundle loadPropertyResourceBundle(Module callerModule, { String bundleName = Control.INSTANCE.toBundleName(baseName, locale); - PrivilegedAction pa = () -> { - try { - String resourceName = Control.INSTANCE - .toResourceName0(bundleName, "properties"); - if (resourceName == null) { - return null; - } - trace("local in %s %s caller %s%n", module, resourceName, callerModule); - - // if the package is in the given module but not opened - // locate it from the given module first. - String pn = toPackageName(bundleName); - trace(" %s/%s is accessible to %s : %s%n", - module.getName(), pn, callerModule, - isAccessible(callerModule, module, pn)); - if (isAccessible(callerModule, module, pn)) { - InputStream in = module.getResourceAsStream(resourceName); - if (in != null) { - return in; - } - } - - ClassLoader loader = module.getClassLoader(); - trace("loader for %s %s caller %s%n", module, resourceName, callerModule); - - try { - if (loader != null) { - return loader.getResourceAsStream(resourceName); - } else { - URL url = BootLoader.findResource(resourceName); - if (url != null) { - return url.openStream(); - } - } - } catch (Exception e) {} - return null; - - } catch (IOException e) { - throw new UncheckedIOException(e); + String resourceName = Control.INSTANCE + .toResourceName0(bundleName, "properties"); + if (resourceName == null) { + return null; + } + trace("local in %s %s caller %s%n", module, resourceName, callerModule); + + + // if the package is in the given module but not opened + // locate it from the given module first. + String pn = toPackageName(bundleName); + trace(" %s/%s is accessible to %s : %s%n", + module.getName(), pn, callerModule, + isAccessible(callerModule, module, pn)); + if (isAccessible(callerModule, module, pn)) { + InputStream in = module.getResourceAsStream(resourceName); + if (in != null) { + return new PropertyResourceBundle(in); } - }; + } + ClassLoader loader = module.getClassLoader(); + trace("loader for %s %s caller %s%n", module, resourceName, callerModule); - try (@SuppressWarnings("removal") InputStream stream = AccessController.doPrivileged(pa)) { + try { + InputStream stream = null; + if (loader != null) { + stream = loader.getResourceAsStream(resourceName); + } else { + URL url = BootLoader.findResource(resourceName); + if (url != null) { + stream = url.openStream(); + } + } if (stream != null) { return new PropertyResourceBundle(stream); } else { return null; } - } catch (UncheckedIOException e) { - throw e.getCause(); + } catch (Exception e) { + return null; } } @@ -3722,8 +3654,8 @@ private static String toPackageName(String bundleName) { } - private static final boolean TRACE_ON = Boolean.parseBoolean( - GetPropertyAction.privilegedGetProperty("resource.bundle.debug", "false")); + private static final boolean TRACE_ON = Boolean.getBoolean( + System.getProperty("resource.bundle.debug", "false")); private static void trace(String format, Object... params) { if (TRACE_ON) diff --git a/src/java.base/share/classes/java/util/TimeZone.java b/src/java.base/share/classes/java/util/TimeZone.java index f1a2d92b6ba..f0b122418c9 100644 --- a/src/java.base/share/classes/java/util/TimeZone.java +++ b/src/java.base/share/classes/java/util/TimeZone.java @@ -43,7 +43,6 @@ import java.time.ZoneOffset; import jdk.internal.util.StaticProperty; -import sun.security.action.GetPropertyAction; import sun.util.calendar.ZoneInfo; import sun.util.calendar.ZoneInfoFile; import sun.util.locale.provider.TimeZoneNameUtility; @@ -683,7 +682,7 @@ static TimeZone getDefaultRef() { private static synchronized TimeZone setDefaultZone() { TimeZone tz; // get the time zone ID from the system properties - Properties props = GetPropertyAction.privilegedGetProperties(); + Properties props = System.getProperties(); String zoneID = props.getProperty("user.timezone"); // if the time zone ID is not set (yet), perform the @@ -729,12 +728,6 @@ private static synchronized TimeZone setDefaultZone() { */ public static void setDefault(TimeZone zone) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(new PropertyPermission - ("user.timezone", "write")); - } // by saving a defensive clone and returning a clone in getDefault() too, // the defaultTimeZone instance is isolated from user code which makes it // effectively immutable. This is important to avoid races when the diff --git a/src/java.base/share/classes/java/util/Tripwire.java b/src/java.base/share/classes/java/util/Tripwire.java index c807a419619..ec20b956375 100644 --- a/src/java.base/share/classes/java/util/Tripwire.java +++ b/src/java.base/share/classes/java/util/Tripwire.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. * 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,9 +26,6 @@ import sun.util.logging.PlatformLogger; -import java.security.AccessController; -import java.security.PrivilegedAction; - /** * Utility class for detecting inadvertent uses of boxing in * {@code java.util} classes. The detection is turned on or off based on @@ -49,9 +46,7 @@ final class Tripwire { private static final String TRIPWIRE_PROPERTY = "org.openjdk.java.util.stream.tripwire"; /** Should debugging checks be enabled? */ - @SuppressWarnings("removal") - static final boolean ENABLED = AccessController.doPrivileged( - (PrivilegedAction) () -> Boolean.getBoolean(TRIPWIRE_PROPERTY)); + static final boolean ENABLED = Boolean.getBoolean(TRIPWIRE_PROPERTY); private Tripwire() { } diff --git a/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java b/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java index 74cca215e73..6447e6d8a4e 100644 --- a/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java +++ b/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java @@ -76,6 +76,7 @@ import java.util.stream.Stream; import jdk.internal.misc.Unsafe; import jdk.internal.util.ArraysSupport; +import jdk.internal.vm.annotation.Stable; /*[IF CRIU_SUPPORT]*/ import openj9.internal.criu.NotCheckpointSafe; @@ -605,7 +606,16 @@ public class ConcurrentHashMap extends AbstractMap static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash /** Number of CPUS, to place bounds on some sizings */ - static final int NCPU = Runtime.getRuntime().availableProcessors(); + static @Stable int NCPU; + + static { + runtimeSetup(); + } + + // Called from JVM when loading an AOT cache. + private static void runtimeSetup() { + NCPU = Runtime.getRuntime().availableProcessors(); + } /** * Serialized pseudo-fields, provided only for jdk7 compatibility. diff --git a/src/java.base/share/classes/java/util/concurrent/ConcurrentSkipListSet.java b/src/java.base/share/classes/java/util/concurrent/ConcurrentSkipListSet.java index 2a2fbc54d86..0bcb7978e90 100644 --- a/src/java.base/share/classes/java/util/concurrent/ConcurrentSkipListSet.java +++ b/src/java.base/share/classes/java/util/concurrent/ConcurrentSkipListSet.java @@ -527,20 +527,11 @@ public Spliterator spliterator() { /** Initializes map field; for use in clone. */ private void setMap(ConcurrentNavigableMap map) { - @SuppressWarnings("removal") - Field mapField = java.security.AccessController.doPrivileged( - (java.security.PrivilegedAction) () -> { - try { - Field f = ConcurrentSkipListSet.class - .getDeclaredField("m"); - f.setAccessible(true); - return f; - } catch (ReflectiveOperationException e) { - throw new Error(e); - }}); try { + Field mapField = ConcurrentSkipListSet.class.getDeclaredField("m"); + mapField.setAccessible(true); mapField.set(this, map); - } catch (IllegalAccessException e) { + } catch (IllegalAccessException | NoSuchFieldException e) { throw new Error(e); } } diff --git a/src/java.base/share/classes/java/util/concurrent/CopyOnWriteArrayList.java b/src/java.base/share/classes/java/util/concurrent/CopyOnWriteArrayList.java index f0f60730eb6..f5069c61d45 100644 --- a/src/java.base/share/classes/java/util/concurrent/CopyOnWriteArrayList.java +++ b/src/java.base/share/classes/java/util/concurrent/CopyOnWriteArrayList.java @@ -2096,20 +2096,11 @@ public List reversed() { /** Initializes the lock; for use when deserializing or cloning. */ private void resetLock() { - @SuppressWarnings("removal") - Field lockField = java.security.AccessController.doPrivileged( - (java.security.PrivilegedAction) () -> { - try { - Field f = CopyOnWriteArrayList.class - .getDeclaredField("lock"); - f.setAccessible(true); - return f; - } catch (ReflectiveOperationException e) { - throw new Error(e); - }}); try { + Field lockField = CopyOnWriteArrayList.class.getDeclaredField("lock"); + lockField.setAccessible(true); lockField.set(this, new Object()); - } catch (IllegalAccessException e) { + } catch (IllegalAccessException | NoSuchFieldException e) { throw new Error(e); } } diff --git a/src/java.base/share/classes/java/util/concurrent/Executors.java b/src/java.base/share/classes/java/util/concurrent/Executors.java index a0a25b1a70d..f804e225790 100644 --- a/src/java.base/share/classes/java/util/concurrent/Executors.java +++ b/src/java.base/share/classes/java/util/concurrent/Executors.java @@ -37,16 +37,12 @@ import static java.lang.ref.Reference.reachabilityFence; import java.lang.ref.Cleaner.Cleanable; -import java.security.AccessControlContext; -import java.security.AccessController; import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import jdk.internal.ref.CleanerFactory; -import sun.security.util.SecurityConstants; /** * Factory and utility methods for {@link Executor}, {@link @@ -559,27 +555,13 @@ public String toString() { */ private static final class PrivilegedCallable implements Callable { final Callable task; - @SuppressWarnings("removal") - final AccessControlContext acc; - @SuppressWarnings("removal") PrivilegedCallable(Callable task) { this.task = task; - this.acc = AccessController.getContext(); } - @SuppressWarnings("removal") public T call() throws Exception { - try { - return AccessController.doPrivileged( - new PrivilegedExceptionAction() { - public T run() throws Exception { - return task.call(); - } - }, acc); - } catch (PrivilegedActionException e) { - throw e.getException(); - } + return task.call(); } public String toString() { @@ -595,49 +577,26 @@ private static final class PrivilegedCallableUsingCurrentClassLoader implements Callable { final Callable task; @SuppressWarnings("removal") - final AccessControlContext acc; final ClassLoader ccl; @SuppressWarnings("removal") PrivilegedCallableUsingCurrentClassLoader(Callable task) { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - // Calls to getContextClassLoader from this class - // never trigger a security check, but we check - // whether our callers have this permission anyways. - sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); - - // Whether setContextClassLoader turns out to be necessary - // or not, we fail fast if permission is not available. - sm.checkPermission(new RuntimePermission("setContextClassLoader")); - } this.task = task; - this.acc = AccessController.getContext(); this.ccl = Thread.currentThread().getContextClassLoader(); } - @SuppressWarnings("removal") public T call() throws Exception { - try { - return AccessController.doPrivileged( - new PrivilegedExceptionAction() { - public T run() throws Exception { - Thread t = Thread.currentThread(); - ClassLoader cl = t.getContextClassLoader(); - if (ccl == cl) { - return task.call(); - } else { - t.setContextClassLoader(ccl); - try { - return task.call(); - } finally { - t.setContextClassLoader(cl); - } - } - } - }, acc); - } catch (PrivilegedActionException e) { - throw e.getException(); + Thread t = Thread.currentThread(); + ClassLoader cl = t.getContextClassLoader(); + if (ccl == cl) { + return task.call(); + } else { + t.setContextClassLoader(ccl); + try { + return task.call(); + } finally { + t.setContextClassLoader(cl); + } } } @@ -656,10 +615,7 @@ private static class DefaultThreadFactory implements ThreadFactory { private final String namePrefix; DefaultThreadFactory() { - @SuppressWarnings("removal") - SecurityManager s = System.getSecurityManager(); - group = (s != null) ? s.getThreadGroup() : - Thread.currentThread().getThreadGroup(); + group = Thread.currentThread().getThreadGroup(); namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-"; @@ -678,27 +634,14 @@ public Thread newThread(Runnable r) { } /** - * Thread factory capturing access control context and class loader. + * Thread factory capturing the current class loader. */ private static class PrivilegedThreadFactory extends DefaultThreadFactory { @SuppressWarnings("removal") - final AccessControlContext acc; final ClassLoader ccl; - @SuppressWarnings("removal") PrivilegedThreadFactory() { super(); - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - // Calls to getContextClassLoader from this class - // never trigger a security check, but we check - // whether our callers have this permission anyways. - sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); - - // Fail fast - sm.checkPermission(new RuntimePermission("setContextClassLoader")); - } - this.acc = AccessController.getContext(); this.ccl = Thread.currentThread().getContextClassLoader(); } @@ -706,13 +649,8 @@ public Thread newThread(final Runnable r) { return super.newThread(new Runnable() { @SuppressWarnings("removal") public void run() { - AccessController.doPrivileged(new PrivilegedAction<>() { - public Void run() { - Thread.currentThread().setContextClassLoader(ccl); - r.run(); - return null; - } - }, acc); + Thread.currentThread().setContextClassLoader(ccl); + r.run(); } }); } @@ -811,9 +749,7 @@ private static class AutoShutdownDelegatedExecutorService super(executor); Runnable action = () -> { if (!executor.isShutdown()) { - PrivilegedAction pa = () -> { executor.shutdown(); return null; }; - @SuppressWarnings("removal") - var ignore = AccessController.doPrivileged(pa); + executor.shutdown(); } }; cleanable = CleanerFactory.cleaner().register(this, action); diff --git a/src/java.base/share/classes/java/util/concurrent/StructuredTaskScope.java b/src/java.base/share/classes/java/util/concurrent/StructuredTaskScope.java index 17448e9bf3d..41c6b4914b9 100644 --- a/src/java.base/share/classes/java/util/concurrent/StructuredTaskScope.java +++ b/src/java.base/share/classes/java/util/concurrent/StructuredTaskScope.java @@ -26,8 +26,6 @@ import java.lang.invoke.MethodHandles; import java.lang.invoke.VarHandle; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.time.Duration; import java.time.Instant; import java.util.Objects; @@ -688,7 +686,7 @@ public StructuredTaskScope joinUntil(Instant deadline) /** * Interrupt all unfinished threads. */ - private void implInterruptAll() { + private void interruptAll() { flock.threads() .filter(t -> t != Thread.currentThread()) .forEach(t -> { @@ -698,19 +696,6 @@ private void implInterruptAll() { }); } - @SuppressWarnings("removal") - private void interruptAll() { - if (System.getSecurityManager() == null) { - implInterruptAll(); - } else { - PrivilegedAction pa = () -> { - implInterruptAll(); - return null; - }; - AccessController.doPrivileged(pa); - } - } - /** * Shutdown the task scope if not already shutdown. Return true if this method * shutdowns the task scope, false if already shutdown. diff --git a/src/java.base/share/classes/java/util/concurrent/ThreadLocalRandom.java b/src/java.base/share/classes/java/util/concurrent/ThreadLocalRandom.java index 751c190acc0..19eb3122947 100644 --- a/src/java.base/share/classes/java/util/concurrent/ThreadLocalRandom.java +++ b/src/java.base/share/classes/java/util/concurrent/ThreadLocalRandom.java @@ -39,7 +39,6 @@ package java.util.concurrent; import java.io.ObjectStreamField; -import java.security.AccessControlContext; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; diff --git a/src/java.base/share/classes/java/util/concurrent/ThreadPerTaskExecutor.java b/src/java.base/share/classes/java/util/concurrent/ThreadPerTaskExecutor.java index e98ece084c0..f37ef6c956e 100644 --- a/src/java.base/share/classes/java/util/concurrent/ThreadPerTaskExecutor.java +++ b/src/java.base/share/classes/java/util/concurrent/ThreadPerTaskExecutor.java @@ -26,7 +26,6 @@ import java.lang.invoke.MethodHandles; import java.lang.invoke.VarHandle; -import java.security.Permission; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; @@ -48,7 +47,6 @@ */ class ThreadPerTaskExecutor extends ThreadContainer implements ExecutorService { private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess(); - private static final Permission MODIFY_THREAD = new RuntimePermission("modifyThread"); private static final VarHandle STATE = MhUtil.findVarHandle( MethodHandles.lookup(), "state", int.class); @@ -80,18 +78,6 @@ static ThreadPerTaskExecutor create(ThreadFactory factory) { return executor; } - /** - * Throws SecurityException if there is a security manager set and it denies - * RuntimePermission("modifyThread"). - */ - @SuppressWarnings("removal") - private void checkPermission() { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(MODIFY_THREAD); - } - } - /** * Throws RejectedExecutionException if the executor has been shutdown. */ @@ -143,14 +129,12 @@ public long threadCount() { @Override public void shutdown() { - checkPermission(); if (!isShutdown()) tryShutdownAndTerminate(false); } @Override public List shutdownNow() { - checkPermission(); if (!isTerminated()) tryShutdownAndTerminate(true); return List.of(); @@ -202,7 +186,6 @@ private void awaitTermination() { @Override public void close() { - checkPermission(); awaitTermination(); } diff --git a/src/java.base/share/classes/java/util/concurrent/ThreadPoolExecutor.java b/src/java.base/share/classes/java/util/concurrent/ThreadPoolExecutor.java index 65217849f19..e34810fe966 100644 --- a/src/java.base/share/classes/java/util/concurrent/ThreadPoolExecutor.java +++ b/src/java.base/share/classes/java/util/concurrent/ThreadPoolExecutor.java @@ -566,29 +566,6 @@ private void decrementWorkerCount() { private static final RejectedExecutionHandler defaultHandler = new AbortPolicy(); - /** - * Permission required for callers of shutdown and shutdownNow. - * We additionally require (see checkShutdownAccess) that callers - * have permission to actually interrupt threads in the worker set - * (as governed by Thread.interrupt, which relies on - * ThreadGroup.checkAccess, which in turn relies on - * SecurityManager.checkAccess). Shutdowns are attempted only if - * these checks pass. - * - * All actual invocations of Thread.interrupt (see - * interruptIdleWorkers and interruptWorkers) ignore - * SecurityExceptions, meaning that the attempted interrupts - * silently fail. In the case of shutdown, they should not fail - * unless the SecurityManager has inconsistent policies, sometimes - * allowing access to a thread and sometimes not. In such cases, - * failure to actually interrupt threads may disable or delay full - * termination. Other uses of interruptIdleWorkers are advisory, - * and failure to actually interrupt will merely delay response to - * configuration changes so is not handled exceptionally. - */ - private static final RuntimePermission shutdownPerm = - new RuntimePermission("modifyThread"); - /** * Class Worker mainly maintains interrupt control state for * threads running tasks, along with other minor bookkeeping. @@ -673,10 +650,7 @@ protected boolean tryRelease(int unused) { void interruptIfStarted() { Thread t; if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) { - try { - t.interrupt(); - } catch (SecurityException ignore) { - } + t.interrupt(); } } } @@ -749,27 +723,7 @@ final void tryTerminate() { */ /** - * If there is a security manager, makes sure caller has - * permission to shut down threads in general (see shutdownPerm). - * If this passes, additionally makes sure the caller is allowed - * to interrupt each worker thread. This might not be true even if - * first check passed, if the SecurityManager treats some threads - * specially. - */ - private void checkShutdownAccess() { - // assert mainLock.isHeldByCurrentThread(); - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkPermission(shutdownPerm); - for (Worker w : workers) - security.checkAccess(w.thread); - } - } - - /** - * Interrupts all threads, even if active. Ignores SecurityExceptions - * (in which case some threads may remain uninterrupted). + * Interrupts all threads, even if active. */ private void interruptWorkers() { // assert mainLock.isHeldByCurrentThread(); @@ -780,9 +734,7 @@ private void interruptWorkers() { /** * Interrupts threads that might be waiting for tasks (as * indicated by not being locked) so they can check for - * termination or configuration changes. Ignores - * SecurityExceptions (in which case some threads may remain - * uninterrupted). + * termination or configuration changes. * * @param onlyOne If true, interrupt at most one worker. This is * called only from tryTerminate when termination is otherwise @@ -805,7 +757,6 @@ private void interruptIdleWorkers(boolean onlyOne) { if (!t.isInterrupted() && w.tryLock()) { try { t.interrupt(); - } catch (SecurityException ignore) { } finally { w.unlock(); } @@ -1390,7 +1341,6 @@ public void shutdown() { final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { - checkShutdownAccess(); advanceRunState(SHUTDOWN); interruptIdleWorkers(); onShutdown(); // hook for ScheduledThreadPoolExecutor @@ -1420,7 +1370,6 @@ public List shutdownNow() { final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { - checkShutdownAccess(); advanceRunState(STOP); interruptWorkers(); tasks = drainQueue(); diff --git a/src/java.base/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java b/src/java.base/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java index 6d412315153..e01b3ec7d50 100644 --- a/src/java.base/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java +++ b/src/java.base/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java @@ -37,9 +37,6 @@ import java.lang.reflect.Field; import java.lang.reflect.Modifier; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.function.IntBinaryOperator; import java.util.function.IntUnaryOperator; import jdk.internal.misc.Unsafe; @@ -385,30 +382,16 @@ private static final class AtomicIntegerFieldUpdaterImpl /** class holding the field */ private final Class tclass; - @SuppressWarnings("removal") AtomicIntegerFieldUpdaterImpl(final Class tclass, final String fieldName, final Class caller) { final Field field; final int modifiers; try { - field = AccessController.doPrivileged( - new PrivilegedExceptionAction() { - public Field run() throws NoSuchFieldException { - return tclass.getDeclaredField(fieldName); - } - }); + field = tclass.getDeclaredField(fieldName); modifiers = field.getModifiers(); sun.reflect.misc.ReflectUtil.ensureMemberAccess( caller, tclass, null, modifiers); - ClassLoader cl = tclass.getClassLoader(); - ClassLoader ccl = caller.getClassLoader(); - if ((ccl != null) && (ccl != cl) && - ((cl == null) || !isAncestor(cl, ccl))) { - sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass); - } - } catch (PrivilegedActionException pae) { - throw new RuntimeException(pae.getException()); } catch (Exception ex) { throw new RuntimeException(ex); } diff --git a/src/java.base/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java b/src/java.base/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java index 0e496dbd6a5..57722f33371 100644 --- a/src/java.base/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java +++ b/src/java.base/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java @@ -37,9 +37,6 @@ import java.lang.reflect.Field; import java.lang.reflect.Modifier; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.function.LongBinaryOperator; import java.util.function.LongUnaryOperator; import jdk.internal.misc.Unsafe; @@ -381,29 +378,15 @@ private static final class CASUpdater extends AtomicLongFieldUpdater { /** class holding the field */ private final Class tclass; - @SuppressWarnings("removal") CASUpdater(final Class tclass, final String fieldName, final Class caller) { final Field field; final int modifiers; try { - field = AccessController.doPrivileged( - new PrivilegedExceptionAction() { - public Field run() throws NoSuchFieldException { - return tclass.getDeclaredField(fieldName); - } - }); + field = tclass.getDeclaredField(fieldName); modifiers = field.getModifiers(); sun.reflect.misc.ReflectUtil.ensureMemberAccess( caller, tclass, null, modifiers); - ClassLoader cl = tclass.getClassLoader(); - ClassLoader ccl = caller.getClassLoader(); - if ((ccl != null) && (ccl != cl) && - ((cl == null) || !isAncestor(cl, ccl))) { - sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass); - } - } catch (PrivilegedActionException pae) { - throw new RuntimeException(pae.getException()); } catch (Exception ex) { throw new RuntimeException(ex); } diff --git a/src/java.base/share/classes/java/util/concurrent/atomic/AtomicReferenceArray.java b/src/java.base/share/classes/java/util/concurrent/atomic/AtomicReferenceArray.java index ec00f40a568..dbec6b81dd9 100644 --- a/src/java.base/share/classes/java/util/concurrent/atomic/AtomicReferenceArray.java +++ b/src/java.base/share/classes/java/util/concurrent/atomic/AtomicReferenceArray.java @@ -329,20 +329,12 @@ private void readObject(java.io.ObjectInputStream s) throw new java.io.InvalidObjectException("Not array type"); if (a.getClass() != Object[].class) a = Arrays.copyOf((Object[])a, Array.getLength(a), Object[].class); - @SuppressWarnings("removal") - Field arrayField = java.security.AccessController.doPrivileged( - (java.security.PrivilegedAction) () -> { - try { - Field f = AtomicReferenceArray.class - .getDeclaredField("array"); - f.setAccessible(true); - return f; - } catch (ReflectiveOperationException e) { - throw new Error(e); - }}); try { + + Field arrayField = AtomicReferenceArray.class.getDeclaredField("array"); + arrayField.setAccessible(true); arrayField.set(this, a); - } catch (IllegalAccessException e) { + } catch (NoSuchFieldException | IllegalAccessException e) { throw new Error(e); } } diff --git a/src/java.base/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java b/src/java.base/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java index b9dcdac9ba5..1c0c6d0afd0 100644 --- a/src/java.base/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java +++ b/src/java.base/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java @@ -37,9 +37,6 @@ import java.lang.reflect.Field; import java.lang.reflect.Modifier; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.function.BinaryOperator; import java.util.function.UnaryOperator; import jdk.internal.misc.Unsafe; @@ -320,7 +317,6 @@ private static final class AtomicReferenceFieldUpdaterImpl * screenings fail. */ - @SuppressWarnings("removal") AtomicReferenceFieldUpdaterImpl(final Class tclass, final Class vclass, final String fieldName, @@ -329,24 +325,11 @@ private static final class AtomicReferenceFieldUpdaterImpl final Class fieldClass; final int modifiers; try { - field = AccessController.doPrivileged( - new PrivilegedExceptionAction() { - public Field run() throws NoSuchFieldException { - return tclass.getDeclaredField(fieldName); - } - }); + field = tclass.getDeclaredField(fieldName); modifiers = field.getModifiers(); sun.reflect.misc.ReflectUtil.ensureMemberAccess( caller, tclass, null, modifiers); - ClassLoader cl = tclass.getClassLoader(); - ClassLoader ccl = caller.getClassLoader(); - if ((ccl != null) && (ccl != cl) && - ((cl == null) || !isAncestor(cl, ccl))) { - sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass); - } fieldClass = field.getType(); - } catch (PrivilegedActionException pae) { - throw new RuntimeException(pae.getException()); } catch (Exception ex) { throw new RuntimeException(ex); } diff --git a/src/java.base/share/classes/java/util/concurrent/atomic/Striped64.java b/src/java.base/share/classes/java/util/concurrent/atomic/Striped64.java index 04ae2b45158..ad230f62ab6 100644 --- a/src/java.base/share/classes/java/util/concurrent/atomic/Striped64.java +++ b/src/java.base/share/classes/java/util/concurrent/atomic/Striped64.java @@ -380,17 +380,12 @@ else if (casBase(v = base, apply(fn, v, x))) BASE = MhUtil.findVarHandle(l1, "base", long.class); CELLSBUSY = MhUtil.findVarHandle(l1, "cellsBusy", int.class); - @SuppressWarnings("removal") - MethodHandles.Lookup l2 = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction<>() { - public MethodHandles.Lookup run() { - try { - return MethodHandles.privateLookupIn(Thread.class, MethodHandles.lookup()); - } catch (ReflectiveOperationException e) { - throw new ExceptionInInitializerError(e); - } - }}); - THREAD_PROBE = MhUtil.findVarHandle(l2, "threadLocalRandomProbe", int.class); + try { + MethodHandles.Lookup l2 = MethodHandles.privateLookupIn(Thread.class, l1); + THREAD_PROBE = MhUtil.findVarHandle(l2, "threadLocalRandomProbe", int.class); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } } } diff --git a/src/java.base/share/classes/java/util/jar/JarFile.java b/src/java.base/share/classes/java/util/jar/JarFile.java index a14821d8046..7b64e3cdd04 100644 --- a/src/java.base/share/classes/java/util/jar/JarFile.java +++ b/src/java.base/share/classes/java/util/jar/JarFile.java @@ -28,7 +28,6 @@ import jdk.internal.access.SharedSecrets; import jdk.internal.access.JavaUtilZipFileAccess; import jdk.internal.misc.ThreadTracker; -import sun.security.action.GetPropertyAction; import sun.security.util.ManifestEntryVerifier; import sun.security.util.SignatureFileVerifier; @@ -171,7 +170,7 @@ public class JarFile extends ZipFile { // multi-release jar file versions >= 9 BASE_VERSION = Runtime.Version.parse(Integer.toString(8)); BASE_VERSION_FEATURE = BASE_VERSION.feature(); - String jarVersion = GetPropertyAction.privilegedGetProperty("jdk.util.jar.version"); + String jarVersion = System.getProperty("jdk.util.jar.version"); int runtimeVersion = Runtime.version().feature(); if (jarVersion != null) { int jarVer = Integer.parseInt(jarVersion); @@ -180,8 +179,8 @@ public class JarFile extends ZipFile { : Math.max(jarVer, BASE_VERSION_FEATURE); } RUNTIME_VERSION = Runtime.Version.parse(Integer.toString(runtimeVersion)); - String enableMultiRelease = GetPropertyAction - .privilegedGetProperty("jdk.util.jar.enableMultiRelease", "true"); + String enableMultiRelease = System. + getProperty("jdk.util.jar.enableMultiRelease", "true"); switch (enableMultiRelease) { case "false" -> { MULTI_RELEASE_ENABLED = false; diff --git a/src/java.base/share/classes/java/util/spi/AbstractResourceBundleProvider.java b/src/java.base/share/classes/java/util/spi/AbstractResourceBundleProvider.java index 6eb35aed691..8db27ec586d 100644 --- a/src/java.base/share/classes/java/util/spi/AbstractResourceBundleProvider.java +++ b/src/java.base/share/classes/java/util/spi/AbstractResourceBundleProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * 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,12 +32,9 @@ import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Locale; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; -import static sun.security.util.SecurityConstants.GET_CLASSLOADER_PERMISSION; /** * {@code AbstractResourceBundleProvider} is an abstract class that provides @@ -78,11 +75,10 @@ * return null; * } * }} - * + *

* Refer to {@link ResourceBundleProvider} for details. * - * @see - * Resource Bundles and Named Modules + * @see ResourceBundle##resource-bundle-modules Resource Bundles and Named Modules * @since 9 */ public abstract class AbstractResourceBundleProvider implements ResourceBundleProvider { @@ -222,11 +218,8 @@ private ResourceBundle getBundle0(Module module, String bundleName) { * Returns the ResourceBundle of .class format if found in the module * of this provider. */ - private static ResourceBundle loadResourceBundle(Module module, String bundleName) - { - PrivilegedAction> pa = () -> Class.forName(module, bundleName); - @SuppressWarnings("removal") - Class c = AccessController.doPrivileged(pa, null, GET_CLASSLOADER_PERMISSION); + private static ResourceBundle loadResourceBundle(Module module, String bundleName) { + Class c = Class.forName(module, bundleName); if (c != null && ResourceBundle.class.isAssignableFrom(c)) { @SuppressWarnings("unchecked") Class bundleClass = (Class) c; @@ -241,28 +234,17 @@ private static ResourceBundle loadResourceBundle(Module module, String bundleNam */ private static ResourceBundle loadPropertyResourceBundle(Module module, String bundleName) - throws IOException - { + throws IOException { String resourceName = toResourceName(bundleName, "properties"); if (resourceName == null) { return null; } - PrivilegedAction pa = () -> { - try { - return module.getResourceAsStream(resourceName); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }; - try (@SuppressWarnings("removal") InputStream stream = AccessController.doPrivileged(pa)) { - if (stream != null) { - return new PropertyResourceBundle(stream); - } else { - return null; - } - } catch (UncheckedIOException e) { - throw e.getCause(); + InputStream stream = module.getResourceAsStream(resourceName); + if (stream != null) { + return new PropertyResourceBundle(stream); + } else { + return null; } } diff --git a/src/java.base/share/classes/java/util/spi/LocaleServiceProvider.java b/src/java.base/share/classes/java/util/spi/LocaleServiceProvider.java index 46712e5c80b..6e130872bd4 100644 --- a/src/java.base/share/classes/java/util/spi/LocaleServiceProvider.java +++ b/src/java.base/share/classes/java/util/spi/LocaleServiceProvider.java @@ -222,22 +222,10 @@ */ public abstract class LocaleServiceProvider { - private static Void checkPermission() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(new RuntimePermission("localeServiceProvider")); - } - return null; - } - private LocaleServiceProvider(Void ignore) { } - /** * Initializes a new locale service provider. */ - protected LocaleServiceProvider() { - this(checkPermission()); - } + protected LocaleServiceProvider() {} /** * {@return an array of all locales for which this locale service provider diff --git a/src/java.base/share/classes/java/util/spi/ToolProvider.java b/src/java.base/share/classes/java/util/spi/ToolProvider.java index 1a3a710e0be..20909522859 100644 --- a/src/java.base/share/classes/java/util/spi/ToolProvider.java +++ b/src/java.base/share/classes/java/util/spi/ToolProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,8 +27,6 @@ import java.io.PrintStream; import java.io.PrintWriter; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Objects; import java.util.Optional; import java.util.ServiceLoader; @@ -178,18 +176,14 @@ default int run(PrintStream out, PrintStream err, String... args) { * * @throws NullPointerException if {@code name} is {@code null} */ - @SuppressWarnings("removal") static Optional findFirst(String name) { Objects.requireNonNull(name); ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); - return AccessController.doPrivileged( - (PrivilegedAction>) () -> { - ServiceLoader sl = - ServiceLoader.load(ToolProvider.class, systemClassLoader); - return StreamSupport.stream(sl.spliterator(), false) - .filter(p -> p.name().equals(name)) - .findFirst(); - }); + + ServiceLoader sl = + ServiceLoader.load(ToolProvider.class, systemClassLoader); + return StreamSupport.stream(sl.spliterator(), false) + .filter(p -> p.name().equals(name)) + .findFirst(); } } - diff --git a/src/java.base/share/classes/java/util/stream/Tripwire.java b/src/java.base/share/classes/java/util/stream/Tripwire.java index 962c7d3e1b0..6aae5e67e50 100644 --- a/src/java.base/share/classes/java/util/stream/Tripwire.java +++ b/src/java.base/share/classes/java/util/stream/Tripwire.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. * 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,9 +24,6 @@ */ package java.util.stream; -import java.security.AccessController; -import java.security.PrivilegedAction; - import sun.util.logging.PlatformLogger; /** @@ -49,9 +46,7 @@ final class Tripwire { private static final String TRIPWIRE_PROPERTY = "org.openjdk.java.util.stream.tripwire"; /** Should debugging checks be enabled? */ - @SuppressWarnings("removal") - static final boolean ENABLED = AccessController.doPrivileged( - (PrivilegedAction) () -> Boolean.getBoolean(TRIPWIRE_PROPERTY)); + static final boolean ENABLED = Boolean.getBoolean(TRIPWIRE_PROPERTY); private Tripwire() { } 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 7c5b231a838..acae1bc371c 100644 --- a/src/java.base/share/classes/java/util/zip/ZipFile.java +++ b/src/java.base/share/classes/java/util/zip/ZipFile.java @@ -61,7 +61,6 @@ import jdk.internal.vm.annotation.Stable; import sun.nio.cs.UTF_8; import sun.nio.fs.DefaultFileSystemProvider; -import sun.security.action.GetPropertyAction; import sun.security.util.SignatureFileVerifier; import static java.util.zip.ZipConstants64.*; @@ -203,14 +202,6 @@ public ZipFile(File file, int mode, Charset charset) throws IOException } String name = file.getPath(); file = new File(name); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkRead(name); - if ((mode & OPEN_DELETE) != 0) { - sm.checkDelete(name); - } - } Objects.requireNonNull(charset, "charset"); this.filePath = name; @@ -1072,8 +1063,7 @@ private BitSet getMetaInfVersions(String name) { */ static boolean getDisableZip64ExtraFieldValidation() { boolean result; - String value = GetPropertyAction.privilegedGetProperty( - "jdk.util.zip.disableZip64ExtraFieldValidation"); + String value = System.getProperty("jdk.util.zip.disableZip64ExtraFieldValidation"); if (value == null) { result = false; } else { diff --git a/src/java.base/share/classes/java/util/zip/ZipOutputStream.java b/src/java.base/share/classes/java/util/zip/ZipOutputStream.java index 3fe992ab440..47499858a37 100644 --- a/src/java.base/share/classes/java/util/zip/ZipOutputStream.java +++ b/src/java.base/share/classes/java/util/zip/ZipOutputStream.java @@ -35,7 +35,6 @@ import static java.util.zip.ZipEntry.isCENHeaderValid; import static java.util.zip.ZipUtils.*; import sun.nio.cs.UTF_8; -import sun.security.action.GetBooleanAction; /** * This class implements an output stream filter for writing files in the @@ -58,7 +57,7 @@ public class ZipOutputStream extends DeflaterOutputStream implements ZipConstant * some in jdk7. */ private static final boolean inhibitZip64 = - GetBooleanAction.privilegedGetProperty("jdk.util.zip.inhibitZip64"); + Boolean.getBoolean("jdk.util.zip.inhibitZip64"); private static class XEntry { final ZipEntry entry; diff --git a/src/java.base/share/classes/jdk/internal/access/SharedSecrets.java b/src/java.base/share/classes/jdk/internal/access/SharedSecrets.java index 5acafe01a89..c29d0dd01a5 100644 --- a/src/java.base/share/classes/jdk/internal/access/SharedSecrets.java +++ b/src/java.base/share/classes/jdk/internal/access/SharedSecrets.java @@ -71,8 +71,6 @@ public class SharedSecrets { private static JavaLangRefAccess javaLangRefAccess; private static JavaLangReflectAccess javaLangReflectAccess; private static JavaIOAccess javaIOAccess; - private static JavaIOPrintStreamAccess javaIOPrintStreamAccess; - private static JavaIOPrintWriterAccess javaIOPrintWriterAccess; private static JavaIOFileDescriptorAccess javaIOFileDescriptorAccess; private static JavaIOFilePermissionAccess javaIOFilePermissionAccess; private static JavaIORandomAccessFileAccess javaIORandomAccessFileAccess; @@ -288,32 +286,6 @@ public static JavaIOAccess getJavaIOAccess() { return access; } - public static void setJavaIOCPrintWriterAccess(JavaIOPrintWriterAccess a) { - javaIOPrintWriterAccess = a; - } - - public static JavaIOPrintWriterAccess getJavaIOPrintWriterAccess() { - var access = javaIOPrintWriterAccess; - if (access == null) { - ensureClassInitialized(PrintWriter.class); - access = javaIOPrintWriterAccess; - } - return access; - } - - public static void setJavaIOCPrintStreamAccess(JavaIOPrintStreamAccess a) { - javaIOPrintStreamAccess = a; - } - - public static JavaIOPrintStreamAccess getJavaIOPrintStreamAccess() { - var access = javaIOPrintStreamAccess; - if (access == null) { - ensureClassInitialized(PrintStream.class); - access = javaIOPrintStreamAccess; - } - return access; - } - public static void setJavaIOFileDescriptorAccess(JavaIOFileDescriptorAccess jiofda) { javaIOFileDescriptorAccess = jiofda; } diff --git a/src/java.base/share/classes/jdk/internal/classfile/impl/AbstractAttributeMapper.java b/src/java.base/share/classes/jdk/internal/classfile/impl/AbstractAttributeMapper.java index 631d6fda849..88759fece13 100644 --- a/src/java.base/share/classes/jdk/internal/classfile/impl/AbstractAttributeMapper.java +++ b/src/java.base/share/classes/jdk/internal/classfile/impl/AbstractAttributeMapper.java @@ -64,7 +64,7 @@ public final String name() { @Override public final void writeAttribute(BufWriter writer, T attr) { BufWriterImpl buf = (BufWriterImpl) writer; - buf.writeIndex(buf.constantPool().utf8Entry(name)); + buf.writeIndex(attr.attributeName()); int lengthIndex = buf.skip(4); writeBody(buf, attr); int written = buf.size() - lengthIndex - 4; diff --git a/src/java.base/share/classes/jdk/internal/classfile/impl/BoundAttribute.java b/src/java.base/share/classes/jdk/internal/classfile/impl/BoundAttribute.java index eb8cad76ca2..8ab1fba0b75 100644 --- a/src/java.base/share/classes/jdk/internal/classfile/impl/BoundAttribute.java +++ b/src/java.base/share/classes/jdk/internal/classfile/impl/BoundAttribute.java @@ -47,6 +47,7 @@ public abstract sealed class BoundAttribute> private final AttributeMapper mapper; final ClassReaderImpl classReader; final int payloadStart; + Utf8Entry name; BoundAttribute(ClassReader classReader, AttributeMapper mapper, int payloadStart) { this.mapper = mapper; @@ -59,8 +60,11 @@ public int payloadLen() { } @Override - public String attributeName() { - return mapper.name(); + public Utf8Entry attributeName() { + if (name == null) { + name = classReader.readEntry(payloadStart - 6, Utf8Entry.class); + } + return name; } @Override diff --git a/src/java.base/share/classes/jdk/internal/classfile/impl/ClassPrinterImpl.java b/src/java.base/share/classes/jdk/internal/classfile/impl/ClassPrinterImpl.java index bd2f9bf931b..70cb5ba46d5 100644 --- a/src/java.base/share/classes/jdk/internal/classfile/impl/ClassPrinterImpl.java +++ b/src/java.base/share/classes/jdk/internal/classfile/impl/ClassPrinterImpl.java @@ -574,7 +574,7 @@ private static MapNode classToTree(ClassModel clm, Verbosity verbosity) { list("flags", "flag", clm.flags().flags().stream().map(AccessFlag::name)), leaf("superclass", clm.superclass().map(ClassEntry::asInternalName).orElse("")), list("interfaces", "interface", clm.interfaces().stream().map(ClassEntry::asInternalName)), - list("attributes", "attribute", clm.attributes().stream().map(Attribute::attributeName))) + list("attributes", "attribute", clm.attributes().stream().map(Attribute::attributeName).map(Utf8Entry::stringValue))) .with(constantPoolToTree(clm.constantPool(), verbosity)) .with(attributesToTree(clm.attributes(), verbosity)) .with(new ListNodeImpl(BLOCK, "fields", clm.fields().stream().map(f -> @@ -672,7 +672,7 @@ private static MapNode fieldToTree(FieldModel f, Verbosity verbosity) { "flag", f.flags().flags().stream().map(AccessFlag::name)), leaf("field type", f.fieldType().stringValue()), list("attributes", - "attribute", f.attributes().stream().map(Attribute::attributeName))) + "attribute", f.attributes().stream().map(Attribute::attributeName).map(Utf8Entry::stringValue))) .with(attributesToTree(f.attributes(), verbosity)); } @@ -683,7 +683,7 @@ public static MapNode methodToTree(MethodModel m, Verbosity verbosity) { "flag", m.flags().flags().stream().map(AccessFlag::name)), leaf("method type", m.methodType().stringValue()), list("attributes", - "attribute", m.attributes().stream().map(Attribute::attributeName))) + "attribute", m.attributes().stream().map(Attribute::attributeName).map(Utf8Entry::stringValue))) .with(attributesToTree(m.attributes(), verbosity)) .with(codeToTree((CodeAttribute)m.code().orElse(null), verbosity)); } @@ -694,7 +694,7 @@ private static MapNode codeToTree(CodeAttribute com, Verbosity verbosity) { codeNode.with(leaf("max stack", com.maxStack())); codeNode.with(leaf("max locals", com.maxLocals())); codeNode.with(list("attributes", - "attribute", com.attributes().stream().map(Attribute::attributeName))); + "attribute", com.attributes().stream().map(Attribute::attributeName).map(Utf8Entry::stringValue))); var stackMap = new MapNodeImpl(BLOCK, "stack map frames"); var visibleTypeAnnos = new LinkedHashMap>(); var invisibleTypeAnnos = new LinkedHashMap>(); @@ -999,7 +999,7 @@ private static Node[] attributesToTree(List> attributes, Verbosity "name", rc.name().stringValue(), "type", rc.descriptor().stringValue())) .with(list("attributes", "attribute", rc.attributes().stream() - .map(Attribute::attributeName))) + .map(Attribute::attributeName).map(Utf8Entry::stringValue))) .with(attributesToTree(rc.attributes(), verbosity))))); case AnnotationDefaultAttribute ada -> nodes.add(new MapNodeImpl(FLOW, "annotation default").with(elementValueToTree(ada.defaultValue()))); diff --git a/src/java.base/share/classes/jdk/internal/classfile/impl/DirectCodeBuilder.java b/src/java.base/share/classes/jdk/internal/classfile/impl/DirectCodeBuilder.java index 7d554a35974..5093f6408c8 100644 --- a/src/java.base/share/classes/jdk/internal/classfile/impl/DirectCodeBuilder.java +++ b/src/java.base/share/classes/jdk/internal/classfile/impl/DirectCodeBuilder.java @@ -241,6 +241,11 @@ public void writeBody(BufWriterImpl b) { if (crSize < characterRangesCount) b.patchU2(pos, crSize); } + + @Override + public Utf8Entry attributeName() { + return constantPool.utf8Entry(Attributes.NAME_CHARACTER_RANGE_TABLE); + } }; attributes.withAttribute(a); } @@ -265,6 +270,11 @@ public void writeBody(BufWriterImpl b) { if (lvSize < localVariablesCount) b.patchU2(pos, lvSize); } + + @Override + public Utf8Entry attributeName() { + return constantPool.utf8Entry(Attributes.NAME_LOCAL_VARIABLE_TABLE); + } }; attributes.withAttribute(a); } @@ -289,6 +299,11 @@ public void writeBody(BufWriterImpl b) { if (lvtSize < localVariableTypesCount) b.patchU2(pos, lvtSize); } + + @Override + public Utf8Entry attributeName() { + return constantPool.utf8Entry(Attributes.NAME_LOCAL_VARIABLE_TYPE_TABLE); + } }; attributes.withAttribute(a); } @@ -371,6 +386,11 @@ public void writeBody(BufWriterImpl buf) { dcb.attributes.writeTo(buf); buf.setLabelContext(null); } + + @Override + public Utf8Entry attributeName() { + return constantPool.utf8Entry(Attributes.NAME_CODE); + } }; } @@ -416,6 +436,11 @@ public void writeTo(BufWriterImpl b) { b.writeU2(buf.size() / 4); b.writeBytes(buf); } + + @Override + public Utf8Entry attributeName() { + return buf.constantPool().utf8Entry(Attributes.NAME_LINE_NUMBER_TABLE); + } } private boolean codeAndExceptionsMatch(int codeLength) { diff --git a/src/java.base/share/classes/jdk/internal/classfile/impl/SplitConstantPool.java b/src/java.base/share/classes/jdk/internal/classfile/impl/SplitConstantPool.java index 706e477cb88..de0910b9a88 100644 --- a/src/java.base/share/classes/jdk/internal/classfile/impl/SplitConstantPool.java +++ b/src/java.base/share/classes/jdk/internal/classfile/impl/SplitConstantPool.java @@ -146,6 +146,11 @@ public void writeBody(BufWriterImpl b) { for (int i = 0; i < bsmSize; i++) bootstrapMethodEntry(i).writeTo(buf); } + + @Override + public Utf8Entry attributeName() { + return utf8Entry(Attributes.NAME_BOOTSTRAP_METHODS); + } }; a.writeTo(buf); } diff --git a/src/java.base/share/classes/jdk/internal/classfile/impl/StackMapGenerator.java b/src/java.base/share/classes/jdk/internal/classfile/impl/StackMapGenerator.java index a83c32dc05a..7e16aea5a52 100644 --- a/src/java.base/share/classes/jdk/internal/classfile/impl/StackMapGenerator.java +++ b/src/java.base/share/classes/jdk/internal/classfile/impl/StackMapGenerator.java @@ -35,6 +35,7 @@ import java.lang.classfile.constantpool.ConstantPoolBuilder; import java.lang.classfile.constantpool.InvokeDynamicEntry; import java.lang.classfile.constantpool.MemberRefEntry; +import java.lang.classfile.constantpool.Utf8Entry; import java.lang.constant.ClassDesc; import java.lang.constant.MethodTypeDesc; import java.util.ArrayList; @@ -401,6 +402,11 @@ public void writeBody(BufWriterImpl b) { prevFrame = fr; } } + + @Override + public Utf8Entry attributeName() { + return cp.utf8Entry(Attributes.NAME_STACK_MAP_TABLE); + } }; } diff --git a/src/java.base/share/classes/jdk/internal/classfile/impl/UnboundAttribute.java b/src/java.base/share/classes/jdk/internal/classfile/impl/UnboundAttribute.java index 80b2995799e..98a263b6d5e 100644 --- a/src/java.base/share/classes/jdk/internal/classfile/impl/UnboundAttribute.java +++ b/src/java.base/share/classes/jdk/internal/classfile/impl/UnboundAttribute.java @@ -54,11 +54,6 @@ public AttributeMapper attributeMapper() { return mapper; } - @Override - public String attributeName() { - return mapper.name(); - } - @Override @SuppressWarnings("unchecked") public void writeTo(BufWriterImpl buf) { @@ -93,6 +88,8 @@ public static final class UnboundConstantValueAttribute extends UnboundAttribute implements ConstantValueAttribute { + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_CONSTANT_VALUE); + private final ConstantValueEntry entry; public UnboundConstantValueAttribute(ConstantValueEntry entry) { @@ -105,27 +102,50 @@ public ConstantValueEntry constant() { return entry; } + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundDeprecatedAttribute extends UnboundAttribute implements DeprecatedAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_DEPRECATED); + public UnboundDeprecatedAttribute() { super(Attributes.deprecated()); } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundSyntheticAttribute extends UnboundAttribute implements SyntheticAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_SYNTHETIC); + public UnboundSyntheticAttribute() { super(Attributes.synthetic()); } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundSignatureAttribute extends UnboundAttribute implements SignatureAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_SIGNATURE); + private final Utf8Entry signature; public UnboundSignatureAttribute(Utf8Entry signature) { @@ -137,11 +157,19 @@ public UnboundSignatureAttribute(Utf8Entry signature) { public Utf8Entry signature() { return signature; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundExceptionsAttribute extends UnboundAttribute implements ExceptionsAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_EXCEPTIONS); + private final List exceptions; public UnboundExceptionsAttribute(List exceptions) { @@ -153,11 +181,19 @@ public UnboundExceptionsAttribute(List exceptions) { public List exceptions() { return exceptions; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundAnnotationDefaultAttribute extends UnboundAttribute implements AnnotationDefaultAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_ANNOTATION_DEFAULT); + private final AnnotationValue annotationDefault; public UnboundAnnotationDefaultAttribute(AnnotationValue annotationDefault) { @@ -169,10 +205,18 @@ public UnboundAnnotationDefaultAttribute(AnnotationValue annotationDefault) { public AnnotationValue defaultValue() { return annotationDefault; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundSourceFileAttribute extends UnboundAttribute implements SourceFileAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_SOURCE_FILE); + private final Utf8Entry sourceFile; public UnboundSourceFileAttribute(Utf8Entry sourceFile) { @@ -185,10 +229,17 @@ public Utf8Entry sourceFile() { return sourceFile; } + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundStackMapTableAttribute extends UnboundAttribute implements StackMapTableAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_STACK_MAP_TABLE); + private final List entries; public UnboundStackMapTableAttribute(List entries) { @@ -200,11 +251,19 @@ public UnboundStackMapTableAttribute(List entries) { public List entries() { return entries; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundInnerClassesAttribute extends UnboundAttribute implements InnerClassesAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_INNER_CLASSES); + private final List innerClasses; public UnboundInnerClassesAttribute(List innerClasses) { @@ -216,11 +275,19 @@ public UnboundInnerClassesAttribute(List innerClasses) { public List classes() { return innerClasses; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundRecordAttribute extends UnboundAttribute implements RecordAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_RECORD); + private final List components; public UnboundRecordAttribute(List components) { @@ -232,11 +299,19 @@ public UnboundRecordAttribute(List components) { public List components() { return components; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundEnclosingMethodAttribute extends UnboundAttribute implements EnclosingMethodAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_ENCLOSING_METHOD); + private final ClassEntry classEntry; private final NameAndTypeEntry method; @@ -255,11 +330,19 @@ public ClassEntry enclosingClass() { public Optional enclosingMethod() { return Optional.ofNullable(method); } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundMethodParametersAttribute extends UnboundAttribute implements MethodParametersAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_METHOD_PARAMETERS); + private final List parameters; public UnboundMethodParametersAttribute(List parameters) { @@ -271,11 +354,19 @@ public UnboundMethodParametersAttribute(List parameters) { public List parameters() { return parameters; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundModuleTargetAttribute extends UnboundAttribute implements ModuleTargetAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_MODULE_TARGET); + final Utf8Entry moduleTarget; public UnboundModuleTargetAttribute(Utf8Entry moduleTarget) { @@ -287,11 +378,19 @@ public UnboundModuleTargetAttribute(Utf8Entry moduleTarget) { public Utf8Entry targetPlatform() { return moduleTarget; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundModuleMainClassAttribute extends UnboundAttribute implements ModuleMainClassAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_MODULE_MAIN_CLASS); + final ClassEntry mainClass; public UnboundModuleMainClassAttribute(ClassEntry mainClass) { @@ -303,11 +402,19 @@ public UnboundModuleMainClassAttribute(ClassEntry mainClass) { public ClassEntry mainClass() { return mainClass; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundModuleHashesAttribute extends UnboundAttribute implements ModuleHashesAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_MODULE_HASHES); + private final Utf8Entry algorithm; private final List hashes; @@ -326,11 +433,19 @@ public Utf8Entry algorithm() { public List hashes() { return hashes; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundModulePackagesAttribute extends UnboundAttribute implements ModulePackagesAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_MODULE_PACKAGES); + private final Collection packages; public UnboundModulePackagesAttribute(Collection packages) { @@ -342,11 +457,19 @@ public UnboundModulePackagesAttribute(Collection packages) { public List packages() { return List.copyOf(packages); } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundModuleResolutionAttribute extends UnboundAttribute implements ModuleResolutionAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_MODULE_RESOLUTION); + private final int resolutionFlags; public UnboundModuleResolutionAttribute(int flags) { @@ -358,11 +481,19 @@ public UnboundModuleResolutionAttribute(int flags) { public int resolutionFlags() { return resolutionFlags; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundPermittedSubclassesAttribute extends UnboundAttribute implements PermittedSubclassesAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_PERMITTED_SUBCLASSES); + private final List permittedSubclasses; public UnboundPermittedSubclassesAttribute(List permittedSubclasses) { @@ -374,6 +505,11 @@ public UnboundPermittedSubclassesAttribute(List permittedSubclasses) public List permittedSubclasses() { return permittedSubclasses; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundLoadableDescriptorsAttribute @@ -395,6 +531,9 @@ public List loadableDescriptors() { public static final class UnboundNestMembersAttribute extends UnboundAttribute implements NestMembersAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_NEST_MEMBERS); + private final List memberEntries; public UnboundNestMembersAttribute(List memberEntries) { @@ -406,11 +545,19 @@ public UnboundNestMembersAttribute(List memberEntries) { public List nestMembers() { return memberEntries; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundNestHostAttribute extends UnboundAttribute implements NestHostAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_NEST_HOST); + private final ClassEntry hostEntry; public UnboundNestHostAttribute(ClassEntry hostEntry) { @@ -422,11 +569,19 @@ public UnboundNestHostAttribute(ClassEntry hostEntry) { public ClassEntry nestHost() { return hostEntry; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundCompilationIDAttribute extends UnboundAttribute implements CompilationIDAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_COMPILATION_ID); + private final Utf8Entry idEntry; public UnboundCompilationIDAttribute(Utf8Entry idEntry) { @@ -438,11 +593,19 @@ public UnboundCompilationIDAttribute(Utf8Entry idEntry) { public Utf8Entry compilationId() { return idEntry; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundSourceIDAttribute extends UnboundAttribute implements SourceIDAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_SOURCE_ID); + private final Utf8Entry idEntry; public UnboundSourceIDAttribute(Utf8Entry idEntry) { @@ -454,11 +617,19 @@ public UnboundSourceIDAttribute(Utf8Entry idEntry) { public Utf8Entry sourceId() { return idEntry; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundSourceDebugExtensionAttribute extends UnboundAttribute implements SourceDebugExtensionAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_SOURCE_DEBUG_EXTENSION); + private final byte[] contents; public UnboundSourceDebugExtensionAttribute(byte[] contents) { @@ -470,11 +641,19 @@ public UnboundSourceDebugExtensionAttribute(byte[] contents) { public byte[] contents() { return contents; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundCharacterRangeTableAttribute extends UnboundAttribute implements CharacterRangeTableAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_CHARACTER_RANGE_TABLE); + private final List ranges; public UnboundCharacterRangeTableAttribute(List ranges) { @@ -486,11 +665,19 @@ public UnboundCharacterRangeTableAttribute(List ranges) { public List characterRangeTable() { return ranges; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundLineNumberTableAttribute extends UnboundAttribute implements LineNumberTableAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_LINE_NUMBER_TABLE); + private final List lines; public UnboundLineNumberTableAttribute(List lines) { @@ -502,11 +689,19 @@ public UnboundLineNumberTableAttribute(List lines) { public List lineNumbers() { return lines; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundLocalVariableTableAttribute extends UnboundAttribute implements LocalVariableTableAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_LOCAL_VARIABLE_TABLE); + private final List locals; public UnboundLocalVariableTableAttribute(List locals) { @@ -518,11 +713,19 @@ public UnboundLocalVariableTableAttribute(List locals) { public List localVariables() { return locals; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundLocalVariableTypeTableAttribute extends UnboundAttribute implements LocalVariableTypeTableAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_LOCAL_VARIABLE_TYPE_TABLE); + private final List locals; public UnboundLocalVariableTypeTableAttribute(List locals) { @@ -534,11 +737,19 @@ public UnboundLocalVariableTypeTableAttribute(List locals public List localVariableTypes() { return locals; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundRuntimeVisibleAnnotationsAttribute extends UnboundAttribute implements RuntimeVisibleAnnotationsAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_RUNTIME_VISIBLE_ANNOTATIONS); + private final List elements; public UnboundRuntimeVisibleAnnotationsAttribute(List elements) { @@ -550,11 +761,19 @@ public UnboundRuntimeVisibleAnnotationsAttribute(List elements) { public List annotations() { return elements; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundRuntimeInvisibleAnnotationsAttribute extends UnboundAttribute implements RuntimeInvisibleAnnotationsAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_RUNTIME_INVISIBLE_ANNOTATIONS); + private final List elements; public UnboundRuntimeInvisibleAnnotationsAttribute(List elements) { @@ -566,11 +785,19 @@ public UnboundRuntimeInvisibleAnnotationsAttribute(List elements) { public List annotations() { return elements; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundRuntimeVisibleParameterAnnotationsAttribute extends UnboundAttribute implements RuntimeVisibleParameterAnnotationsAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS); + private final List> elements; public UnboundRuntimeVisibleParameterAnnotationsAttribute(List> elements) { @@ -588,11 +815,19 @@ public UnboundRuntimeVisibleParameterAnnotationsAttribute(List> public List> parameterAnnotations() { return elements; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundRuntimeInvisibleParameterAnnotationsAttribute extends UnboundAttribute implements RuntimeInvisibleParameterAnnotationsAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS); + private final List> elements; public UnboundRuntimeInvisibleParameterAnnotationsAttribute(List> elements) { @@ -610,11 +845,19 @@ public UnboundRuntimeInvisibleParameterAnnotationsAttribute(List> parameterAnnotations() { return elements; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundRuntimeVisibleTypeAnnotationsAttribute extends UnboundAttribute implements RuntimeVisibleTypeAnnotationsAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_RUNTIME_VISIBLE_TYPE_ANNOTATIONS); + private final List elements; public UnboundRuntimeVisibleTypeAnnotationsAttribute(List elements) { @@ -626,11 +869,19 @@ public UnboundRuntimeVisibleTypeAnnotationsAttribute(List elemen public List annotations() { return elements; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public static final class UnboundRuntimeInvisibleTypeAnnotationsAttribute extends UnboundAttribute implements RuntimeInvisibleTypeAnnotationsAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_RUNTIME_INVISIBLE_TYPE_ANNOTATIONS); + private final List elements; public UnboundRuntimeInvisibleTypeAnnotationsAttribute(List elements) { @@ -642,6 +893,11 @@ public UnboundRuntimeInvisibleTypeAnnotationsAttribute(List elem public List annotations() { return elements; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public record UnboundCharacterRangeInfo(int startPc, int endPc, @@ -765,6 +1021,9 @@ public record TypePathComponentImpl(TypeAnnotation.TypePathComponent.Kind typePa implements TypeAnnotation.TypePathComponent {} public static final class UnboundModuleAttribute extends UnboundAttribute implements ModuleAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_MODULE); + private final ModuleEntry moduleName; private final int moduleFlags; private final Utf8Entry moduleVersion; @@ -833,6 +1092,11 @@ public List uses() { public List provides() { return provides; } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } public abstract static non-sealed class AdHocAttribute> @@ -857,6 +1121,9 @@ public void writeTo(BufWriterImpl b) { public static final class EmptyBootstrapAttribute extends UnboundAttribute implements BootstrapMethodsAttribute { + + private static final Utf8Entry NAME = TemporaryConstantPool.INSTANCE.utf8Entry(Attributes.NAME_BOOTSTRAP_METHODS); + public EmptyBootstrapAttribute() { super(Attributes.bootstrapMethods()); } @@ -870,5 +1137,10 @@ public int bootstrapMethodsSize() { public List bootstrapMethods() { return List.of(); } + + @Override + public Utf8Entry attributeName() { + return NAME; + } } } diff --git a/src/java.base/share/classes/jdk/internal/classfile/impl/Util.java b/src/java.base/share/classes/jdk/internal/classfile/impl/Util.java index b8d031fd3e2..20961600d85 100644 --- a/src/java.base/share/classes/jdk/internal/classfile/impl/Util.java +++ b/src/java.base/share/classes/jdk/internal/classfile/impl/Util.java @@ -281,6 +281,11 @@ public void writeBody(BufWriterImpl b) { b.writeBytes(bytecode.array(), 0, bytecode.length()); b.writeU2U2(0, 0);//exception handlers & attributes } + + @Override + public Utf8Entry attributeName() { + return cp.utf8Entry(Attributes.NAME_CODE); + } })))); ClassPrinter.toYaml(clm.methods().get(0).code().get(), ClassPrinter.Verbosity.TRACE_ALL, dump); } catch (Error | Exception _) { diff --git a/src/java.base/share/classes/jdk/internal/classfile/impl/verifier/ParserVerifier.java b/src/java.base/share/classes/jdk/internal/classfile/impl/verifier/ParserVerifier.java index faccf93d247..169bc1018da 100644 --- a/src/java.base/share/classes/jdk/internal/classfile/impl/verifier/ParserVerifier.java +++ b/src/java.base/share/classes/jdk/internal/classfile/impl/verifier/ParserVerifier.java @@ -176,8 +176,8 @@ private void verifyAttributes(ClassFileElement cfe, List errors) { if (cfe instanceof AttributedElement ae) { var attrNames = new HashSet(); for (var a : ae.attributes()) { - if (!a.attributeMapper().allowMultiple() && !attrNames.add(a.attributeName())) { - errors.add(new VerifyError("Multiple %s attributes in %s".formatted(a.attributeName(), toString(ae)))); + if (!a.attributeMapper().allowMultiple() && !attrNames.add(a.attributeName().stringValue())) { + errors.add(new VerifyError("Multiple %s attributes in %s".formatted(a.attributeName().stringValue(), toString(ae)))); } verifyAttribute(ae, a, errors); } @@ -333,7 +333,7 @@ private void verifyAttribute(AttributedElement ae, Attribute a, List= 0 && size != ((BoundAttribute)a).payloadLen()) { - errors.add(new VerifyError("Wrong %s attribute length in %s".formatted(a.attributeName(), toString(ae)))); + errors.add(new VerifyError("Wrong %s attribute length in %s".formatted(a.attributeName().stringValue(), toString(ae)))); } } diff --git a/src/java.base/share/classes/jdk/internal/javac/PreviewFeature.java b/src/java.base/share/classes/jdk/internal/javac/PreviewFeature.java index e9ec19e68ae..674aa3caca3 100644 --- a/src/java.base/share/classes/jdk/internal/javac/PreviewFeature.java +++ b/src/java.base/share/classes/jdk/internal/javac/PreviewFeature.java @@ -84,7 +84,6 @@ public enum Feature { SCOPED_VALUES, @JEP(number=480, title="Structured Concurrency", status="Third Preview") STRUCTURED_CONCURRENCY, - @JEP(number=466, title="ClassFile API", status="Second Preview") CLASSFILE_API, STREAM_GATHERERS, @JEP(number=494, title="Module Import Declarations", status="Second Preview") diff --git a/src/java.base/share/classes/jdk/internal/loader/BootLoader.java b/src/java.base/share/classes/jdk/internal/loader/BootLoader.java index 98ff60a7309..c845146a838 100644 --- a/src/java.base/share/classes/jdk/internal/loader/BootLoader.java +++ b/src/java.base/share/classes/jdk/internal/loader/BootLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * 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,8 +32,6 @@ import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Arrays; import java.util.Enumeration; import java.util.concurrent.ConcurrentHashMap; @@ -143,18 +141,8 @@ public static Class loadClass(Module module, String name) { /** * Loads a native library from the system library path. */ - @SuppressWarnings("removal") public static void loadLibrary(String name) { - if (System.getSecurityManager() == null) { - BootLoader.getNativeLibraries().loadLibrary(name); - } else { - AccessController.doPrivileged(new java.security.PrivilegedAction<>() { - public Void run() { - BootLoader.getNativeLibraries().loadLibrary(name); - return null; - } - }); - } + getNativeLibraries().loadLibrary(name); } /** @@ -294,38 +282,28 @@ private static Module findModule(String location) { /** * Returns URL if the given location is a regular file path. */ - @SuppressWarnings("removal") private static URL toFileURL(String location) { - return AccessController.doPrivileged(new PrivilegedAction<>() { - public URL run() { - Path path = Path.of(location); - if (Files.isRegularFile(path)) { - try { - return path.toUri().toURL(); - } catch (MalformedURLException e) {} - } - return null; - } - }); + Path path = Path.of(location); + if (Files.isRegularFile(path)) { + try { + return path.toUri().toURL(); + } catch (MalformedURLException e) {} + } + return null; } /** * Returns the Manifest if the given location is a JAR file * containing a manifest. */ - @SuppressWarnings("removal") private static Manifest getManifest(String location) { - return AccessController.doPrivileged(new PrivilegedAction<>() { - public Manifest run() { - Path jar = Path.of(location); - try (InputStream in = Files.newInputStream(jar); - JarInputStream jis = new JarInputStream(in, false)) { - return jis.getManifest(); - } catch (IOException e) { - return null; - } - } - }); + Path jar = Path.of(location); + try (InputStream in = Files.newInputStream(jar); + JarInputStream jis = new JarInputStream(in, false)) { + return jis.getManifest(); + } catch (IOException e) { + return null; + } } } diff --git a/src/java.base/share/classes/jdk/internal/loader/BuiltinClassLoader.java b/src/java.base/share/classes/jdk/internal/loader/BuiltinClassLoader.java index 9cba132f3e3..52c5276b506 100644 --- a/src/java.base/share/classes/jdk/internal/loader/BuiltinClassLoader.java +++ b/src/java.base/share/classes/jdk/internal/loader/BuiltinClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -46,14 +46,8 @@ import java.nio.file.Files; //OpenJ9-shared_classes_misc import java.nio.file.Path; //OpenJ9-shared_classes_misc import java.nio.file.Paths; //OpenJ9-shared_classes_misc -import java.security.AccessControlException; -import java.security.AccessController; import java.security.CodeSigner; import java.security.CodeSource; -import java.security.PermissionCollection; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.security.SecureClassLoader; import java.util.ArrayList; import java.util.Collections; @@ -76,7 +70,6 @@ import jdk.internal.module.ModulePatcher.PatchedModuleReader; import jdk.internal.module.Resources; import jdk.internal.vm.annotation.Stable; -import sun.security.util.LazyCodeSourcePermissionCollection; /** @@ -246,11 +239,7 @@ private static boolean isSharedClassesEnabled() { //OpenJ9-shared_clas * when jdk.internal.lambda.dumpProxyClasses is enabled. //OpenJ9-shared_classes_misc * More details are at https://github.com/eclipse-openj9/openj9/issues/3399 //OpenJ9-shared_classes_misc */ //OpenJ9-shared_classes_misc - return AccessController.doPrivileged(new PrivilegedAction() { //OpenJ9-shared_classes_misc - public Boolean run() { //OpenJ9-shared_classes_misc - return Boolean.getBoolean("com.ibm.oti.shared.enabled"); //OpenJ9-shared_classes_misc - } //OpenJ9-shared_classes_misc - }); //OpenJ9-shared_classes_misc + return Boolean.getBoolean("com.ibm.oti.shared.enabled"); //OpenJ9-shared_classes_misc } //OpenJ9-shared_classes_misc /* //OpenJ9-shared_classes_misc @@ -262,11 +251,7 @@ private static void setJimageURL() { //OpenJ9-shared_classes_misc * when jdk.internal.lambda.dumpProxyClasses is enabled. //OpenJ9-shared_classes_misc * More details are at https://github.com/eclipse-openj9/openj9/issues/3399 //OpenJ9-shared_classes_misc */ //OpenJ9-shared_classes_misc - String javaHome = AccessController.doPrivileged( new PrivilegedAction() { //OpenJ9-shared_classes_misc - public String run() { //OpenJ9-shared_classes_misc - return System.getProperty("java.home"); //OpenJ9-shared_classes_misc - } //OpenJ9-shared_classes_misc - }); //OpenJ9-shared_classes_misc + String javaHome = System.getProperty("java.home"); //OpenJ9-shared_classes_misc Path p = Paths.get(javaHome, "lib", "modules"); //OpenJ9-shared_classes_misc if (Files.isRegularFile(p)) { //OpenJ9-shared_classes_misc try { //OpenJ9-shared_classes_misc @@ -464,31 +449,30 @@ public URL findResource(String mn, String name) throws IOException { url = findResourceOnClassPath(name); } - return checkURL(url); // check access before returning + return url; } /** * Returns an input stream to a resource of the given name in a module * defined to this class loader. */ - @SuppressWarnings("removal") public InputStream findResourceAsStream(String mn, String name) throws IOException { - // Need URL to resource when running with a security manager so that - // the right permission check is done. - if (System.getSecurityManager() != null || mn == null) { - URL url = findResource(mn, name); - return (url != null) ? url.openStream() : null; - } - - // find in module defined to this loader, no security manager - ModuleReference mref = nameToModule.get(mn); - if (mref != null) { - return moduleReaderFor(mref).open(name).orElse(null); + InputStream in = null; + if (mn != null) { + // find in module defined to this loader + ModuleReference mref = nameToModule.get(mn); + if (mref != null) { + in = moduleReaderFor(mref).open(name).orElse(null); + } } else { - return null; + URL url = findResourceOnClassPath(name); + if (url != null) { + in = url.openStream(); + } } + return in; } /** @@ -525,7 +509,7 @@ public URL findResource(String name) { if (!urls.isEmpty()) { URL url = urls.get(0); if (url != null) { - return checkURL(url); // check access before returning + return url; } } } catch (IOException ioe) { @@ -535,8 +519,7 @@ public URL findResource(String name) { } // search class path - URL url = findResourceOnClassPath(name); - return checkURL(url); + return findResourceOnClassPath(name); } /** @@ -566,7 +549,6 @@ public Enumeration findResources(String name) throws IOException { } else { // not in a package of a module defined to this loader for (URL url : findMiscResource(name)) { - url = checkURL(url); if (url != null) { checked.add(url); } @@ -589,7 +571,7 @@ private boolean hasNext() { } else { // need to check each URL while (e.hasMoreElements() && next == null) { - next = checkURL(e.nextElement()); + next = e.nextElement(); } return next != null; } @@ -619,7 +601,6 @@ public URL nextElement() { * * The cache used by this method avoids repeated searching of all modules. */ - @SuppressWarnings("removal") private List findMiscResource(String name) throws IOException { SoftReference>> ref = this.resourceCache; Map> map = (ref != null) ? ref.get() : null; @@ -636,38 +617,25 @@ private List findMiscResource(String name) throws IOException { } // search all modules for the resource - List urls; - try { - urls = AccessController.doPrivileged( - new PrivilegedExceptionAction<>() { - @Override - public List run() throws IOException { - List result = null; - for (ModuleReference mref : nameToModule.values()) { - URI u = moduleReaderFor(mref).find(name).orElse(null); - if (u != null) { - try { - if (result == null) - result = new ArrayList<>(); - result.add(u.toURL()); - } catch (MalformedURLException | - IllegalArgumentException e) { - } - } - } - return (result != null) ? result : Collections.emptyList(); - } - }); - } catch (PrivilegedActionException pae) { - throw (IOException) pae.getCause(); + List urls = null; + for (ModuleReference mref : nameToModule.values()) { + URI u = moduleReaderFor(mref).find(name).orElse(null); + if (u != null) { + try { + if (urls == null) + urls = new ArrayList<>(); + urls.add(u.toURL()); + } catch (MalformedURLException | IllegalArgumentException e) { + } + } + } + if (urls == null) { + urls = List.of(); } // only cache resources after VM is fully initialized if (map != null) { map.putIfAbsent(name, urls); - } else { - if (urls == null) - urls = Collections.emptyList(); } return urls; @@ -676,23 +644,8 @@ public List run() throws IOException { /** * Returns the URL to a resource in a module or {@code null} if not found. */ - @SuppressWarnings("removal") private URL findResource(ModuleReference mref, String name) throws IOException { - URI u; - if (System.getSecurityManager() == null) { - u = moduleReaderFor(mref).find(name).orElse(null); - } else { - try { - u = AccessController.doPrivileged(new PrivilegedExceptionAction<> () { - @Override - public URI run() throws IOException { - return moduleReaderFor(mref).find(name).orElse(null); - } - }); - } catch (PrivilegedActionException pae) { - throw (IOException) pae.getCause(); - } - } + URI u = moduleReaderFor(mref).find(name).orElse(null); if (u != null) { try { return u.toURL(); @@ -701,30 +654,12 @@ public URI run() throws IOException { return null; } - /** - * Returns the URL to a resource in a module. Returns {@code null} if not found - * or an I/O error occurs. - */ - private URL findResourceOrNull(ModuleReference mref, String name) { - try { - return findResource(mref, name); - } catch (IOException ignore) { - return null; - } - } - /** * Returns a URL to a resource on the class path. */ - @SuppressWarnings("removal") private URL findResourceOnClassPath(String name) { if (hasClassPath()) { - if (System.getSecurityManager() == null) { - return ucp.findResource(name, false); - } else { - PrivilegedAction pa = () -> ucp.findResource(name, false); - return AccessController.doPrivileged(pa); - } + return ucp.findResource(name, false); } else { // no class path return null; @@ -734,16 +669,9 @@ private URL findResourceOnClassPath(String name) { /** * Returns the URLs of all resources of the given name on the class path. */ - @SuppressWarnings("removal") private Enumeration findResourcesOnClassPath(String name) { if (hasClassPath()) { - if (System.getSecurityManager() == null) { - return ucp.findResources(name, false); - } else { - PrivilegedAction> pa; - pa = () -> ucp.findResources(name, false); - return AccessController.doPrivileged(pa); - } + return ucp.findResources(name, false); } else { // no class path return Collections.emptyEnumeration(); @@ -921,11 +849,9 @@ private LoadedModule findLoadedModule(String mn, String cn) { * * @return the resulting Class or {@code null} if not found */ - @SuppressWarnings("removal") private Class findClassInModuleOrNull(LoadedModule loadedModule, String cn) { Class c = null; //OpenJ9-shared_classes_misc - PrivilegedAction paModuleReaderFor = () -> moduleReaderFor(loadedModule.mref()); //OpenJ9-shared_classes_misc - ModuleReader reader = AccessController.doPrivileged(paModuleReaderFor); //OpenJ9-shared_classes_misc + ModuleReader reader = moduleReaderFor(loadedModule.mref()); //OpenJ9-shared_classes_misc if (!(reader instanceof PatchedModuleReader)) { //OpenJ9-shared_classes_misc c = findClassInSharedClassesCache(cn, loadedModule, false); //OpenJ9-shared_classes_misc } //OpenJ9-shared_classes_misc @@ -933,12 +859,7 @@ private Class findClassInModuleOrNull(LoadedModule loadedModule, String cn) { return c; //OpenJ9-shared_classes_misc } //OpenJ9-shared_classes_misc - if (System.getSecurityManager() == null) { - return defineClass(cn, loadedModule); - } else { - PrivilegedAction> pa = () -> defineClass(cn, loadedModule); - return AccessController.doPrivileged(pa); - } + return defineClass(cn, loadedModule); } /** @@ -946,7 +867,6 @@ private Class findClassInModuleOrNull(LoadedModule loadedModule, String cn) { * * @return the resulting Class or {@code null} if not found */ - @SuppressWarnings("removal") private Class findClassOnClassPathOrNull(String cn) { Class c = findClassInSharedClassesCache(cn, null, true); //OpenJ9-shared_classes_misc if (null != c) { //OpenJ9-shared_classes_misc @@ -954,33 +874,15 @@ private Class findClassOnClassPathOrNull(String cn) { } //OpenJ9-shared_classes_misc String path = cn.replace('.', '/').concat(".class"); - if (System.getSecurityManager() == null) { - Resource res = ucp.getResource(path, false); - if (res != null) { - try { - return defineClass(cn, res); - } catch (IOException ioe) { - // TBD on how I/O errors should be propagated - } + Resource res = ucp.getResource(path, false); + if (res != null) { + try { + return defineClass(cn, res); + } catch (IOException ioe) { + // TBD on how I/O errors should be propagated } - return null; - } else { - // avoid use of lambda here - PrivilegedAction> pa = new PrivilegedAction<>() { - public Class run() { - Resource res = ucp.getResource(path, false); - if (res != null) { - try { - return defineClass(cn, res); - } catch (IOException ioe) { - // TBD on how I/O errors should be propagated - } - } - return null; - } - }; - return AccessController.doPrivileged(pa); } + return null; } /** //OpenJ9-shared_classes_misc @@ -1316,16 +1218,6 @@ private boolean isSealed(String pn, Manifest man) { return "true".equalsIgnoreCase(sealed); } - // -- permissions - - /** - * Returns the permissions for the given CodeSource. - */ - @Override - protected PermissionCollection getPermissions(CodeSource cs) { - return new LazyCodeSourcePermissionCollection(super.getPermissions(cs), cs); - } - // -- miscellaneous supporting methods /** @@ -1390,14 +1282,6 @@ private boolean isOpen(ModuleReference mref, String pn) { return false; } - /** - * Checks access to the given URL. We use URLClassPath for consistent - * checking with java.net.URLClassLoader. - */ - private static URL checkURL(URL url) { - return URLClassPath.checkURL(url); - } - // Called from VM only, during -Xshare:dump private void resetArchivedStates() { ucp = null; diff --git a/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java b/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java index ab4aa3fb907..1a61d4b1522 100644 --- a/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java +++ b/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,8 +29,6 @@ import java.net.URL; import java.nio.file.InvalidPathException; import java.nio.file.Path; -import java.security.CodeSource; -import java.security.PermissionCollection; import java.util.jar.Manifest; import jdk.internal.access.JavaLangAccess; @@ -170,31 +168,6 @@ private static class AppClassLoader extends BuiltinClassLoader { super("app", parent, ucp); } - @Override - protected Class loadClass(String cn, boolean resolve) - throws ClassNotFoundException - { - // for compatibility reasons, say where restricted package list has - // been updated to list API packages in the unnamed module. - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - int i = cn.lastIndexOf('.'); - if (i != -1) { - sm.checkPackageAccess(cn.substring(0, i)); - } - } - - return super.loadClass(cn, resolve); - } - - @Override - protected PermissionCollection getPermissions(CodeSource cs) { - PermissionCollection perms = super.getPermissions(cs); - perms.add(new RuntimePermission("exitVM")); - return perms; - } - /** * Called by the VM to support dynamic additions to the class path * @@ -207,6 +180,7 @@ void appendToClassPathForInstrumentation(String path) { /** * Called by the VM to support define package for AppCDS */ + @Override protected Package defineOrCheckPackage(String pn, Manifest man, URL url) { return super.defineOrCheckPackage(pn, man, url); } diff --git a/src/java.base/share/classes/jdk/internal/loader/Loader.java b/src/java.base/share/classes/jdk/internal/loader/Loader.java index fbd16467da7..c4f9023482d 100644 --- a/src/java.base/share/classes/jdk/internal/loader/Loader.java +++ b/src/java.base/share/classes/jdk/internal/loader/Loader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * 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,8 +25,6 @@ package jdk.internal.loader; -import java.io.File; -import java.io.FilePermission; import java.io.IOException; import java.lang.module.Configuration; import java.lang.module.ModuleDescriptor; @@ -37,15 +35,8 @@ import java.net.URI; import java.net.URL; import java.nio.ByteBuffer; -import java.security.AccessControlContext; -import java.security.AccessController; import java.security.CodeSigner; import java.security.CodeSource; -import java.security.Permission; -import java.security.PermissionCollection; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.security.SecureClassLoader; import java.util.ArrayList; import java.util.Collection; @@ -110,16 +101,11 @@ public final class Loader extends SecureClassLoader { private final Map moduleToReader = new ConcurrentHashMap<>(); - // ACC used when loading classes and resources - @SuppressWarnings("removal") - private final AccessControlContext acc; - /** * A module defined/loaded to a {@code Loader}. */ private static class LoadedModule { private final ModuleReference mref; - private final URL url; // may be null private final CodeSource cs; LoadedModule(ModuleReference mref) { @@ -130,13 +116,11 @@ private static class LoadedModule { } catch (MalformedURLException | IllegalArgumentException e) { } } this.mref = mref; - this.url = url; this.cs = new CodeSource(url, (CodeSigner[]) null); } ModuleReference mref() { return mref; } String name() { return mref.descriptor().name(); } - URL location() { return url; } CodeSource codeSource() { return cs; } } @@ -145,7 +129,6 @@ private static class LoadedModule { * Creates a {@code Loader} in a loader pool that loads classes/resources * from one module. */ - @SuppressWarnings("removal") public Loader(ResolvedModule resolvedModule, LoaderPool pool, ClassLoader parent) @@ -164,8 +147,6 @@ public Loader(ResolvedModule resolvedModule, LoadedModule lm = new LoadedModule(mref); descriptor.packages().forEach(pn -> localPackageToModule.put(pn, lm)); this.localPackageToModule = localPackageToModule; - - this.acc = AccessController.getContext(); } /** @@ -175,7 +156,6 @@ public Loader(ResolvedModule resolvedModule, * @throws IllegalArgumentException * If two or more modules have the same package */ - @SuppressWarnings("removal") public Loader(Collection modules, ClassLoader parent) { super(parent); @@ -197,8 +177,6 @@ public Loader(Collection modules, ClassLoader parent) { } this.nameToModule = nameToModule; this.localPackageToModule = localPackageToModule; - - this.acc = AccessController.getContext(); } /** @@ -326,7 +304,6 @@ public LoaderPool pool() { * Returns a URL to a resource of the given name in a module defined to * this class loader. */ - @SuppressWarnings("removal") @Override protected URL findResource(String mn, String name) throws IOException { ModuleReference mref = (mn != null) ? nameToModule.get(mn) : null; @@ -335,41 +312,12 @@ protected URL findResource(String mn, String name) throws IOException { // locate resource URL url = null; - try { - url = AccessController.doPrivileged( - new PrivilegedExceptionAction() { - @Override - public URL run() throws IOException { - Optional ouri = moduleReaderFor(mref).find(name); - if (ouri.isPresent()) { - try { - return ouri.get().toURL(); - } catch (MalformedURLException | - IllegalArgumentException e) { } - } - return null; - } - }); - } catch (PrivilegedActionException pae) { - throw (IOException) pae.getCause(); - } - - // check access with permissions restricted by ACC - if (url != null && System.getSecurityManager() != null) { + Optional ouri = moduleReaderFor(mref).find(name); + if (ouri.isPresent()) { try { - URL urlToCheck = url; - url = AccessController.doPrivileged( - new PrivilegedExceptionAction() { - @Override - public URL run() throws IOException { - return URLClassPath.checkURL(urlToCheck); - } - }, acc); - } catch (PrivilegedActionException pae) { - url = null; - } + url = ouri.get().toURL(); + } catch (MalformedURLException | IllegalArgumentException e) { } } - return url; } @@ -525,15 +473,6 @@ protected Class findClass(String mn, String cn) { protected Class loadClass(String cn, boolean resolve) throws ClassNotFoundException { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - String pn = packageName(cn); - if (!pn.isEmpty()) { - sm.checkPackageAccess(pn); - } - } - synchronized (getClassLoadingLock(cn)) { // check if already loaded Class c = findLoadedClass(cn); @@ -584,19 +523,7 @@ protected Class loadClass(String cn, boolean resolve) * * @return the resulting Class or {@code null} if not found */ - @SuppressWarnings("removal") private Class findClassInModuleOrNull(LoadedModule loadedModule, String cn) { - PrivilegedAction> pa = () -> defineClass(cn, loadedModule); - return AccessController.doPrivileged(pa, acc); - } - - /** - * Defines the given binary class name to the VM, loading the class - * bytes from the given module. - * - * @return the resulting Class or {@code null} if an I/O error occurs - */ - private Class defineClass(String cn, LoadedModule loadedModule) { ModuleReader reader = moduleReaderFor(loadedModule.mref()); try { @@ -620,40 +547,6 @@ private Class defineClass(String cn, LoadedModule loadedModule) { } } - - // -- permissions - - /** - * Returns the permissions for the given CodeSource. - */ - @Override - protected PermissionCollection getPermissions(CodeSource cs) { - PermissionCollection perms = super.getPermissions(cs); - - URL url = cs.getLocation(); - if (url == null) - return perms; - - // add the permission to access the resource - try { - Permission p = url.openConnection().getPermission(); - if (p != null) { - // for directories then need recursive access - if (p instanceof FilePermission) { - String path = p.getName(); - if (path.endsWith(File.separator)) { - path += "-"; - p = new FilePermission(path, "read"); - } - } - perms.add(p); - } - } catch (IOException ioe) { } - - return perms; - } - - // -- miscellaneous supporting methods /** diff --git a/src/java.base/share/classes/jdk/internal/loader/NativeLibraries.java b/src/java.base/share/classes/jdk/internal/loader/NativeLibraries.java index 18cb37bb5c7..fe58eb8a562 100644 --- a/src/java.base/share/classes/jdk/internal/loader/NativeLibraries.java +++ b/src/java.base/share/classes/jdk/internal/loader/NativeLibraries.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. * 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,28 +130,20 @@ public long find(String name) { * @param file the path of the native library * @throws UnsatisfiedLinkError if any error in loading the native library */ - @SuppressWarnings("removal") public NativeLibrary loadLibrary(Class fromClass, File file) { // Check to see if we're attempting to access a static library String name = findBuiltinLib(file.getName()); boolean isBuiltin = (name != null); if (!isBuiltin) { - name = AccessController.doPrivileged(new PrivilegedAction<>() { - public String run() { - try { - if (!loadLibraryOnlyIfPresentInitialized) { - initLoadLibraryOnlyIfPresent(); - } - if (loadLibraryOnlyIfPresent && !file.exists()) { - return null; - } - return file.getCanonicalPath(); - } catch (IOException e) { - return null; - } - } - }); - if (name == null) { + try { + if (!loadLibraryOnlyIfPresentInitialized) { + initLoadLibraryOnlyIfPresent(); + } + if (loadLibraryOnlyIfPresent && !file.exists()) { + return null; + } + name = file.getCanonicalPath(); + } catch (IOException e) { return null; } } diff --git a/src/java.base/share/classes/jdk/internal/loader/RawNativeLibraries.java b/src/java.base/share/classes/jdk/internal/loader/RawNativeLibraries.java index 35ed4701c99..fa4c1390c1a 100644 --- a/src/java.base/share/classes/jdk/internal/loader/RawNativeLibraries.java +++ b/src/java.base/share/classes/jdk/internal/loader/RawNativeLibraries.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,8 +29,6 @@ import java.io.IOException; import java.lang.invoke.MethodHandles; import java.nio.file.Path; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -78,18 +76,11 @@ public static RawNativeLibraries newInstance(MethodHandles.Lookup trustedCaller) * * @param path the path of the native library */ - @SuppressWarnings("removal") public NativeLibrary load(Path path) { - String name = AccessController.doPrivileged(new PrivilegedAction<>() { - public String run() { - try { - return path.toRealPath().toString(); - } catch (IOException e) { - return null; - } - } - }); - if (name == null) { + String name; + try { + name = path.toRealPath().toString(); + } catch (IOException e) { return null; } return load(name); diff --git a/src/java.base/share/classes/jdk/internal/misc/InternalLock.java b/src/java.base/share/classes/jdk/internal/misc/InternalLock.java deleted file mode 100644 index 822b64f74ca..00000000000 --- a/src/java.base/share/classes/jdk/internal/misc/InternalLock.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.internal.misc; - -import java.util.concurrent.locks.ReentrantLock; - -/** - * A reentrant mutual exclusion lock for internal use. The lock does not - * implement {@link java.util.concurrent.locks.Lock} or extend {@link - * java.util.concurrent.locks.ReentrantLock} so that it can be distinguished - * from lock objects accessible to subclasses of {@link java.io.Reader} and - * {@link java.io.Writer} (it is possible to create a Reader that uses a - * lock object of type ReentrantLock for example). - */ -public class InternalLock { - private static final boolean CAN_USE_INTERNAL_LOCK; - static { - String s = System.getProperty("jdk.io.useMonitors"); - if (s != null && s.equals("false")) { - CAN_USE_INTERNAL_LOCK = true; - } else { - CAN_USE_INTERNAL_LOCK = false; - } - } - - private final ReentrantLock lock; - - private InternalLock() { - this.lock = new ReentrantLock(); - } - - /** - * Returns a new InternalLock or null. - */ - public static InternalLock newLockOrNull() { - return (CAN_USE_INTERNAL_LOCK) ? new InternalLock() : null; - } - - /** - * Returns a new InternalLock or the given object. - */ - public static Object newLockOr(Object obj) { - return (CAN_USE_INTERNAL_LOCK) ? new InternalLock() : obj; - } - - public boolean tryLock() { - return lock.tryLock(); - } - - public void lock() { - lock.lock(); - } - - public void unlock() { - lock.unlock(); - } - - public boolean isHeldByCurrentThread() { - return lock.isHeldByCurrentThread(); - } -} diff --git a/src/java.base/share/classes/jdk/internal/misc/Unsafe.java b/src/java.base/share/classes/jdk/internal/misc/Unsafe.java index b9681362a12..4870de532bb 100644 --- a/src/java.base/share/classes/jdk/internal/misc/Unsafe.java +++ b/src/java.base/share/classes/jdk/internal/misc/Unsafe.java @@ -57,6 +57,11 @@ public final class Unsafe { private static native void registerNatives(); static { + runtimeSetup(); + } + + // Called from JVM when loading an AOT cache + private static void runtimeSetup() { registerNatives(); } diff --git a/src/java.base/share/classes/jdk/internal/module/ModuleReferences.java b/src/java.base/share/classes/jdk/internal/module/ModuleReferences.java index a5ad79eb7c6..c87c039c133 100644 --- a/src/java.base/share/classes/jdk/internal/module/ModuleReferences.java +++ b/src/java.base/share/classes/jdk/internal/module/ModuleReferences.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -370,14 +370,6 @@ static class ExplodedModuleReader implements ModuleReader { ExplodedModuleReader(Path dir) { this.dir = dir; - - // when running with a security manager then check that the caller - // has access to the directory. - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - boolean unused = Files.isDirectory(dir); - } } /** diff --git a/src/java.base/share/classes/jdk/internal/module/Modules.java b/src/java.base/share/classes/jdk/internal/module/Modules.java index 11ca2d5e521..3c3d148e196 100644 --- a/src/java.base/share/classes/jdk/internal/module/Modules.java +++ b/src/java.base/share/classes/jdk/internal/module/Modules.java @@ -32,8 +32,6 @@ import java.lang.module.ModuleReference; import java.lang.module.ResolvedModule; import java.net.URI; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Collection; import java.util.List; import java.util.Map; @@ -155,10 +153,7 @@ public static void addUses(Module m, Class service) { public static void addProvides(Module m, Class service, Class impl) { ModuleLayer layer = m.getLayer(); - PrivilegedAction pa = m::getClassLoader; - @SuppressWarnings("removal") - ClassLoader loader = AccessController.doPrivileged(pa); - + ClassLoader loader = m.getClassLoader(); ClassLoader platformClassLoader = ClassLoaders.platformClassLoader(); if (layer == null || loader == null || loader == platformClassLoader) { // update ClassLoader catalog diff --git a/src/java.base/share/classes/jdk/internal/module/SystemModuleFinders.java b/src/java.base/share/classes/jdk/internal/module/SystemModuleFinders.java index 74af7570d57..c520e6e636a 100644 --- a/src/java.base/share/classes/jdk/internal/module/SystemModuleFinders.java +++ b/src/java.base/share/classes/jdk/internal/module/SystemModuleFinders.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,8 +38,6 @@ import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayDeque; import java.util.Collections; import java.util.Deque; @@ -208,21 +206,7 @@ public static ModuleFinder ofSystem() { Path dir = Path.of(home, "modules"); if (!Files.isDirectory(dir)) throw new InternalError("Unable to detect the run-time image"); - ModuleFinder f = ModulePath.of(ModuleBootstrap.patcher(), dir); - return new ModuleFinder() { - @SuppressWarnings("removal") - @Override - public Optional find(String name) { - PrivilegedAction> pa = () -> f.find(name); - return AccessController.doPrivileged(pa); - } - @SuppressWarnings("removal") - @Override - public Set findAll() { - PrivilegedAction> pa = f::findAll; - return AccessController.doPrivileged(pa); - } - }; + return ModulePath.of(ModuleBootstrap.patcher(), dir); } /** @@ -314,7 +298,7 @@ static ModuleReference toModuleReference(ModuleDescriptor descriptor, Supplier readerSupplier = new Supplier<>() { @Override public ModuleReader get() { - return new SystemModuleReader(mn, uri); + return new SystemModuleReader(mn); } }; @@ -377,9 +361,7 @@ public byte[] generate(String algorithm) { } /** - * Holder class for the ImageReader - * - * @apiNote This class must be loaded before a security manager is set. + * Holder class for the ImageReader. */ private static class SystemImage { static final ImageReader READER = ImageReaderFactory.getImageReader(); @@ -396,25 +378,7 @@ private static class SystemModuleReader implements ModuleReader { private final String module; private volatile boolean closed; - /** - * If there is a security manager set then check permission to - * connect to the run-time image. - */ - private static void checkPermissionToConnect(URI uri) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - try { - URLConnection uc = uri.toURL().openConnection(); - sm.checkPermission(uc.getPermission()); - } catch (IOException ioe) { - throw new UncheckedIOException(ioe); - } - } - } - - SystemModuleReader(String module, URI uri) { - checkPermissionToConnect(uri); + SystemModuleReader(String module) { this.module = module; } diff --git a/src/java.base/share/classes/module-info.java b/src/java.base/share/classes/module-info.java index 1d6935b48ca..ff8df85f2d2 100644 --- a/src/java.base/share/classes/module-info.java +++ b/src/java.base/share/classes/module-info.java @@ -153,6 +153,8 @@ java.security.sasl; exports jdk.crypto.jniprovider to jdk.crypto.ec; + exports jdk.internal to + jdk.incubator.vector; // Note: all modules in the exported list participate in preview features // and therefore if they use preview features they do not need to be // compiled with "--enable-preview". @@ -329,7 +331,6 @@ java.desktop; exports sun.reflect.misc to java.desktop, - java.datatransfer, java.management, java.management.rmi, java.rmi, diff --git a/src/java.base/share/classes/sun/net/ftp/FtpClient.java b/src/java.base/share/classes/sun/net/ftp/FtpClient.java index da0cffd3f20..970d095242c 100644 --- a/src/java.base/share/classes/sun/net/ftp/FtpClient.java +++ b/src/java.base/share/classes/sun/net/ftp/FtpClient.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -234,8 +234,6 @@ public static FtpClient create(String dest) throws FtpProtocolException, IOExcep * @param dest the address of the destination server * @return this FtpClient * @throws IOException if connection failed. - * @throws SecurityException if there is a SecurityManager installed and it - * denied the authorization to connect to the destination. * @throws FtpProtocolException */ public abstract FtpClient connect(SocketAddress dest) throws FtpProtocolException, IOException; @@ -247,8 +245,6 @@ public static FtpClient create(String dest) throws FtpProtocolException, IOExcep * @param timeout the value, in milliseconds, to use as a connection timeout * @return this FtpClient * @throws IOException if connection failed. - * @throws SecurityException if there is a SecurityManager installed and it - * denied the authorization to connect to the destination. * @throws FtpProtocolException */ public abstract FtpClient connect(SocketAddress dest, int timeout) throws FtpProtocolException, IOException; diff --git a/src/java.base/share/classes/sun/net/ftp/FtpClientProvider.java b/src/java.base/share/classes/sun/net/ftp/FtpClientProvider.java index ad5d092aab1..94136d85f1d 100644 --- a/src/java.base/share/classes/sun/net/ftp/FtpClientProvider.java +++ b/src/java.base/share/classes/sun/net/ftp/FtpClientProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2024, Oracle and/or its affiliates. All rights reserved. * 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,8 +24,6 @@ */ package sun.net.ftp; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ServiceConfigurationError; //import java.util.ServiceLoader; @@ -50,16 +48,8 @@ public abstract class FtpClientProvider { /** * Initializes a new instance of this class. - * - * @throws SecurityException if a security manager is installed and it denies - * {@link RuntimePermission}{@code ("ftpClientProvider")} */ protected FtpClientProvider() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(new RuntimePermission("ftpClientProvider")); - } } private static boolean loadProviderFromProperty() { @@ -74,8 +64,7 @@ private static boolean loadProviderFromProperty() { return true; } catch (ClassNotFoundException | IllegalAccessException | - InstantiationException | - SecurityException x) { + InstantiationException x) { throw new ServiceConfigurationError(x.toString()); } } @@ -135,26 +124,19 @@ private static boolean loadProviderAsService() { * * @return The system-wide default FtpClientProvider */ - @SuppressWarnings("removal") public static FtpClientProvider provider() { synchronized (lock) { if (provider != null) { return provider; } - return (FtpClientProvider) AccessController.doPrivileged( - new PrivilegedAction() { - - public Object run() { - if (loadProviderFromProperty()) { - return provider; - } - if (loadProviderAsService()) { - return provider; - } - provider = new sun.net.ftp.impl.DefaultFtpClientProvider(); - return provider; - } - }); + if (loadProviderFromProperty()) { + return provider; + } + if (loadProviderAsService()) { + return provider; + } + provider = new sun.net.ftp.impl.DefaultFtpClientProvider(); + return provider; } } } diff --git a/src/java.base/share/classes/sun/net/ftp/impl/FtpClient.java b/src/java.base/share/classes/sun/net/ftp/impl/FtpClient.java index 8b6dd9c5ec7..bfc10028ae0 100644 --- a/src/java.base/share/classes/sun/net/ftp/impl/FtpClient.java +++ b/src/java.base/share/classes/sun/net/ftp/impl/FtpClient.java @@ -44,9 +44,6 @@ import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedExceptionAction; import java.text.DateFormat; import java.time.ZoneOffset; import java.time.ZonedDateTime; @@ -133,31 +130,17 @@ public class FtpClient extends sun.net.ftp.FtpClient { private DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, java.util.Locale.US); private static final boolean acceptPasvAddressVal; static { - final int vals[] = {0, 0}; - final String acceptPasvAddress[] = {null}; - @SuppressWarnings("removal") - final String enc = AccessController.doPrivileged( - new PrivilegedAction() { - public String run() { - acceptPasvAddress[0] = System.getProperty("jdk.net.ftp.trustPasvAddress", "false"); - vals[0] = Integer.getInteger("sun.net.client.defaultReadTimeout", 300_000).intValue(); - vals[1] = Integer.getInteger("sun.net.client.defaultConnectTimeout", 300_000).intValue(); - return System.getProperty("file.encoding", "ISO8859_1"); - } - }); - if (vals[0] == 0) { + defaultSoTimeout = Integer.getInteger("sun.net.client.defaultReadTimeout", 300_000).intValue(); + if (defaultSoTimeout == 0) { defaultSoTimeout = -1; - } else { - defaultSoTimeout = vals[0]; } - if (vals[1] == 0) { + defaultConnectTimeout = Integer.getInteger("sun.net.client.defaultConnectTimeout", 300_000).intValue(); + if (defaultConnectTimeout == 0) { defaultConnectTimeout = -1; - } else { - defaultConnectTimeout = vals[1]; } - encoding = enc; + encoding = System.getProperty("file.encoding", "ISO8859_1"); try { if (!isASCIISuperset(encoding)) { encoding = "ISO8859_1"; @@ -171,7 +154,7 @@ public String run() { patterns[i] = Pattern.compile(patStrings[i]); } - acceptPasvAddressVal = Boolean.parseBoolean(acceptPasvAddress[0]); + acceptPasvAddressVal = Boolean.getBoolean("jdk.net.ftp.trustPasvAddress"); } /** @@ -662,10 +645,7 @@ private Socket openPassiveDataConnection(String cmd) throws sun.net.ftp.FtpProto Socket s; if (proxy != null) { if (proxy.type() == Proxy.Type.SOCKS) { - PrivilegedAction pa = () -> new Socket(proxy); - @SuppressWarnings("removal") - var tmp = AccessController.doPrivileged(pa); - s = tmp; + s = new Socket(proxy); } else { s = new Socket(Proxy.NO_PROXY); } @@ -673,9 +653,7 @@ private Socket openPassiveDataConnection(String cmd) throws sun.net.ftp.FtpProto s = new Socket(); } - PrivilegedAction pa = () -> server.getLocalAddress(); - @SuppressWarnings("removal") - InetAddress serverAddress = AccessController.doPrivileged(pa); + InetAddress serverAddress = server.getLocalAddress(); // Bind the socket to the same address as the control channel. This // is needed in case of multi-homed systems. @@ -761,11 +739,8 @@ private InetSocketAddress validatePasvAddress(int port, String s, InetAddress ad } private static InetAddress privilegedLocalHost() throws FtpProtocolException { - PrivilegedExceptionAction action = InetAddress::getLocalHost; try { - @SuppressWarnings("removal") - var tmp = AccessController.doPrivileged(action); - return tmp; + return InetAddress.getLocalHost(); } catch (Exception e) { var ftpEx = new FtpProtocolException(ERROR_MSG); ftpEx.initCause(e); @@ -774,11 +749,8 @@ private static InetAddress privilegedLocalHost() throws FtpProtocolException { } private static InetAddress[] privilegedGetAllByName(String hostName) throws FtpProtocolException { - PrivilegedExceptionAction pAction = () -> InetAddress.getAllByName(hostName); try { - @SuppressWarnings("removal") - var tmp =AccessController.doPrivileged(pAction); - return tmp; + return InetAddress.getAllByName(hostName); } catch (Exception e) { var ftpEx = new FtpProtocolException(ERROR_MSG); ftpEx.initCause(e); @@ -1021,10 +993,7 @@ private Socket doConnect(InetSocketAddress dest, int timeout) throws IOException Socket s; if (proxy != null) { if (proxy.type() == Proxy.Type.SOCKS) { - PrivilegedAction pa = () -> new Socket(proxy); - @SuppressWarnings("removal") - var tmp = AccessController.doPrivileged(pa); - s = tmp; + s = new Socket(proxy); } else { s = new Socket(Proxy.NO_PROXY); } diff --git a/src/java.base/share/classes/sun/net/smtp/SmtpClient.java b/src/java.base/share/classes/sun/net/smtp/SmtpClient.java index 59c60ce70dc..494bcf19987 100644 --- a/src/java.base/share/classes/sun/net/smtp/SmtpClient.java +++ b/src/java.base/share/classes/sun/net/smtp/SmtpClient.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,7 +28,6 @@ import java.io.*; import java.net.*; import sun.net.TransferProtocolClient; -import sun.security.action.GetPropertyAction; /** * This class implements the SMTP client. @@ -167,7 +166,7 @@ public SmtpClient (String host) throws IOException { } try { String s; - mailhost = GetPropertyAction.privilegedGetProperty("mail.host"); + mailhost = System.getProperty("mail.host"); if (mailhost != null) { openServer(mailhost); return; @@ -193,7 +192,7 @@ public SmtpClient(int to) throws IOException { setConnectTimeout(to); try { String s; - mailhost = GetPropertyAction.privilegedGetProperty("mail.host"); + mailhost = System.getProperty("mail.host"); if (mailhost != null) { openServer(mailhost); return; diff --git a/src/java.base/share/classes/sun/net/www/protocol/jar/JarFileFactory.java b/src/java.base/share/classes/sun/net/www/protocol/jar/JarFileFactory.java index 17ca43d4ace..9afbea8bf76 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/jar/JarFileFactory.java +++ b/src/java.base/share/classes/sun/net/www/protocol/jar/JarFileFactory.java @@ -31,7 +31,6 @@ import java.net.URLConnection; import java.util.HashMap; import java.util.jar.JarFile; -import java.security.Permission; import jdk.internal.util.OperatingSystem; import sun.net.util.URLUtil; @@ -219,35 +218,7 @@ public void close(JarFile jarFile) { private JarFile getCachedJarFile(URL url) { assert Thread.holdsLock(instance); - JarFile result = fileCache.get(urlKey(url)); - - /* if the JAR file is cached, the permission will always be there */ - if (result != null) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - Permission perm = getPermission(result); - if (perm != null) { - try { - sm.checkPermission(perm); - } catch (SecurityException se) { - // fallback to checkRead/checkConnect for pre 1.2 - // security managers - if ((perm instanceof java.io.FilePermission) && - perm.getActions().contains("read")) { - sm.checkRead(perm.getName()); - } else if ((perm instanceof - java.net.SocketPermission) && - perm.getActions().contains("connect")) { - sm.checkConnect(url.getHost(), url.getPort()); - } else { - throw se; - } - } - } - } - } - return result; + return fileCache.get(urlKey(url)); } private String urlKey(URL url) { @@ -255,16 +226,4 @@ private String urlKey(URL url) { if ("runtime".equals(url.getRef())) urlstr += "#runtime"; return urlstr; } - - private Permission getPermission(JarFile jarFile) { - try { - URLConnection uc = getConnection(jarFile); - if (uc != null) - return uc.getPermission(); - } catch (IOException ioe) { - // gulp - } - - return null; - } } diff --git a/src/java.base/share/classes/sun/net/www/protocol/jrt/JavaRuntimeURLConnection.java b/src/java.base/share/classes/sun/net/www/protocol/jrt/JavaRuntimeURLConnection.java index b4cd98870ca..4e67c962a46 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/jrt/JavaRuntimeURLConnection.java +++ b/src/java.base/share/classes/sun/net/www/protocol/jrt/JavaRuntimeURLConnection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved. * 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,15 +30,11 @@ import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; -import java.security.AccessController; -import java.security.Permission; -import java.security.PrivilegedAction; import jdk.internal.jimage.ImageLocation; import jdk.internal.jimage.ImageReader; import jdk.internal.jimage.ImageReaderFactory; -import jdk.internal.loader.URLClassPath; import jdk.internal.loader.Resource; import sun.net.www.ParseUtil; import sun.net.www.URLConnection; @@ -47,15 +43,10 @@ * URLConnection implementation that can be used to connect to resources * contained in the runtime image. */ -@SuppressWarnings("removal") public class JavaRuntimeURLConnection extends URLConnection { // ImageReader to access resources in jimage - private static final ImageReader reader; - static { - PrivilegedAction pa = ImageReaderFactory::getImageReader; - reader = AccessController.doPrivileged(pa); - } + private static final ImageReader reader = ImageReaderFactory.getImageReader(); // the module and resource name in the URL private final String module; @@ -92,7 +83,7 @@ private static Resource findResource(String module, String name) { if (reader != null) { URL url = toJrtURL(module, name); ImageLocation location = reader.findLocation(module, name); - if (location != null && URLClassPath.checkURL(url) != null) { + if (location != null) { return new Resource() { @Override public String getName() { @@ -158,11 +149,6 @@ public int getContentLength() { return len > Integer.MAX_VALUE ? -1 : (int)len; } - @Override - public Permission getPermission() { - return new RuntimePermission("accessSystemModules"); - } - /** * Returns a jrt URL for the given module and resource name. */ diff --git a/src/java.base/share/classes/sun/net/www/protocol/mailto/MailToURLConnection.java b/src/java.base/share/classes/sun/net/www/protocol/mailto/MailToURLConnection.java index 555279f71ee..7791d07a8ca 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/mailto/MailToURLConnection.java +++ b/src/java.base/share/classes/sun/net/www/protocol/mailto/MailToURLConnection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, Oracle and/or its affiliates. All rights reserved. * 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,9 +27,7 @@ import java.net.URL; import java.net.InetAddress; -import java.net.SocketPermission; import java.io.*; -import java.security.Permission; import jdk.internal.util.StaticProperty; import sun.net.www.*; @@ -48,7 +46,6 @@ public class MailToURLConnection extends URLConnection { OutputStream os = null; SmtpClient client; - Permission permission; private int connectTimeout = -1; private int readTimeout = -1; @@ -67,12 +64,6 @@ public class MailToURLConnection extends URLConnection { String getFromAddress() { String str = System.getProperty("user.fromaddr"); if (str == null) { - // Perform the property security check for user.name - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPropertyAccess("user.name"); - } str = StaticProperty.userName(); if (str != null) { String host = System.getProperty("mail.host"); @@ -112,16 +103,6 @@ public synchronized OutputStream getOutputStream() throws IOException { return os; } - @Override - public Permission getPermission() throws IOException { - if (permission == null) { - connect(); - String host = client.getMailHost() + ":" + 25; - permission = new SocketPermission(host, "connect"); - } - return permission; - } - @Override public void setConnectTimeout(int timeout) { if (timeout < 0) diff --git a/src/java.base/share/classes/sun/nio/cs/StreamDecoder.java b/src/java.base/share/classes/sun/nio/cs/StreamDecoder.java index a2026744f04..124e41b77c9 100644 --- a/src/java.base/share/classes/sun/nio/cs/StreamDecoder.java +++ b/src/java.base/share/classes/sun/nio/cs/StreamDecoder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,8 +44,6 @@ import java.nio.charset.UnsupportedCharsetException; import java.util.Arrays; -import jdk.internal.misc.InternalLock; - public class StreamDecoder extends Reader { private static final int MIN_BYTE_BUFFER_SIZE = 32; @@ -121,178 +119,109 @@ public int read() throws IOException { return read0(); } + @SuppressWarnings("fallthrough") private int read0() throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - return lockedRead0(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - return lockedRead0(); + synchronized (lock) { + // Return the leftover char, if there is one + if (haveLeftoverChar) { + haveLeftoverChar = false; + return leftoverChar; } - } - } - - @SuppressWarnings("fallthrough") - private int lockedRead0() throws IOException { - // Return the leftover char, if there is one - if (haveLeftoverChar) { - haveLeftoverChar = false; - return leftoverChar; - } - // Convert more bytes - char[] cb = new char[2]; - int n = read(cb, 0, 2); - switch (n) { - case -1: - return -1; - case 2: - leftoverChar = cb[1]; - haveLeftoverChar = true; - // FALL THROUGH - case 1: - return cb[0]; - default: - assert false : n; - return -1; + // Convert more bytes + char[] cb = new char[2]; + int n = read(cb, 0, 2); + switch (n) { + case -1: + return -1; + case 2: + leftoverChar = cb[1]; + haveLeftoverChar = true; + // FALL THROUGH + case 1: + return cb[0]; + default: + assert false : n; + return -1; + } } } public int read(char[] cbuf, int offset, int length) throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - return lockedRead(cbuf, offset, length); - } finally { - locker.unlock(); + synchronized (lock) { + int off = offset; + int len = length; + + ensureOpen(); + if ((off < 0) || (off > cbuf.length) || (len < 0) || + ((off + len) > cbuf.length) || ((off + len) < 0)) { + throw new IndexOutOfBoundsException(); } - } else { - synchronized (lock) { - return lockedRead(cbuf, offset, length); + if (len == 0) + return 0; + + int n = 0; + + if (haveLeftoverChar) { + // Copy the leftover char into the buffer + cbuf[off] = leftoverChar; + off++; len--; + haveLeftoverChar = false; + n = 1; + if ((len == 0) || !implReady()) + // Return now if this is all we can produce w/o blocking + return n; } - } - } - private int lockedRead(char[] cbuf, int offset, int length) throws IOException { - int off = offset; - int len = length; + if (len == 1) { + // Treat single-character array reads just like read() + int c = read0(); + if (c == -1) + return (n == 0) ? -1 : n; + cbuf[off] = (char)c; + return n + 1; + } - ensureOpen(); - if ((off < 0) || (off > cbuf.length) || (len < 0) || - ((off + len) > cbuf.length) || ((off + len) < 0)) { - throw new IndexOutOfBoundsException(); - } - if (len == 0) - return 0; - - int n = 0; - - if (haveLeftoverChar) { - // Copy the leftover char into the buffer - cbuf[off] = leftoverChar; - off++; len--; - haveLeftoverChar = false; - n = 1; - if ((len == 0) || !implReady()) - // Return now if this is all we can produce w/o blocking - return n; - } + // Read remaining characters + int nr = implRead(cbuf, off, off + len); - if (len == 1) { - // Treat single-character array reads just like read() - int c = read0(); - if (c == -1) - return (n == 0) ? -1 : n; - cbuf[off] = (char)c; - return n + 1; + // At this point, n is either 1 if a leftover character was read, + // or 0 if no leftover character was read. If n is 1 and nr is -1, + // indicating EOF, then we don't return their sum as this loses data. + return (nr < 0) ? (n == 1 ? 1 : nr) : (n + nr); } - - // Read remaining characters - int nr = implRead(cbuf, off, off + len); - - // At this point, n is either 1 if a leftover character was read, - // or 0 if no leftover character was read. If n is 1 and nr is -1, - // indicating EOF, then we don't return their sum as this loses data. - return (nr < 0) ? (n == 1 ? 1 : nr) : (n + nr); } public boolean ready() throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - return lockedReady(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - return lockedReady(); - } + synchronized (lock) { + ensureOpen(); + return haveLeftoverChar || implReady(); } } - private boolean lockedReady() throws IOException { - ensureOpen(); - return haveLeftoverChar || implReady(); - } - public void close() throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); + synchronized (lock) { + if (closed) + return; try { - lockedClose(); + implClose(); } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - lockedClose(); + closed = true; } } } - private void lockedClose() throws IOException { - if (closed) - return; - try { - implClose(); - } finally { - closed = true; - } - } - private boolean isOpen() { return !closed; } public void fillZeroToPosition() throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - lockedFillZeroToPosition(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - lockedFillZeroToPosition(); - } + synchronized (lock) { + Arrays.fill(bb.array(), bb.arrayOffset(), + bb.arrayOffset() + bb.position(), (byte)0); } } - private void lockedFillZeroToPosition() { - Arrays.fill(bb.array(), bb.arrayOffset(), bb.arrayOffset() + bb.position(), (byte)0); - } - // -- Charset-based stream decoder impl -- private final Charset cs; diff --git a/src/java.base/share/classes/sun/nio/cs/StreamEncoder.java b/src/java.base/share/classes/sun/nio/cs/StreamEncoder.java index 3a82030121a..b580ad2f921 100644 --- a/src/java.base/share/classes/sun/nio/cs/StreamEncoder.java +++ b/src/java.base/share/classes/sun/nio/cs/StreamEncoder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,7 +37,6 @@ import java.nio.charset.CodingErrorAction; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.UnsupportedCharsetException; -import jdk.internal.misc.InternalLock; public final class StreamEncoder extends Writer { @@ -97,28 +96,14 @@ public String getEncoding() { } public void flushBuffer() throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - lockedFlushBuffer(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - lockedFlushBuffer(); - } + synchronized (lock) { + if (isOpen()) + implFlushBuffer(); + else + throw new IOException("Stream closed"); } } - private void lockedFlushBuffer() throws IOException { - if (isOpen()) - implFlushBuffer(); - else - throw new IOException("Stream closed"); - } - public void write(int c) throws IOException { char[] cbuf = new char[1]; cbuf[0] = (char) c; @@ -126,30 +111,16 @@ public void write(int c) throws IOException { } public void write(char[] cbuf, int off, int len) throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - lockedWrite(cbuf, off, len); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - lockedWrite(cbuf, off, len); - } - } - } - - private void lockedWrite(char[] cbuf, int off, int len) throws IOException { - ensureOpen(); - if ((off < 0) || (off > cbuf.length) || (len < 0) || + synchronized (lock) { + ensureOpen(); + if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) { - throw new IndexOutOfBoundsException(); - } else if (len == 0) { - return; + throw new IndexOutOfBoundsException(); + } else if (len == 0) { + return; + } + implWrite(cbuf, off, len); } - implWrite(cbuf, off, len); } public void write(String str, int off, int len) throws IOException { @@ -164,76 +135,34 @@ public void write(String str, int off, int len) throws IOException { public void write(CharBuffer cb) throws IOException { int position = cb.position(); try { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - lockedWrite(cb); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - lockedWrite(cb); - } + synchronized (lock) { + ensureOpen(); + implWrite(cb); } } finally { cb.position(position); } } - private void lockedWrite(CharBuffer cb) throws IOException { - ensureOpen(); - implWrite(cb); - } - public void flush() throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); - try { - lockedFlush(); - } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - lockedFlush(); - } + synchronized (lock) { + ensureOpen(); + implFlush(); } } - private void lockedFlush() throws IOException { - ensureOpen(); - implFlush(); - } - public void close() throws IOException { - Object lock = this.lock; - if (lock instanceof InternalLock locker) { - locker.lock(); + synchronized (lock) { + if (closed) + return; try { - lockedClose(); + implClose(); } finally { - locker.unlock(); - } - } else { - synchronized (lock) { - lockedClose(); + closed = true; } } } - private void lockedClose() throws IOException { - if (closed) - return; - try { - implClose(); - } finally { - closed = true; - } - } - private boolean isOpen() { return !closed; } diff --git a/src/java.base/share/classes/sun/security/util/SecurityConstants.java b/src/java.base/share/classes/sun/security/util/SecurityConstants.java index df2861f3034..617e7a35a54 100644 --- a/src/java.base/share/classes/sun/security/util/SecurityConstants.java +++ b/src/java.base/share/classes/sun/security/util/SecurityConstants.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * 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,22 +80,6 @@ private SecurityConstants () { public static final NetPermission GET_PROXYSELECTOR_PERMISSION = new NetPermission("getProxySelector"); - // java.net.CookieHandler - public static final NetPermission SET_COOKIEHANDLER_PERMISSION = - new NetPermission("setCookieHandler"); - - // java.net.CookieHandler - public static final NetPermission GET_COOKIEHANDLER_PERMISSION = - new NetPermission("getCookieHandler"); - - // java.net.ResponseCache - public static final NetPermission SET_RESPONSECACHE_PERMISSION = - new NetPermission("setResponseCache"); - - // java.net.ResponseCache - public static final NetPermission GET_RESPONSECACHE_PERMISSION = - new NetPermission("getResponseCache"); - // java.net.ServerSocket, java.net.Socket public static final NetPermission SET_SOCKETIMPL_PERMISSION = new NetPermission("setSocketImpl"); diff --git a/src/java.datatransfer/share/classes/java/awt/datatransfer/DataFlavor.java b/src/java.datatransfer/share/classes/java/awt/datatransfer/DataFlavor.java index 757c4f99f45..f228f1a4da1 100644 --- a/src/java.datatransfer/share/classes/java/awt/datatransfer/DataFlavor.java +++ b/src/java.datatransfer/share/classes/java/awt/datatransfer/DataFlavor.java @@ -45,7 +45,6 @@ import java.util.Objects; import sun.datatransfer.DataFlavorUtil; -import sun.reflect.misc.ReflectUtil; /** * A {@code DataFlavor} provides meta information about data. {@code DataFlavor} @@ -131,32 +130,22 @@ protected static final Class tryToLoadClass(String className, ClassLoader fallback) throws ClassNotFoundException { - ReflectUtil.checkPackageAccess(className); + ClassLoader loader = ClassLoader.getSystemClassLoader(); try { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(new RuntimePermission("getClassLoader")); - } - ClassLoader loader = ClassLoader.getSystemClassLoader(); - try { - // bootstrap class loader and system class loader if present - return Class.forName(className, true, loader); - } - catch (ClassNotFoundException exception) { - // thread context class loader if and only if present - loader = Thread.currentThread().getContextClassLoader(); - if (loader != null) { - try { - return Class.forName(className, true, loader); - } - catch (ClassNotFoundException e) { - // fallback to user's class loader - } + // bootstrap class loader and system class loader if present + return Class.forName(className, true, loader); + } + catch (ClassNotFoundException exception) { + // thread context class loader if and only if present + loader = Thread.currentThread().getContextClassLoader(); + if (loader != null) { + try { + return Class.forName(className, true, loader); + } + catch (ClassNotFoundException e) { + // fallback to user's class loader } } - } catch (SecurityException exception) { - // ignore secured class loaders } return Class.forName(className, true, fallback); } diff --git a/src/java.datatransfer/share/classes/java/awt/datatransfer/SystemFlavorMap.java b/src/java.datatransfer/share/classes/java/awt/datatransfer/SystemFlavorMap.java index 6b2dc14c05f..deea133b734 100644 --- a/src/java.datatransfer/share/classes/java/awt/datatransfer/SystemFlavorMap.java +++ b/src/java.datatransfer/share/classes/java/awt/datatransfer/SystemFlavorMap.java @@ -30,8 +30,6 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.lang.ref.SoftReference; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -202,12 +200,8 @@ private void initSystemFlavorMap() { } isMapInitialized = true; - @SuppressWarnings("removal") - InputStream is = AccessController.doPrivileged( - (PrivilegedAction) () -> { - return SystemFlavorMap.class.getResourceAsStream( + InputStream is = SystemFlavorMap.class.getResourceAsStream( "/sun/datatransfer/resources/flavormap.properties"); - }); if (is == null) { throw new InternalError("Default flavor mapping not found"); } diff --git a/src/java.desktop/share/classes/java/awt/Component.java b/src/java.desktop/share/classes/java/awt/Component.java index ad0b87fd3fc..a1f8461c802 100644 --- a/src/java.desktop/share/classes/java/awt/Component.java +++ b/src/java.desktop/share/classes/java/awt/Component.java @@ -627,14 +627,10 @@ static class AWTTreeLock {} initIDs(); } - @SuppressWarnings("removal") - String s = java.security.AccessController.doPrivileged( - new GetPropertyAction("awt.image.incrementaldraw")); + String s = System.getProperty("awt.image.incrementaldraw"); isInc = (s == null || s.equals("true")); - @SuppressWarnings("removal") - String s2 = java.security.AccessController.doPrivileged( - new GetPropertyAction("awt.image.redrawrate")); + String s2 = System.getProperty("awt.image.redrawrate"); incRate = (s2 != null) ? Integer.parseInt(s2) : 100; } @@ -1431,15 +1427,7 @@ public Point getMousePosition() throws HeadlessException { throw new HeadlessException(); } - @SuppressWarnings("removal") - PointerInfo pi = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public PointerInfo run() { - return MouseInfo.getPointerInfo(); - } - } - ); - + PointerInfo pi = MouseInfo.getPointerInfo(); synchronized (getTreeLock()) { Component inTheSameWindow = findUnderMouseInWindow(pi); if (!isSameOrAncestorOf(inTheSameWindow, true)) { @@ -6253,14 +6241,7 @@ private boolean checkCoalescing() { } // Need to check non-bootstraps. - @SuppressWarnings("removal") - Boolean enabled = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Boolean run() { - return isCoalesceEventsOverriden(clazz); - } - } - ); + Boolean enabled = isCoalesceEventsOverriden(clazz); coalesceMap.put(clazz, enabled); return enabled; } diff --git a/src/java.desktop/share/classes/java/awt/Container.java b/src/java.desktop/share/classes/java/awt/Container.java index c8289aa7fcc..2eb2c923de0 100644 --- a/src/java.desktop/share/classes/java/awt/Container.java +++ b/src/java.desktop/share/classes/java/awt/Container.java @@ -1576,10 +1576,8 @@ public boolean isValidateRoot() { } // Don't lazy-read because every app uses invalidate() - @SuppressWarnings("removal") - private static final boolean isJavaAwtSmartInvalidate - = AccessController.doPrivileged( - new GetBooleanAction("java.awt.smartInvalidate")); + private static final boolean isJavaAwtSmartInvalidate = + Boolean.getBoolean("java.awt.smartInvalidate"); /** * Invalidates the parent of the container unless the container @@ -2632,14 +2630,7 @@ public Point getMousePosition(boolean allowChildren) throws HeadlessException { if (GraphicsEnvironment.isHeadless()) { throw new HeadlessException(); } - @SuppressWarnings("removal") - PointerInfo pi = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public PointerInfo run() { - return MouseInfo.getPointerInfo(); - } - } - ); + PointerInfo pi = MouseInfo.getPointerInfo(); synchronized (getTreeLock()) { Component inTheSameWindow = findUnderMouseInWindow(pi); if (isSameOrAncestorOf(inTheSameWindow, allowChildren)) { @@ -4738,33 +4729,17 @@ private Component retargetMouseEnterExit(Component targetOver, MouseEvent e, * from other heavyweight containers will generate enter/exit * events in this container */ - @SuppressWarnings("removal") private void startListeningForOtherDrags() { //System.out.println("Adding AWTEventListener"); - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - nativeContainer.getToolkit().addAWTEventListener( - LightweightDispatcher.this, - AWTEvent.MOUSE_EVENT_MASK | - AWTEvent.MOUSE_MOTION_EVENT_MASK); - return null; - } - } - ); + nativeContainer.getToolkit().addAWTEventListener( + LightweightDispatcher.this, + AWTEvent.MOUSE_EVENT_MASK | + AWTEvent.MOUSE_MOTION_EVENT_MASK); } - @SuppressWarnings("removal") private void stopListeningForOtherDrags() { //System.out.println("Removing AWTEventListener"); - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - nativeContainer.getToolkit().removeAWTEventListener(LightweightDispatcher.this); - return null; - } - } - ); + nativeContainer.getToolkit().removeAWTEventListener(LightweightDispatcher.this); } /* diff --git a/src/java.desktop/share/classes/java/awt/Cursor.java b/src/java.desktop/share/classes/java/awt/Cursor.java index cfccf06723b..8a595f61285 100644 --- a/src/java.desktop/share/classes/java/awt/Cursor.java +++ b/src/java.desktop/share/classes/java/awt/Cursor.java @@ -29,8 +29,6 @@ import java.io.InputStream; import java.io.Serial; import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedExceptionAction; import java.util.Hashtable; import java.util.Properties; import java.util.StringTokenizer; @@ -332,11 +330,7 @@ public static Cursor getSystemCustomCursor(final String name) } final Toolkit toolkit = Toolkit.getDefaultToolkit(); final String file = RESOURCE_PREFIX + fileName; - @SuppressWarnings("removal") - final InputStream in = AccessController.doPrivileged( - (PrivilegedAction) () -> { - return Cursor.class.getResourceAsStream(file); - }); + final InputStream in = Cursor.class.getResourceAsStream(file); try (in) { Image image = toolkit.createImage(in.readAllBytes()); cursor = toolkit.createCustomCursor(image, hotPoint, localized); @@ -428,7 +422,6 @@ public String toString() { /* * load the cursor.properties file */ - @SuppressWarnings("removal") private static void loadSystemCustomCursorProperties() throws AWTException { synchronized (systemCustomCursors) { if (systemCustomCursorProperties != null) { @@ -437,14 +430,8 @@ private static void loadSystemCustomCursorProperties() throws AWTException { systemCustomCursorProperties = new Properties(); try { - AccessController.doPrivileged( - (PrivilegedExceptionAction) () -> { - try (InputStream is = Cursor.class - .getResourceAsStream(PROPERTIES_FILE)) { - systemCustomCursorProperties.load(is); - } - return null; - }); + InputStream is = Cursor.class.getResourceAsStream(PROPERTIES_FILE); + systemCustomCursorProperties.load(is); } catch (Exception e) { systemCustomCursorProperties = null; throw new AWTException("Exception: " + e.getClass() + " " + diff --git a/src/java.desktop/share/classes/java/awt/DefaultKeyboardFocusManager.java b/src/java.desktop/share/classes/java/awt/DefaultKeyboardFocusManager.java index e416e791e8d..3c57ec3a8d9 100644 --- a/src/java.desktop/share/classes/java/awt/DefaultKeyboardFocusManager.java +++ b/src/java.desktop/share/classes/java/awt/DefaultKeyboardFocusManager.java @@ -32,8 +32,6 @@ import java.awt.peer.LightweightPeer; import java.io.Serial; import java.lang.ref.WeakReference; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Iterator; import java.util.LinkedList; import java.util.ListIterator; @@ -86,21 +84,14 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager { initStatic(); } - @SuppressWarnings("removal") private static void initStatic() { AWTAccessor.setDefaultKeyboardFocusManagerAccessor( new AWTAccessor.DefaultKeyboardFocusManagerAccessor() { public void consumeNextKeyTyped(DefaultKeyboardFocusManager dkfm, KeyEvent e) { dkfm.consumeNextKeyTyped(e); - } + } }); - AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - fxAppThreadIsDispatchThread = - "true".equals(System.getProperty("javafx.embed.singleThread")); - return null; - } - }); + fxAppThreadIsDispatchThread = "true".equals(System.getProperty("javafx.embed.singleThread")); } /** diff --git a/src/java.desktop/share/classes/java/awt/Desktop.java b/src/java.desktop/share/classes/java/awt/Desktop.java index 025889755b8..89a78518873 100644 --- a/src/java.desktop/share/classes/java/awt/Desktop.java +++ b/src/java.desktop/share/classes/java/awt/Desktop.java @@ -42,8 +42,6 @@ import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Objects; import javax.swing.JMenuBar; @@ -936,11 +934,7 @@ public boolean moveToTrash(File file) { sm.checkDelete(file.getPath()); } checkActionSupport(Action.MOVE_TO_TRASH); - final File finalFile = file; - AccessController.doPrivileged((PrivilegedAction) () -> { - checkFileValidation(finalFile); - return null; - }); + checkFileValidation(file); return peer.moveToTrash(file); } } diff --git a/src/java.desktop/share/classes/java/awt/Dialog.java b/src/java.desktop/share/classes/java/awt/Dialog.java index a0d22fbb327..03449200478 100644 --- a/src/java.desktop/share/classes/java/awt/Dialog.java +++ b/src/java.desktop/share/classes/java/awt/Dialog.java @@ -34,8 +34,6 @@ import java.io.ObjectInputStream; import java.io.Serial; import java.security.AccessControlException; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Iterator; import java.util.concurrent.atomic.AtomicLong; @@ -1052,9 +1050,7 @@ public void show() { modalityPushed(); try { - @SuppressWarnings("removal") - final EventQueue eventQueue = AccessController.doPrivileged( - (PrivilegedAction) Toolkit.getDefaultToolkit()::getSystemEventQueue); + EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue(); secondaryLoop = eventQueue.createSecondaryLoop(() -> true, modalFilter, 0); if (!secondaryLoop.enter()) { secondaryLoop = null; diff --git a/src/java.desktop/share/classes/java/awt/EventQueue.java b/src/java.desktop/share/classes/java/awt/EventQueue.java index 4dce257f727..57a9a6cf567 100644 --- a/src/java.desktop/share/classes/java/awt/EventQueue.java +++ b/src/java.desktop/share/classes/java/awt/EventQueue.java @@ -32,9 +32,6 @@ import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; -import java.security.AccessController; -import java.security.PrivilegedAction; - import java.util.EmptyStackException; import sun.awt.*; @@ -45,11 +42,6 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.atomic.AtomicInteger; -import java.security.AccessControlContext; - -import jdk.internal.access.SharedSecrets; -import jdk.internal.access.JavaSecurityAccess; - /** * {@code EventQueue} is a platform-independent class * that queues events, both from the underlying peer classes @@ -229,13 +221,8 @@ public long getMostRecentEventTime(EventQueue eventQueue) { }); } - @SuppressWarnings("removal") private static boolean fxAppThreadIsDispatchThread = - AccessController.doPrivileged(new PrivilegedAction() { - public Boolean run() { - return "true".equals(System.getProperty("javafx.embed.singleThread")); - } - }); + "true".equals(System.getProperty("javafx.embed.singleThread")); /** * Initializes a new instance of {@code EventQueue}. @@ -668,9 +655,6 @@ public AWTEvent peekEvent(int id) { return null; } - private static final JavaSecurityAccess javaSecurityAccess = - SharedSecrets.getJavaSecurityAccess(); - /** * Dispatches an event. The manner in which the event is * dispatched depends upon the type of the event and the @@ -711,59 +695,25 @@ public AWTEvent peekEvent(int id) { */ protected void dispatchEvent(final AWTEvent event) { final Object src = event.getSource(); - final PrivilegedAction action = new PrivilegedAction() { - public Void run() { - // In case fwDispatcher is installed and we're already on the - // dispatch thread (e.g. performing DefaultKeyboardFocusManager.sendMessage), - // dispatch the event straight away. - if (fwDispatcher == null || isDispatchThreadImpl()) { - dispatchEventImpl(event, src); - } else { - fwDispatcher.scheduleDispatch(new Runnable() { - @Override - public void run() { - if (dispatchThread.filterAndCheckEvent(event)) { - dispatchEventImpl(event, src); - } - } - }); - } - return null; - } - }; - - @SuppressWarnings("removal") - final AccessControlContext stack = AccessController.getContext(); - @SuppressWarnings("removal") - final AccessControlContext srcAcc = getAccessControlContextFrom(src); - @SuppressWarnings("removal") - final AccessControlContext eventAcc = event.getAccessControlContext(); - if (srcAcc == null) { - javaSecurityAccess.doIntersectionPrivilege(action, stack, eventAcc); + // In case fwDispatcher is installed and we're already on the + // dispatch thread (e.g. performing DefaultKeyboardFocusManager.sendMessage), + // dispatch the event straight away. + if (fwDispatcher == null || isDispatchThreadImpl()) { + dispatchEventImpl(event, src); } else { - javaSecurityAccess.doIntersectionPrivilege( - new PrivilegedAction() { - public Void run() { - javaSecurityAccess.doIntersectionPrivilege(action, eventAcc); - return null; + fwDispatcher.scheduleDispatch(new Runnable() { + @Override + public void run() { + if (dispatchThread.filterAndCheckEvent(event)) { + dispatchEventImpl(event, src); } - }, stack, srcAcc); + } + }); } } - @SuppressWarnings("removal") - private static AccessControlContext getAccessControlContextFrom(Object src) { - return src instanceof Component ? - ((Component)src).getAccessControlContext() : - src instanceof MenuComponent ? - ((MenuComponent)src).getAccessControlContext() : - src instanceof TrayIcon ? - ((TrayIcon)src).getAccessControlContext() : - null; - } - /** - * Called from dispatchEvent() under a correct AccessControlContext + * Called from dispatchEvent() */ private void dispatchEventImpl(final AWTEvent event, final Object src) { event.isPosted = true; @@ -1113,21 +1063,12 @@ final void initDispatchThread() { pushPopLock.lock(); try { if (dispatchThread == null && !threadGroup.isDestroyed() && !appContext.isDisposed()) { - dispatchThread = AccessController.doPrivileged( - new PrivilegedAction() { - public EventDispatchThread run() { - EventDispatchThread t = - new EventDispatchThread(threadGroup, - name, - EventQueue.this); - t.setContextClassLoader(classLoader); - t.setPriority(Thread.NORM_PRIORITY + 1); - t.setDaemon(false); - AWTAutoShutdown.getInstance().notifyThreadBusy(t); - return t; - } - } - ); + EventDispatchThread t = new EventDispatchThread(threadGroup, name, EventQueue.this); + t.setContextClassLoader(classLoader); + t.setPriority(Thread.NORM_PRIORITY + 1); + t.setDaemon(false); + AWTAutoShutdown.getInstance().notifyThreadBusy(t); + dispatchThread = t; dispatchThread.start(); } } finally { diff --git a/src/java.desktop/share/classes/java/awt/Font.java b/src/java.desktop/share/classes/java/awt/Font.java index ff5c29a2758..3df4632f9d3 100644 --- a/src/java.desktop/share/classes/java/awt/Font.java +++ b/src/java.desktop/share/classes/java/awt/Font.java @@ -44,8 +44,6 @@ import java.io.Serial; import java.lang.ref.SoftReference; import java.nio.file.Files; -import java.security.AccessController; -import java.security.PrivilegedExceptionAction; import java.text.AttributedCharacterIterator.Attribute; import java.text.CharacterIterator; import java.util.EventListener; @@ -1095,7 +1093,6 @@ public static Font createFont(int fontFormat, InputStream fontStream) } } - @SuppressWarnings("removal") private static Font[] createFont0(int fontFormat, InputStream fontStream, boolean allFonts, CreatedFontTracker tracker) @@ -1107,27 +1104,14 @@ private static Font[] createFont0(int fontFormat, InputStream fontStream, } boolean copiedFontData = false; try { - final File tFile = AccessController.doPrivileged( - new PrivilegedExceptionAction() { - public File run() throws IOException { - return Files.createTempFile("+~JF", ".tmp").toFile(); - } - } - ); + final File tFile = Files.createTempFile("+~JF", ".tmp").toFile(); if (tracker != null) { tracker.add(tFile); } int totalSize = 0; try { - final OutputStream outStream = - AccessController.doPrivileged( - new PrivilegedExceptionAction() { - public OutputStream run() throws IOException { - return new FileOutputStream(tFile); - } - } - ); + final OutputStream outStream = new FileOutputStream(tFile); if (tracker != null) { tracker.set(tFile, outStream); } @@ -1181,14 +1165,7 @@ public OutputStream run() throws IOException { if (tracker != null) { tracker.subBytes(totalSize); } - AccessController.doPrivileged( - new PrivilegedExceptionAction() { - public Void run() { - tFile.delete(); - return null; - } - } - ); + tFile.delete(); } } } catch (Throwable t) { diff --git a/src/java.desktop/share/classes/java/awt/GraphicsEnvironment.java b/src/java.desktop/share/classes/java/awt/GraphicsEnvironment.java index 2e89aa6f672..4936d5d396d 100644 --- a/src/java.desktop/share/classes/java/awt/GraphicsEnvironment.java +++ b/src/java.desktop/share/classes/java/awt/GraphicsEnvironment.java @@ -26,8 +26,6 @@ package java.awt; import java.awt.image.BufferedImage; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Locale; import sun.awt.PlatformGraphicsInfo; @@ -137,20 +135,16 @@ static String getHeadlessMessage() { * @return the value of the property "java.awt.headless" * @since 1.4 */ - @SuppressWarnings("removal") private static boolean getHeadlessProperty() { if (headless == null) { - AccessController.doPrivileged((PrivilegedAction) () -> { - String nm = System.getProperty("java.awt.headless"); + String nm = System.getProperty("java.awt.headless"); - if (nm == null) { - headless = defaultHeadless = - PlatformGraphicsInfo.getDefaultHeadlessProperty(); - } else { - headless = Boolean.valueOf(nm); - } - return null; - }); + if (nm == null) { + headless = defaultHeadless = + PlatformGraphicsInfo.getDefaultHeadlessProperty(); + } else { + headless = Boolean.valueOf(nm); + } } return headless; } diff --git a/src/java.desktop/share/classes/java/awt/KeyboardFocusManager.java b/src/java.desktop/share/classes/java/awt/KeyboardFocusManager.java index 0ca86f3433b..eb623213a77 100644 --- a/src/java.desktop/share/classes/java/awt/KeyboardFocusManager.java +++ b/src/java.desktop/share/classes/java/awt/KeyboardFocusManager.java @@ -40,9 +40,6 @@ import java.lang.ref.WeakReference; -import java.security.AccessController; -import java.security.PrivilegedAction; - import java.util.Collections; import java.util.HashSet; import java.util.Iterator; @@ -601,14 +598,8 @@ private void _clearGlobalFocusOwner() { peer.clearGlobalFocusOwner(activeWindow); } - @SuppressWarnings("removal") void clearGlobalFocusOwnerPriv() { - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - clearGlobalFocusOwner(); - return null; - } - }); + clearGlobalFocusOwner(); } Component getNativeFocusOwner() { @@ -1194,14 +1185,8 @@ public void setGlobalCurrentFocusCycleRoot(Container newFocusCycleRoot) { newFocusCycleRoot); } - @SuppressWarnings("removal") void setGlobalCurrentFocusCycleRootPriv(final Container newFocusCycleRoot) { - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - setGlobalCurrentFocusCycleRoot(newFocusCycleRoot); - return null; - } - }); + setGlobalCurrentFocusCycleRoot(newFocusCycleRoot); } /** diff --git a/src/java.desktop/share/classes/java/awt/SequencedEvent.java b/src/java.desktop/share/classes/java/awt/SequencedEvent.java index 410437a5c9e..a671814a57b 100644 --- a/src/java.desktop/share/classes/java/awt/SequencedEvent.java +++ b/src/java.desktop/share/classes/java/awt/SequencedEvent.java @@ -26,8 +26,6 @@ package java.awt; import java.io.Serial; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.LinkedList; import sun.awt.AWTAccessor; @@ -80,13 +78,7 @@ public AWTEvent create(AWTEvent event) { return new SequencedEvent(event); } }); - AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - fxAppThreadIsDispatchThread = - "true".equals(System.getProperty("javafx.embed.singleThread")); - return null; - } - }); + fxAppThreadIsDispatchThread = "true".equals(System.getProperty("javafx.embed.singleThread")); } private static final class SequencedEventsFilter implements EventFilter { diff --git a/src/java.desktop/share/classes/java/awt/SplashScreen.java b/src/java.desktop/share/classes/java/awt/SplashScreen.java index 78ec4ed7aa0..7f522026b8a 100644 --- a/src/java.desktop/share/classes/java/awt/SplashScreen.java +++ b/src/java.desktop/share/classes/java/awt/SplashScreen.java @@ -129,13 +129,7 @@ public static SplashScreen getSplashScreen() { } // SplashScreen class is now a singleton if (!wasClosed && theInstance == null) { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("splashscreen"); - return null; - } - }); + System.loadLibrary("splashscreen"); long ptr = _getInstance(); if (ptr != 0 && _isVisible(ptr)) { theInstance = new SplashScreen(ptr); diff --git a/src/java.desktop/share/classes/java/awt/Toolkit.java b/src/java.desktop/share/classes/java/awt/Toolkit.java index 19b0ab9019a..d181fb6f536 100644 --- a/src/java.desktop/share/classes/java/awt/Toolkit.java +++ b/src/java.desktop/share/classes/java/awt/Toolkit.java @@ -56,8 +56,6 @@ import java.io.File; import java.io.FileInputStream; import java.net.URL; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.EventListener; @@ -396,18 +394,12 @@ public abstract ColorModel getColorModel() * properties are set up properly before any classes dependent upon them * are initialized. */ - @SuppressWarnings("removal") private static void initAssistiveTechnologies() { // Get accessibility properties final String sep = File.separator; final Properties properties = new Properties(); - - atNames = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public String run() { - // Try loading the per-user accessibility properties file. try { File propsFile = new File( @@ -459,9 +451,7 @@ public String run() { System.setProperty("javax.accessibility.assistive_technologies", classNames); } } - return classNames; - } - }); + atNames = classNames; } /** @@ -512,7 +502,6 @@ private static void fallbackToLoadClassForAT(String atName) { * {@code null} it is ignored. All other errors are handled via an AWTError * exception. */ - @SuppressWarnings("removal") private static void loadAssistiveTechnologies() { // Load any assistive technologies if (atNames != null && !atNames.isBlank()) { @@ -521,20 +510,17 @@ private static void loadAssistiveTechnologies() { .map(String::trim) .collect(Collectors.toSet()); final Map providers = new HashMap<>(); - AccessController.doPrivileged((PrivilegedAction) () -> { - try { - for (AccessibilityProvider p : ServiceLoader.load(AccessibilityProvider.class, cl)) { - String name = p.getName(); - if (names.contains(name) && !providers.containsKey(name)) { - p.activate(); - providers.put(name, p); - } + try { + for (AccessibilityProvider p : ServiceLoader.load(AccessibilityProvider.class, cl)) { + String name = p.getName(); + if (names.contains(name) && !providers.containsKey(name)) { + p.activate(); + providers.put(name, p); } - } catch (java.util.ServiceConfigurationError | Exception e) { - newAWTError(e, "Could not load or activate service provider"); } - return null; - }); + } catch (java.util.ServiceConfigurationError | Exception e) { + newAWTError(e, "Could not load or activate service provider"); + } names.stream() .filter(n -> !providers.containsKey(n)) .forEach(Toolkit::fallbackToLoadClassForAT); @@ -1302,16 +1288,10 @@ private static void setPlatformResources(ResourceBundle bundle) { * directly. -hung */ private static boolean loaded = false; - @SuppressWarnings({"removal", "restricted"}) + @SuppressWarnings("restricted") static void loadLibraries() { if (!loaded) { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("awt"); - return null; - } - }); + System.loadLibrary("awt"); loaded = true; } } @@ -1320,7 +1300,6 @@ public Void run() { initStatic(); } - @SuppressWarnings("removal") private static void initStatic() { AWTAccessor.setToolkitAccessor( new AWTAccessor.ToolkitAccessor() { @@ -1330,17 +1309,11 @@ public void setPlatformResources(ResourceBundle bundle) { } }); - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - try { - resources = ResourceBundle.getBundle("sun.awt.resources.awt"); - } catch (MissingResourceException e) { - // No resource file; defaults will be used. - } - return null; - } - }); + try { + resources = ResourceBundle.getBundle("sun.awt.resources.awt"); + } catch (MissingResourceException e) { + // No resource file; defaults will be used. + } // ensure that the proper libraries are loaded loadLibraries(); diff --git a/src/java.desktop/share/classes/java/awt/WaitDispatchSupport.java b/src/java.desktop/share/classes/java/awt/WaitDispatchSupport.java index d239a600697..2968c9ad3ef 100644 --- a/src/java.desktop/share/classes/java/awt/WaitDispatchSupport.java +++ b/src/java.desktop/share/classes/java/awt/WaitDispatchSupport.java @@ -29,9 +29,6 @@ import java.util.TimerTask; import java.util.concurrent.atomic.AtomicBoolean; -import java.security.PrivilegedAction; -import java.security.AccessController; - import sun.awt.PeerEvent; import sun.util.logging.PlatformLogger; @@ -230,13 +227,7 @@ public void run() { // The event will be handled after the new event pump // starts. Thus, the enter() method will not hang. // - // Event pump should be privileged. See 6300270. - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - run.run(); - return null; - } - }); + run.run(); } else { if (log.isLoggable(PlatformLogger.Level.FINEST)) { log.finest("On non-dispatch thread: " + currentThread); diff --git a/src/java.desktop/share/classes/java/awt/Window.java b/src/java.desktop/share/classes/java/awt/Window.java index a1e9d48d9d4..1a5395431ab 100644 --- a/src/java.desktop/share/classes/java/awt/Window.java +++ b/src/java.desktop/share/classes/java/awt/Window.java @@ -48,7 +48,6 @@ import java.io.Serializable; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; -import java.security.AccessController; import java.util.ArrayList; import java.util.Arrays; import java.util.EventListener; @@ -414,13 +413,9 @@ public static enum Type { initIDs(); } - @SuppressWarnings("removal") - String s = java.security.AccessController.doPrivileged( - new GetPropertyAction("java.awt.syncLWRequests")); + String s = System.getProperty("java.awt.syncLWRequests"); systemSyncLWRequests = "true".equals(s); - @SuppressWarnings("removal") - String s2 = java.security.AccessController.doPrivileged( - new GetPropertyAction("java.awt.Window.locationByPlatform")); + String s2 = System.getProperty("java.awt.Window.locationByPlatform"); locationByPlatformProp = "true".equals(s2); } @@ -505,7 +500,6 @@ private void init(GraphicsConfiguration gc) { weakThis = new WeakReference(this); addToWindowList(); - setWarningString(); this.cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); this.visible = false; @@ -1376,24 +1370,6 @@ public final String getWarningString() { return warningString; } - @SuppressWarnings("removal") - private void setWarningString() { - warningString = null; - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - try { - sm.checkPermission(AWTPermissions.TOPLEVEL_WINDOW_PERMISSION); - } catch (SecurityException se) { - // make sure the privileged action is only - // for getting the property! We don't want the - // above checkPermission call to always succeed! - warningString = AccessController.doPrivileged( - new GetPropertyAction("awt.appletWarning", - "Java Applet Window")); - } - } - } - /** * Gets the {@code Locale} object that is associated * with this window, if the locale has been set. @@ -2978,7 +2954,6 @@ private void writeObject(ObjectOutputStream s) throws IOException { // user's code. // private void initDeserializedWindow() { - setWarningString(); inputContextLock = new Object(); // Deserialized Windows are not yet visible. diff --git a/src/java.desktop/share/classes/java/awt/color/ICC_Profile.java b/src/java.desktop/share/classes/java/awt/color/ICC_Profile.java index b4e71b3c839..729d8123a24 100644 --- a/src/java.desktop/share/classes/java/awt/color/ICC_Profile.java +++ b/src/java.desktop/share/classes/java/awt/color/ICC_Profile.java @@ -48,8 +48,6 @@ import java.io.OutputStream; import java.io.Serial; import java.io.Serializable; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Objects; import java.util.StringTokenizer; @@ -1341,13 +1339,8 @@ private static File getProfileFile(String fileName) { * fileName. If there is no built-in profile with such name, then the method * returns {@code null}. */ - @SuppressWarnings("removal") private static InputStream getStandardProfileInputStream(String fileName) { - return AccessController.doPrivileged( - (PrivilegedAction) () -> { - return PCMM.class.getResourceAsStream("profiles/" + fileName); - }, null, new FilePermission("<>", "read"), - new RuntimePermission("accessSystemModules")); + return PCMM.class.getResourceAsStream("profiles/" + fileName); } /** diff --git a/src/java.desktop/share/classes/java/awt/dnd/DragSource.java b/src/java.desktop/share/classes/java/awt/dnd/DragSource.java index 01945662e46..8477bc6376d 100644 --- a/src/java.desktop/share/classes/java/awt/dnd/DragSource.java +++ b/src/java.desktop/share/classes/java/awt/dnd/DragSource.java @@ -40,13 +40,11 @@ import java.io.ObjectOutputStream; import java.io.Serial; import java.io.Serializable; -import java.security.AccessController; import java.util.EventListener; import sun.awt.AWTAccessor; import sun.awt.AWTAccessor.DragSourceContextAccessor; import sun.awt.dnd.SunDragSourceContextPeer; -import sun.security.action.GetIntegerAction; /** * The {@code DragSource} is the entity responsible @@ -908,8 +906,7 @@ private void readObject(ObjectInputStream s) */ public static int getDragThreshold() { @SuppressWarnings("removal") - int ts = AccessController.doPrivileged( - new GetIntegerAction("awt.dnd.drag.threshold", 0)).intValue(); + int ts = Integer.getInteger("awt.dnd.drag.threshold", 0); if (ts > 0) { return ts; } else { diff --git a/src/java.desktop/share/classes/java/awt/event/NativeLibLoader.java b/src/java.desktop/share/classes/java/awt/event/NativeLibLoader.java index 27a2c439747..8b0d46d05e0 100644 --- a/src/java.desktop/share/classes/java/awt/event/NativeLibLoader.java +++ b/src/java.desktop/share/classes/java/awt/event/NativeLibLoader.java @@ -52,14 +52,8 @@ class NativeLibLoader { * For now, we know it's done by the implementation, and we assume * that the name of the library is "awt". -br. */ - @SuppressWarnings({"removal", "restricted"}) + @SuppressWarnings("restricted") static void loadLibraries() { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("awt"); - return null; - } - }); + System.loadLibrary("awt"); } } diff --git a/src/java.desktop/share/classes/java/awt/image/BufferedImage.java b/src/java.desktop/share/classes/java/awt/image/BufferedImage.java index cfbebd68710..09c96a6560f 100644 --- a/src/java.desktop/share/classes/java/awt/image/BufferedImage.java +++ b/src/java.desktop/share/classes/java/awt/image/BufferedImage.java @@ -31,8 +31,6 @@ import java.awt.Rectangle; import java.awt.Transparency; import java.awt.color.ColorSpace; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Hashtable; import java.util.Set; import java.util.Vector; @@ -800,26 +798,16 @@ else if (offs[3] == 0 && ccm.hasAlpha()) { } // else if ((raster instanceof ByteComponentRaster) && } - @SuppressWarnings("removal") private static boolean isStandard(ColorModel cm, WritableRaster wr) { final Class cmClass = cm.getClass(); final Class wrClass = wr.getClass(); final Class smClass = wr.getSampleModel().getClass(); - final PrivilegedAction checkClassLoadersAction = - new PrivilegedAction() - { - - @Override - public Boolean run() { - final ClassLoader std = System.class.getClassLoader(); + final ClassLoader std = System.class.getClassLoader(); - return (cmClass.getClassLoader() == std) && - (smClass.getClassLoader() == std) && - (wrClass.getClassLoader() == std); - } - }; - return AccessController.doPrivileged(checkClassLoadersAction); + return (cmClass.getClassLoader() == std) && + (smClass.getClassLoader() == std) && + (wrClass.getClassLoader() == std); } /** diff --git a/src/java.desktop/share/classes/java/awt/image/ColorModel.java b/src/java.desktop/share/classes/java/awt/image/ColorModel.java index a0aa8fddc10..b2d568cb09f 100644 --- a/src/java.desktop/share/classes/java/awt/image/ColorModel.java +++ b/src/java.desktop/share/classes/java/awt/image/ColorModel.java @@ -202,16 +202,10 @@ public abstract class ColorModel implements Transparency{ * that the name of the library is "awt". -br. */ private static boolean loaded = false; - @SuppressWarnings({"removal", "restricted"}) + @SuppressWarnings("restricted") static void loadLibraries() { if (!loaded) { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("awt"); - return null; - } - }); + System.loadLibrary("awt"); loaded = true; } } diff --git a/src/java.desktop/share/classes/java/beans/EventHandler.java b/src/java.desktop/share/classes/java/beans/EventHandler.java index b3c630ae5c9..eb892f34985 100644 --- a/src/java.desktop/share/classes/java/beans/EventHandler.java +++ b/src/java.desktop/share/classes/java/beans/EventHandler.java @@ -28,9 +28,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Proxy; import java.lang.reflect.Method; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedAction; import sun.reflect.misc.MethodUtil; import sun.reflect.misc.ReflectUtil; @@ -281,8 +278,6 @@ public class EventHandler implements InvocationHandler { private String action; private final String eventPropertyName; private final String listenerMethodName; - @SuppressWarnings("removal") - private final AccessControlContext acc = AccessController.getContext(); /** * Creates a new {@code EventHandler} object; @@ -421,20 +416,7 @@ private Object applyGetters(Object target, String getters) { * * @see EventHandler */ - @SuppressWarnings("removal") public Object invoke(final Object proxy, final Method method, final Object[] arguments) { - AccessControlContext acc = this.acc; - if ((acc == null) && (System.getSecurityManager() != null)) { - throw new SecurityException("AccessControlContext is not set"); - } - return AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - return invokeInternal(proxy, method, arguments); - } - }, acc); - } - - private Object invokeInternal(Object proxy, Method method, Object[] arguments) { String methodName = method.getName(); if (method.getDeclaringClass() == Object.class) { // Handle the Object public methods. @@ -689,7 +671,7 @@ public static T create(Class listenerInterface, * @see EventHandler * @see Proxy#newProxyInstance */ - @SuppressWarnings("removal") + @SuppressWarnings("unchecked") public static T create(Class listenerInterface, Object target, String action, String eventPropertyName, @@ -705,12 +687,7 @@ public static T create(Class listenerInterface, } final ClassLoader loader = getClassLoader(listenerInterface); final Class[] interfaces = {listenerInterface}; - return AccessController.doPrivileged(new PrivilegedAction() { - @SuppressWarnings("unchecked") - public T run() { - return (T) Proxy.newProxyInstance(loader, interfaces, handler); - } - }); + return (T) Proxy.newProxyInstance(loader, interfaces, handler); } private static ClassLoader getClassLoader(Class type) { diff --git a/src/java.desktop/share/classes/java/beans/MetaData.java b/src/java.desktop/share/classes/java/beans/MetaData.java index e3cf55a85c5..0a12e7dcee8 100644 --- a/src/java.desktop/share/classes/java/beans/MetaData.java +++ b/src/java.desktop/share/classes/java/beans/MetaData.java @@ -41,9 +41,6 @@ import java.lang.reflect.Modifier; import java.lang.reflect.InvocationTargetException; -import java.security.AccessController; -import java.security.PrivilegedAction; - import java.util.*; import javax.swing.Box; @@ -1319,28 +1316,22 @@ private static Object getBeanAttribute(Class type, String attribute) { } } - @SuppressWarnings("removal") static Object getPrivateFieldValue(Object instance, String name) { Field field = fields.get(name); if (field == null) { int index = name.lastIndexOf('.'); final String className = name.substring(0, index); final String fieldName = name.substring(1 + index); - field = AccessController.doPrivileged(new PrivilegedAction() { - public Field run() { - try { - Field field = Class.forName(className).getDeclaredField(fieldName); - field.setAccessible(true); - return field; - } - catch (ClassNotFoundException exception) { - throw new IllegalStateException("Could not find class", exception); - } - catch (NoSuchFieldException exception) { - throw new IllegalStateException("Could not find field", exception); - } - } - }); + try { + field = Class.forName(className).getDeclaredField(fieldName); + field.setAccessible(true); + } + catch (ClassNotFoundException exception) { + throw new IllegalStateException("Could not find class", exception); + } + catch (NoSuchFieldException exception) { + throw new IllegalStateException("Could not find field", exception); + } fields.put(name, field); } try { diff --git a/src/java.desktop/share/classes/java/beans/SimpleBeanInfo.java b/src/java.desktop/share/classes/java/beans/SimpleBeanInfo.java index 34ca9d20403..7b6fd131c24 100644 --- a/src/java.desktop/share/classes/java/beans/SimpleBeanInfo.java +++ b/src/java.desktop/share/classes/java/beans/SimpleBeanInfo.java @@ -29,8 +29,6 @@ import java.awt.Toolkit; import java.awt.image.ImageProducer; import java.net.URL; -import java.security.AccessController; -import java.security.PrivilegedAction; /** * This is a support class to make it easier for people to provide @@ -154,10 +152,8 @@ public Image getIcon(final int iconKind) { * @return an image object. May be null if the load failed. * @see java.beans.SimpleBeanInfo#loadImage(String) */ - @SuppressWarnings("removal") private Image loadStandardImage(final String resourceName) { - return AccessController.doPrivileged( - (PrivilegedAction) () -> loadImage(resourceName)); + return loadImage(resourceName); } /** diff --git a/src/java.desktop/share/classes/java/beans/Statement.java b/src/java.desktop/share/classes/java/beans/Statement.java index d079a0b24a9..bf1c62be78b 100644 --- a/src/java.desktop/share/classes/java/beans/Statement.java +++ b/src/java.desktop/share/classes/java/beans/Statement.java @@ -29,10 +29,6 @@ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import com.sun.beans.finder.ClassFinder; import com.sun.beans.finder.ConstructorFinder; @@ -69,8 +65,6 @@ public void exceptionThrown(Exception e) { } }; - @SuppressWarnings("removal") - private final AccessControlContext acc = AccessController.getContext(); private final Object target; private final String methodName; private final Object[] arguments; @@ -174,28 +168,7 @@ public void execute() throws Exception { invoke(); } - @SuppressWarnings("removal") Object invoke() throws Exception { - AccessControlContext acc = this.acc; - if ((acc == null) && (System.getSecurityManager() != null)) { - throw new SecurityException("AccessControlContext is not set"); - } - try { - return AccessController.doPrivileged( - new PrivilegedExceptionAction() { - public Object run() throws Exception { - return invokeInternal(); - } - }, - acc - ); - } - catch (PrivilegedActionException exception) { - throw exception.getException(); - } - } - - private Object invokeInternal() throws Exception { Object target = getTarget(); String methodName = getMethodName(); diff --git a/src/java.desktop/share/classes/java/beans/XMLDecoder.java b/src/java.desktop/share/classes/java/beans/XMLDecoder.java index 8a7e6b9984a..febba84d2a1 100644 --- a/src/java.desktop/share/classes/java/beans/XMLDecoder.java +++ b/src/java.desktop/share/classes/java/beans/XMLDecoder.java @@ -29,9 +29,6 @@ import java.io.Closeable; import java.io.InputStream; import java.io.IOException; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedAction; import org.xml.sax.InputSource; import org.xml.sax.helpers.DefaultHandler; @@ -64,8 +61,6 @@ * @author Philip Milne */ public class XMLDecoder implements AutoCloseable { - @SuppressWarnings("removal") - private final AccessControlContext acc = AccessController.getContext(); private final DocumentHandler handler = new DocumentHandler(); private final InputSource input; private Object owner; @@ -189,21 +184,12 @@ private void close(Closeable in) { } } - @SuppressWarnings("removal") private boolean parsingComplete() { if (this.input == null) { return false; } if (this.array == null) { - if ((this.acc == null) && (null != System.getSecurityManager())) { - throw new SecurityException("AccessControlContext is not set"); - } - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - XMLDecoder.this.handler.parse(XMLDecoder.this.input); - return null; - } - }, this.acc); + XMLDecoder.this.handler.parse(XMLDecoder.this.input); this.array = this.handler.getObjects(); } return true; diff --git a/src/java.net.http/share/classes/java/net/http/HttpClient.java b/src/java.net.http/share/classes/java/net/http/HttpClient.java index c1269eed823..fbd2e2aba36 100644 --- a/src/java.net.http/share/classes/java/net/http/HttpClient.java +++ b/src/java.net.http/share/classes/java/net/http/HttpClient.java @@ -37,9 +37,6 @@ import java.net.InetSocketAddress; import java.net.Proxy; import java.net.ProxySelector; -import java.net.URLPermission; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.time.Duration; import java.util.Objects; import java.util.Optional; diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/Exchange.java b/src/java.net.http/share/classes/jdk/internal/net/http/Exchange.java index 1ff1e5f4733..71e4e05d2c5 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/Exchange.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/Exchange.java @@ -26,25 +26,15 @@ package jdk.internal.net.http; import java.io.IOException; -import java.net.InetSocketAddress; import java.net.ProtocolException; -import java.net.ProxySelector; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URLPermission; -import java.security.AccessControlContext; import java.time.Duration; -import java.util.List; -import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.net.http.HttpClient; -import java.net.http.HttpHeaders; import java.net.http.HttpResponse; import java.net.http.HttpTimeoutException; @@ -53,20 +43,11 @@ import jdk.internal.net.http.common.Utils; import jdk.internal.net.http.common.Log; -import static jdk.internal.net.http.common.Utils.permissionForProxy; - /** * One request/response exchange (handles 100/101 intermediate response also). * depth field used to track number of times a new request is being sent * for a given API request. If limit exceeded exception is thrown. * - * Security check is performed here: - * - uses AccessControlContext captured at API level - * - checks for appropriate URLPermission for request - * - if permission allowed, grants equivalent SocketPermission to call - * - in case of direct HTTP proxy, checks additionally for access to proxy - * (CONNECT proxying uses its own Exchange, so check done there) - * */ final class Exchange { @@ -83,8 +64,6 @@ final class Exchange { // used to record possible cancellation raised before the exchImpl // has been established. private volatile IOException failed; - @SuppressWarnings("removal") - final AccessControlContext acc; final MultiExchange multi; final Executor parentExecutor; volatile boolean upgrading; // to HTTP/2 @@ -103,22 +82,6 @@ final class Exchange { this.upgrading = false; this.client = multi.client(); this.multi = multi; - this.acc = multi.acc; - this.parentExecutor = multi.executor; - this.pushGroup = multi.pushGroup; - this.dbgTag = "Exchange"; - } - - /* If different AccessControlContext to be used */ - Exchange(HttpRequestImpl request, - MultiExchange multi, - @SuppressWarnings("removal") AccessControlContext acc) - { - this.request = request; - this.acc = acc; - this.upgrading = false; - this.client = multi.client(); - this.multi = multi; this.parentExecutor = multi.executor; this.pushGroup = multi.pushGroup; this.dbgTag = "Exchange"; @@ -338,7 +301,7 @@ private void checkCancelled() { } } - CompletableFuture checkCancelled(CompletableFuture cf, HttpConnection connection) { + CompletableFuture checkCancelled(CompletableFuture cf, HttpConnection connection) { return cf.handle((r,t) -> { if (t == null) { if (multi.requestCancelled()) { @@ -354,7 +317,7 @@ CompletableFuture checkCancelled(CompletableFuture cf, HttpConnection } catch (Throwable x) { if (debug.on()) debug.log("Failed to close connection", x); } - return MinimalFuture.failedFuture(t); + return MinimalFuture.failedFuture(t); } } } @@ -422,15 +385,6 @@ public CompletableFuture responseAsync() { return responseAsyncImpl(null); } - CompletableFuture responseAsyncImpl(HttpConnection connection) { - SecurityException e = checkPermissions(); - if (e != null) { - return MinimalFuture.failedFuture(e); - } else { - return responseAsyncImpl0(connection); - } - } - // check whether the headersSentCF was completed exceptionally with // ProxyAuthorizationRequired. If so the Response embedded in the // exception is returned. Otherwise we proceed. @@ -584,7 +538,7 @@ private CompletableFuture ignore1xxResponse(final Response rsp) { } } - CompletableFuture responseAsyncImpl0(HttpConnection connection) { + CompletableFuture responseAsyncImpl(HttpConnection connection) { Function, CompletableFuture> after407Check; bodyIgnored = null; if (request.expectContinue()) { @@ -735,109 +689,6 @@ HttpResponse.BodySubscriber ignoreBody(HttpResponse.ResponseInfo hdrs) { return MinimalFuture.completedFuture(resp); } - private URI getURIForSecurityCheck() { - URI u; - String method = request.method(); - InetSocketAddress authority = request.authority(); - URI uri = request.uri(); - - // CONNECT should be restricted at API level - if (method.equalsIgnoreCase("CONNECT")) { - try { - u = new URI("socket", - null, - authority.getHostString(), - authority.getPort(), - null, - null, - null); - } catch (URISyntaxException e) { - throw new InternalError(e); // shouldn't happen - } - } else { - u = uri; - } - return u; - } - - /** - * Returns the security permission required for the given details. - * If method is CONNECT, then uri must be of form "scheme://host:port" - */ - private static URLPermission permissionForServer(URI uri, - String method, - Map> headers) { - if (method.equals("CONNECT")) { - return new URLPermission(uri.toString(), "CONNECT"); - } else { - return Utils.permissionForServer(uri, method, headers.keySet().stream()); - } - } - - /** - * Performs the necessary security permission checks required to retrieve - * the response. Returns a security exception representing the denied - * permission, or null if all checks pass or there is no security manager. - */ - private SecurityException checkPermissions() { - String method = request.method(); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm == null || method.equals("CONNECT")) { - // tunneling will have a null acc, which is fine. The proxy - // permission check will have already been preformed. - return null; - } - - HttpHeaders userHeaders = request.getUserHeaders(); - URI u = getURIForSecurityCheck(); - URLPermission p = permissionForServer(u, method, userHeaders.map()); - - try { - assert acc != null; - sm.checkPermission(p, acc); - } catch (SecurityException e) { - return e; - } - String hostHeader = userHeaders.firstValue("Host").orElse(null); - if (hostHeader != null && !hostHeader.equalsIgnoreCase(u.getHost())) { - // user has set a Host header different to request URI - // must check that for URLPermission also - URI u1 = replaceHostInURI(u, hostHeader); - URLPermission p1 = permissionForServer(u1, method, userHeaders.map()); - try { - assert acc != null; - sm.checkPermission(p1, acc); - } catch (SecurityException e) { - return e; - } - } - ProxySelector ps = client.proxySelector(); - if (ps != null) { - if (!method.equals("CONNECT")) { - // a non-tunneling HTTP proxy. Need to check access - URLPermission proxyPerm = permissionForProxy(request.proxy()); - if (proxyPerm != null) { - try { - sm.checkPermission(proxyPerm, acc); - } catch (SecurityException e) { - return e; - } - } - } - } - return null; - } - - private static URI replaceHostInURI(URI u, String hostPort) { - StringBuilder sb = new StringBuilder(); - sb.append(u.getScheme()) - .append("://") - .append(hostPort) - .append(u.getRawPath()); - return URI.create(sb.toString()); - } - HttpClient.Version version() { return multi.version(); } diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/HttpClientBuilderImpl.java b/src/java.net.http/share/classes/jdk/internal/net/http/HttpClientBuilderImpl.java index c4157b3c74c..65e9210f9cb 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/HttpClientBuilderImpl.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/HttpClientBuilderImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -46,7 +46,6 @@ public class HttpClientBuilderImpl implements HttpClient.Builder { Authenticator authenticator; HttpClient.Version version; Executor executor; - // Security parameters SSLContext sslContext; SSLParameters sslParams; int priority = -1; diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/HttpClientImpl.java b/src/java.net.http/share/classes/jdk/internal/net/http/HttpClientImpl.java index e1f4ec16dcd..4d7518d4054 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/HttpClientImpl.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/HttpClientImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -48,10 +48,7 @@ import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; -import java.security.AccessControlContext; -import java.security.AccessController; import java.security.NoSuchAlgorithmException; -import java.security.PrivilegedAction; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.ArrayList; @@ -97,7 +94,6 @@ import jdk.internal.net.http.common.OperationTrackers.Trackable; import jdk.internal.net.http.common.OperationTrackers.Tracker; import jdk.internal.net.http.websocket.BuilderImpl; -import jdk.internal.misc.InnocuousThread; /** * Client implementation. Contains all configuration information and also @@ -131,16 +127,10 @@ private static final class DefaultThreadFactory implements ThreadFactory { namePrefix = "HttpClient-" + clientID + "-Worker-"; } - @SuppressWarnings("removal") @Override public Thread newThread(Runnable r) { String name = namePrefix + nextId.getAndIncrement(); - Thread t; - if (System.getSecurityManager() == null) { - t = new Thread(null, r, name, 0, false); - } else { - t = InnocuousThread.newThread(name, r); - } + Thread t = new Thread(null, r, name, 0, false); t.setDaemon(true); return t; } @@ -188,15 +178,9 @@ public void ensureExecutedAsync(Runnable command) { } } - @SuppressWarnings("removal") private void shutdown() { if (delegate instanceof ExecutorService service) { - PrivilegedAction action = () -> { - service.shutdown(); - return null; - }; - AccessController.doPrivileged(action, null, - new RuntimePermission("modifyThread")); + service.shutdown(); } } } @@ -336,7 +320,6 @@ static void abortPendingRequests(HttpClientImpl client, Throwable reason) { private final ConnectionPool connections; private final DelegatingExecutor delegatingExecutor; private final boolean isDefaultExecutor; - // Security parameters private final SSLContext sslContext; private final SSLParameters sslParams; private final SelectorManager selmgr; @@ -445,16 +428,6 @@ private HttpClientImpl(HttpClientBuilderImpl builder, SingleFacadeFactory facadeFactory) { id = CLIENT_IDS.incrementAndGet(); dbgTag = "HttpClientImpl(" + id +")"; - @SuppressWarnings("removal") - var sm = System.getSecurityManager(); - if (sm != null && builder.localAddr != null) { - // when a specific local address is configured, it will eventually - // lead to the SocketChannel.bind(...) call with an InetSocketAddress - // whose InetAddress is the local address and the port is 0. That ultimately - // leads to a SecurityManager.checkListen permission check for that port. - // so we do that security manager check here with port 0. - sm.checkListen(0); - } localAddr = builder.localAddr; if (builder.sslContext == null) { try { @@ -484,7 +457,7 @@ private HttpClientImpl(HttpClientBuilderImpl builder, Redirect.NEVER : builder.followRedirects; this.userProxySelector = builder.proxy; this.proxySelector = Optional.ofNullable(userProxySelector) - .orElseGet(HttpClientImpl::getDefaultProxySelector); + .orElseGet(ProxySelector::getDefault); if (debug.on()) debug.log("proxySelector is %s (user-supplied=%s)", this.proxySelector, userProxySelector != null); @@ -642,12 +615,6 @@ private static SSLParameters getDefaultParams(SSLContext ctx) { return params; } - @SuppressWarnings("removal") - private static ProxySelector getDefaultProxySelector() { - PrivilegedAction action = ProxySelector::getDefault; - return AccessController.doPrivileged(action); - } - // Returns the facade that was returned to the application code. // May be null if that facade is no longer referenced. final HttpClientFacade facade() { @@ -992,7 +959,6 @@ private void debugCompleted(String tag, long startNanos, HttpRequest req) { return sendAsync(userRequest, responseHandler, pushPromiseHandler, delegatingExecutor.delegate); } - @SuppressWarnings("removal") private CompletableFuture> sendAsync(HttpRequest userRequest, BodyHandler responseHandler, @@ -1012,11 +978,7 @@ private void debugCompleted(String tag, long startNanos, HttpRequest req) { return MinimalFuture.failedFuture(selmgr.selectorClosedException()); } - AccessControlContext acc = null; - if (System.getSecurityManager() != null) - acc = AccessController.getContext(); - - // Clone the, possibly untrusted, HttpRequest + // Clone the possibly untrusted HttpRequest HttpRequestImpl requestImpl = new HttpRequestImpl(userRequest, proxySelector); if (requestImpl.method().equals("CONNECT")) throw new IllegalArgumentException("Unsupported method CONNECT"); @@ -1049,8 +1011,7 @@ private void debugCompleted(String tag, long startNanos, HttpRequest req) { requestImpl, this, responseHandler, - pushPromiseHandler, - acc); + pushPromiseHandler); CompletableFuture> mexCf = mex.responseAsync(executor); CompletableFuture> res = mexCf.whenComplete((b,t) -> requestUnreference()); if (DEBUGELAPSED) { diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/HttpRequestImpl.java b/src/java.net.http/share/classes/jdk/internal/net/http/HttpRequestImpl.java index 839b6a6185d..bb794031508 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/HttpRequestImpl.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/HttpRequestImpl.java @@ -31,9 +31,6 @@ import java.net.Proxy; import java.net.ProxySelector; import java.net.URI; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.time.Duration; import java.util.List; import java.util.Locale; @@ -65,17 +62,13 @@ public class HttpRequestImpl extends HttpRequest implements WebSocketRequest { final boolean secure; final boolean expectContinue; private volatile boolean isWebSocket; - @SuppressWarnings("removal") - private volatile AccessControlContext acc; private final Duration timeout; // may be null private final Optional version; private volatile boolean userSetAuthorization; private volatile boolean userSetProxyAuthorization; private static String userAgent() { - PrivilegedAction pa = () -> System.getProperty("java.version"); - @SuppressWarnings("removal") - String version = AccessController.doPrivileged(pa); + String version = System.getProperty("java.version"); return "Java-http-client/" + version; } @@ -196,7 +189,6 @@ private HttpRequestImpl(URI uri, this.expectContinue = other.expectContinue; this.secure = uri.getScheme().toLowerCase(Locale.US).equals("https"); this.requestPublisher = mayHaveBody ? publisher(other) : null; // may be null - this.acc = other.acc; this.timeout = other.timeout; this.version = other.version(); this.authority = null; @@ -274,7 +266,6 @@ private HttpRequestImpl(HttpRequestImpl parent, HttpHeaders headers) this.expectContinue = parent.expectContinue; this.secure = parent.secure; this.requestPublisher = parent.requestPublisher; - this.acc = parent.acc; this.timeout = parent.timeout; this.version = parent.version; this.authority = null; @@ -395,7 +386,6 @@ public void setSystemHeader(String name, String value) { systemHeadersBuilder.setHeader(name, value); } - @SuppressWarnings("removal") InetSocketAddress getAddress() { URI uri = uri(); if (uri == null) { @@ -412,8 +402,7 @@ InetSocketAddress getAddress() { final String host = uri.getHost(); final int port = p; if (proxy() == null) { - PrivilegedAction pa = () -> new InetSocketAddress(host, port); - return AccessController.doPrivileged(pa); + return new InetSocketAddress(host, port); } else { return InetSocketAddress.createUnresolved(host, port); } diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/MultiExchange.java b/src/java.net.http/share/classes/jdk/internal/net/http/MultiExchange.java index 2c15a704ef9..a7fe5f19e02 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/MultiExchange.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/MultiExchange.java @@ -30,7 +30,6 @@ import java.net.ConnectException; import java.net.http.HttpConnectTimeoutException; import java.time.Duration; -import java.security.AccessControlContext; import java.util.List; import java.util.ListIterator; import java.util.Objects; @@ -79,8 +78,6 @@ class MultiExchange implements Cancelable { private final HttpRequest userRequest; // the user request private final HttpRequestImpl request; // a copy of the user request private final ConnectTimeoutTracker connectTimeout; // null if no timeout - @SuppressWarnings("removal") - final AccessControlContext acc; final HttpClientImpl client; final HttpResponse.BodyHandler responseHandler; final HttpClientImpl.DelegatingExecutor executor; @@ -155,8 +152,7 @@ Duration getRemaining() { HttpRequestImpl requestImpl, HttpClientImpl client, HttpResponse.BodyHandler responseHandler, - PushPromiseHandler pushPromiseHandler, - @SuppressWarnings("removal") AccessControlContext acc) { + PushPromiseHandler pushPromiseHandler) { this.previous = null; this.userRequest = userRequest; this.request = requestImpl; @@ -164,15 +160,11 @@ Duration getRemaining() { this.previousreq = null; this.client = client; this.filters = client.filterChain(); - this.acc = acc; this.executor = client.theExecutor(); this.responseHandler = responseHandler; if (pushPromiseHandler != null) { - Executor ensureExecutedAsync = this.executor::ensureExecutedAsync; - Executor executor = acc == null - ? ensureExecutedAsync - : new PrivilegedExecutor(ensureExecutedAsync, acc); + Executor executor = this.executor::ensureExecutedAsync; this.pushGroup = new PushGroup<>(pushPromiseHandler, request, executor); } else { pushGroup = null; @@ -470,7 +462,7 @@ private CompletableFuture responseAsyncImpl() { previousreq = currentreq; currentreq = newrequest; retriedOnce = false; - setExchange(new Exchange<>(currentreq, this, acc)); + setExchange(new Exchange<>(currentreq, this)); return responseAsyncImpl(); }).thenCompose(Function.identity()); } }) diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/PlainHttpConnection.java b/src/java.net.http/share/classes/jdk/internal/net/http/PlainHttpConnection.java index 1b42801e9ba..747945701f8 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/PlainHttpConnection.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/PlainHttpConnection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * 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,9 +32,6 @@ import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.locks.ReentrantLock; @@ -167,7 +164,6 @@ public void abort(IOException ioe) { } } - @SuppressWarnings("removal") @Override public CompletableFuture connectAsync(Exchange exchange) { CompletableFuture cf = new MinimalFuture<>(); @@ -191,14 +187,12 @@ public CompletableFuture connectAsync(Exchange exchange) { debug.log("binding to configured local address " + localAddr); } var sockAddr = new InetSocketAddress(localAddr, 0); - PrivilegedExceptionAction pa = () -> chan.bind(sockAddr); try { - AccessController.doPrivileged(pa); + chan.bind(sockAddr); if (debug.on()) { debug.log("bind completed " + localAddr); } - } catch (PrivilegedActionException e) { - var cause = e.getCause(); + } catch (IOException cause) { if (debug.on()) { debug.log("bind to " + localAddr + " failed: " + cause.getMessage()); } @@ -206,13 +200,7 @@ public CompletableFuture connectAsync(Exchange exchange) { } } - PrivilegedExceptionAction pa = - () -> chan.connect(Utils.resolveAddress(address)); - try { - finished = AccessController.doPrivileged(pa); - } catch (PrivilegedActionException e) { - throw e.getCause(); - } + finished = chan.connect(Utils.resolveAddress(address)); if (finished) { if (debug.on()) debug.log("connect finished without blocking"); if (connectionOpened()) { diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/PlainTunnelingConnection.java b/src/java.net.http/share/classes/jdk/internal/net/http/PlainTunnelingConnection.java index 4565514f577..80ca6ba8a3a 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/PlainTunnelingConnection.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/PlainTunnelingConnection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -72,7 +72,7 @@ public CompletableFuture connectAsync(Exchange exchange) { assert client != null; HttpRequestImpl req = new HttpRequestImpl("CONNECT", address, proxyHeaders); MultiExchange mulEx = new MultiExchange<>(null, req, - client, discarding(), null, null); + client, discarding(), null); Exchange connectExchange = mulEx.getExchange(); return connectExchange diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/PrivilegedExecutor.java b/src/java.net.http/share/classes/jdk/internal/net/http/PrivilegedExecutor.java deleted file mode 100644 index 72518f2c4e8..00000000000 --- a/src/java.net.http/share/classes/jdk/internal/net/http/PrivilegedExecutor.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package jdk.internal.net.http; - -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.Objects; -import java.util.concurrent.Executor; - -/** - * Executes tasks within a given access control context, and by a given executor. - */ -class PrivilegedExecutor implements Executor { - - /** The underlying executor. May be provided by the user. */ - final Executor executor; - /** The ACC to execute the tasks within. */ - @SuppressWarnings("removal") - final AccessControlContext acc; - - public PrivilegedExecutor(Executor executor, @SuppressWarnings("removal") AccessControlContext acc) { - Objects.requireNonNull(executor); - Objects.requireNonNull(acc); - this.executor = executor; - this.acc = acc; - } - - private static class PrivilegedRunnable implements Runnable { - private final Runnable r; - @SuppressWarnings("removal") - private final AccessControlContext acc; - PrivilegedRunnable(Runnable r, @SuppressWarnings("removal") AccessControlContext acc) { - this.r = r; - this.acc = acc; - } - @SuppressWarnings("removal") - @Override - public void run() { - PrivilegedAction pa = () -> { r.run(); return null; }; - AccessController.doPrivileged(pa, acc); - } - } - - @Override - public void execute(Runnable r) { - executor.execute(new PrivilegedRunnable(r, acc)); - } -} diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/RequestPublishers.java b/src/java.net.http/share/classes/jdk/internal/net/http/RequestPublishers.java index cfb0a20fe94..ecf88eb6566 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/RequestPublishers.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/RequestPublishers.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,6 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; -import java.io.FilePermission; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; @@ -37,11 +36,6 @@ import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.Permission; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; @@ -229,11 +223,6 @@ public void subscribe(Flow.Subscriber subscriber) { /** * Publishes the content of a given file. - *

- * Privileged actions are performed within a limited doPrivileged that only - * asserts the specific, read, file permission that was checked during the - * construction of this FilePublisher. This only applies if the file system - * that created the file provides interoperability with {@code java.io.File}. */ public static class FilePublisher implements BodyPublisher { @@ -241,62 +230,27 @@ public static class FilePublisher implements BodyPublisher { private final long length; private final Function inputStreamSupplier; - private static String pathForSecurityCheck(Path path) { - return path.toFile().getPath(); - } - /** * Factory for creating FilePublisher. - * - * Permission checks are performed here before construction of the - * FilePublisher. Permission checking and construction are deliberately - * and tightly co-located. */ public static FilePublisher create(Path path) throws FileNotFoundException { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - FilePermission filePermission = null; boolean defaultFS = true; try { - String fn = pathForSecurityCheck(path); - if (sm != null) { - FilePermission readPermission = new FilePermission(fn, "read"); - sm.checkPermission(readPermission); - filePermission = readPermission; - } + path.toFile().getPath(); } catch (UnsupportedOperationException uoe) { + // path not associated with the default file system provider defaultFS = false; - // Path not associated with the default file system - // Test early if an input stream can still be obtained - try { - if (sm != null) { - Files.newInputStream(path).close(); - } - } catch (IOException ioe) { - if (ioe instanceof FileNotFoundException) { - throw (FileNotFoundException) ioe; - } else { - var ex = new FileNotFoundException(ioe.getMessage()); - ex.initCause(ioe); - throw ex; - } - } } - // existence check must be after permission checks + // existence check must be after FS checks if (Files.notExists(path)) throw new FileNotFoundException(path + " not found"); - Permission perm = filePermission; - assert perm == null || perm.getActions().equals("read"); - @SuppressWarnings("removal") - AccessControlContext acc = sm != null ? - AccessController.getContext() : null; boolean finalDefaultFS = defaultFS; Function inputStreamSupplier = (p) -> - createInputStream(p, acc, perm, finalDefaultFS); + createInputStream(p, finalDefaultFS); long length; try { @@ -308,41 +262,17 @@ public static FilePublisher create(Path path) return new FilePublisher(path, length, inputStreamSupplier); } - @SuppressWarnings("removal") private static InputStream createInputStream(Path path, - AccessControlContext acc, - Permission perm, boolean defaultFS) { try { - if (acc != null) { - PrivilegedExceptionAction pa = defaultFS - ? () -> new FileInputStream(path.toFile()) - : () -> Files.newInputStream(path); - return perm != null - ? AccessController.doPrivileged(pa, acc, perm) - : AccessController.doPrivileged(pa, acc); - } else { - return defaultFS + return defaultFS ? new FileInputStream(path.toFile()) : Files.newInputStream(path); - } - } catch (PrivilegedActionException pae) { - throw toUncheckedException(pae.getCause()); } catch (IOException io) { throw new UncheckedIOException(io); } } - private static RuntimeException toUncheckedException(Throwable t) { - if (t instanceof RuntimeException) - throw (RuntimeException) t; - if (t instanceof Error) - throw (Error) t; - if (t instanceof IOException) - throw new UncheckedIOException((IOException) t); - throw new UndeclaredThrowableException(t); - } - private FilePublisher(Path name, long length, Function inputStreamSupplier) { diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/ResponseBodyHandlers.java b/src/java.net.http/share/classes/jdk/internal/net/http/ResponseBodyHandlers.java index 22e03238d21..79b2332ae37 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/ResponseBodyHandlers.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/ResponseBodyHandlers.java @@ -25,8 +25,6 @@ package jdk.internal.net.http; -import java.io.File; -import java.io.FilePermission; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; @@ -34,10 +32,8 @@ import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.Paths; -import java.security.AccessControlContext; -import java.security.AccessController; import java.util.List; -import java.util.Objects; + import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentMap; import java.util.function.Function; @@ -56,62 +52,31 @@ public final class ResponseBodyHandlers { private ResponseBodyHandlers() { } - private static final String pathForSecurityCheck(Path path) { - return path.toFile().getPath(); - } - /** * A Path body handler. */ public static class PathBodyHandler implements BodyHandler{ private final Path file; private final List openOptions; // immutable list - @SuppressWarnings("removal") - private final AccessControlContext acc; - private final FilePermission filePermission; /** * Factory for creating PathBodyHandler. - * - * Permission checks are performed here before construction of the - * PathBodyHandler. Permission checking and construction are - * deliberately and tightly co-located. */ public static PathBodyHandler create(Path file, List openOptions) { - FilePermission filePermission = null; - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - try { - String fn = pathForSecurityCheck(file); - FilePermission writePermission = new FilePermission(fn, "write"); - sm.checkPermission(writePermission); - filePermission = writePermission; - } catch (UnsupportedOperationException ignored) { - // path not associated with the default file system provider - } - } - assert filePermission == null || filePermission.getActions().equals("write"); - @SuppressWarnings("removal") - var acc = sm != null ? AccessController.getContext() : null; - return new PathBodyHandler(file, openOptions, acc, filePermission); + return new PathBodyHandler(file, openOptions); } private PathBodyHandler(Path file, - List openOptions, - @SuppressWarnings("removal") AccessControlContext acc, - FilePermission filePermission) { + List openOptions) { this.file = file; this.openOptions = openOptions; - this.acc = acc; - this.filePermission = filePermission; } @Override public BodySubscriber apply(ResponseInfo responseInfo) { - return new PathSubscriber(file, openOptions, acc, filePermission); + return new PathSubscriber(file, openOptions); } } @@ -170,44 +135,20 @@ public void applyPushPromise( public static class FileDownloadBodyHandler implements BodyHandler { private final Path directory; private final List openOptions; - @SuppressWarnings("removal") - private final AccessControlContext acc; - private final FilePermission[] filePermissions; // may be null /** * Factory for creating FileDownloadBodyHandler. - * - * Permission checks are performed here before construction of the - * FileDownloadBodyHandler. Permission checking and construction are - * deliberately and tightly co-located. */ public static FileDownloadBodyHandler create(Path directory, List openOptions) { - String fn; try { - fn = pathForSecurityCheck(directory); + directory.toFile().getPath(); } catch (UnsupportedOperationException uoe) { // directory not associated with the default file system provider throw new IllegalArgumentException("invalid path: " + directory, uoe); } - FilePermission filePermissions[] = null; - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - FilePermission writePermission = new FilePermission(fn, "write"); - String writePathPerm = fn + File.separatorChar + "*"; - FilePermission writeInDirPermission = new FilePermission(writePathPerm, "write"); - sm.checkPermission(writeInDirPermission); - FilePermission readPermission = new FilePermission(fn, "read"); - sm.checkPermission(readPermission); - - // read permission is only needed before determine the below checks - // only write permission is required when downloading to the file - filePermissions = new FilePermission[] { writePermission, writeInDirPermission }; - } - - // existence, etc, checks must be after permission checks + // existence, etc, checks must be after FS checks if (Files.notExists(directory)) throw new IllegalArgumentException("non-existent directory: " + directory); if (!Files.isDirectory(directory)) @@ -215,21 +156,13 @@ public static FileDownloadBodyHandler create(Path directory, if (!Files.isWritable(directory)) throw new IllegalArgumentException("non-writable directory: " + directory); - assert filePermissions == null || (filePermissions[0].getActions().equals("write") - && filePermissions[1].getActions().equals("write")); - @SuppressWarnings("removal") - var acc = sm != null ? AccessController.getContext() : null; - return new FileDownloadBodyHandler(directory, openOptions, acc, filePermissions); + return new FileDownloadBodyHandler(directory, openOptions); } private FileDownloadBodyHandler(Path directory, - List openOptions, - @SuppressWarnings("removal") AccessControlContext acc, - FilePermission... filePermissions) { + List openOptions) { this.directory = directory; this.openOptions = openOptions; - this.acc = acc; - this.filePermissions = filePermissions; } /** The "attachment" disposition-type and separator. */ @@ -394,7 +327,7 @@ public BodySubscriber apply(ResponseInfo responseInfo) { "Resulting file, " + file.toString() + ", outside of given directory"); } - return new PathSubscriber(file, openOptions, acc, filePermissions); + return new PathSubscriber(file, openOptions); } } } diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/ResponseSubscribers.java b/src/java.net.http/share/classes/jdk/internal/net/http/ResponseSubscribers.java index 09ad87f9205..04d019e4c81 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/ResponseSubscribers.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/ResponseSubscribers.java @@ -26,7 +26,6 @@ package jdk.internal.net.http; import java.io.BufferedReader; -import java.io.FilePermission; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -35,11 +34,6 @@ import java.nio.charset.Charset; import java.nio.file.OpenOption; import java.nio.file.Path; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -164,83 +158,31 @@ public void onComplete() { /** * A Subscriber that writes the flow of data to a given file. - * - * Privileged actions are performed within a limited doPrivileged that only - * asserts the specific, write, file permissions that were checked during - * the construction of this PathSubscriber. */ public static class PathSubscriber implements TrustedSubscriber { - - private static final FilePermission[] EMPTY_FILE_PERMISSIONS = new FilePermission[0]; - private final Path file; private final OpenOption[] options; - @SuppressWarnings("removal") - private final AccessControlContext acc; - private final FilePermission[] filePermissions; - private final boolean isDefaultFS; private final CompletableFuture result = new MinimalFuture<>(); private final AtomicBoolean subscribed = new AtomicBoolean(); private volatile Flow.Subscription subscription; private volatile FileChannel out; - private static final String pathForSecurityCheck(Path path) { - return path.toFile().getPath(); - } - /** * Factory for creating PathSubscriber. - * - * Permission checks are performed here before construction of the - * PathSubscriber. Permission checking and construction are deliberately - * and tightly co-located. */ public static PathSubscriber create(Path file, List options) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - FilePermission filePermission = null; - if (sm != null) { - try { - String fn = pathForSecurityCheck(file); - FilePermission writePermission = new FilePermission(fn, "write"); - sm.checkPermission(writePermission); - filePermission = writePermission; - } catch (UnsupportedOperationException ignored) { - // path not associated with the default file system provider - } - } - - assert filePermission == null || filePermission.getActions().equals("write"); - @SuppressWarnings("removal") - AccessControlContext acc = sm != null ? AccessController.getContext() : null; - return new PathSubscriber(file, options, acc, filePermission); + return new PathSubscriber(file, options); } // pp so handler implementations in the same package can construct /*package-private*/ PathSubscriber(Path file, - List options, - @SuppressWarnings("removal") AccessControlContext acc, - FilePermission... filePermissions) { + List options) { this.file = file; this.options = options.stream().toArray(OpenOption[]::new); - this.acc = acc; - this.filePermissions = filePermissions == null || filePermissions[0] == null - ? EMPTY_FILE_PERMISSIONS : filePermissions; - this.isDefaultFS = isDefaultFS(file); - } - - private static boolean isDefaultFS(Path file) { - try { - file.toFile(); - return true; - } catch (UnsupportedOperationException uoe) { - return false; - } } - @SuppressWarnings("removal") @Override public void onSubscribe(Flow.Subscription subscription) { Objects.requireNonNull(subscription); @@ -250,31 +192,12 @@ public void onSubscribe(Flow.Subscription subscription) { } this.subscription = subscription; - if (acc == null) { - try { - out = FileChannel.open(file, options); - } catch (IOException ioe) { - result.completeExceptionally(ioe); - subscription.cancel(); - return; - } - } else { - try { - PrivilegedExceptionAction pa = - () -> FileChannel.open(file, options); - out = isDefaultFS - ? AccessController.doPrivileged(pa, acc, filePermissions) - : AccessController.doPrivileged(pa, acc); - } catch (PrivilegedActionException pae) { - Throwable t = pae.getCause() != null ? pae.getCause() : pae; - result.completeExceptionally(t); - subscription.cancel(); - return; - } catch (Exception e) { - result.completeExceptionally(e); - subscription.cancel(); - return; - } + try { + out = FileChannel.open(file, options); + } catch (IOException ioe) { + result.completeExceptionally(ioe); + subscription.cancel(); + return; } subscription.request(1); } @@ -311,21 +234,8 @@ public CompletionStage getBody() { return result; } - @SuppressWarnings("removal") private void close() { - if (acc == null) { - Utils.close(out); - } else { - PrivilegedAction pa = () -> { - Utils.close(out); - return null; - }; - if (isDefaultFS) { - AccessController.doPrivileged(pa, acc, filePermissions); - } else { - AccessController.doPrivileged(pa, acc); - } - } + Utils.close(out); } } diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/common/ImmutableExtendedSSLSession.java b/src/java.net.http/share/classes/jdk/internal/net/http/common/ImmutableExtendedSSLSession.java index bb6540e44b9..2a5f125c0c4 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/common/ImmutableExtendedSSLSession.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/common/ImmutableExtendedSSLSession.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,6 @@ import java.security.Principal; import java.util.List; -import javax.net.ssl.SSLSession; import javax.net.ssl.ExtendedSSLSession; import javax.net.ssl.SSLSessionContext; import javax.net.ssl.SSLPeerUnverifiedException; diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/common/Utils.java b/src/java.net.http/share/classes/jdk/internal/net/http/common/Utils.java index ef5af764e76..511b17d7813 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/common/Utils.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/common/Utils.java @@ -39,8 +39,6 @@ import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.URI; -import java.net.URLPermission; -import java.net.http.HttpClient; import java.net.http.HttpHeaders; import java.net.http.HttpTimeoutException; import java.nio.ByteBuffer; @@ -51,8 +49,6 @@ import java.nio.charset.Charset; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.text.Normalizer; import java.util.Arrays; import java.util.Collection; @@ -100,10 +96,7 @@ public final class Utils { // public static final boolean TESTING; // static { -// if (ASSERTIONSENABLED) { -// PrivilegedAction action = () -> System.getProperty("test.src"); -// TESTING = AccessController.doPrivileged(action) != null; -// } else TESTING = false; +// TESTING = ASSERTIONSENABLED ? System.getProperty("test.src") != null : false; // } public static final LoggerConfig DEBUG_CONFIG = getLoggerConfig(DebugLogger.HTTP_NAME, LoggerConfig.OFF); @@ -120,9 +113,7 @@ public final class Utils { hostnameVerificationDisabledValue(); private static LoggerConfig getLoggerConfig(String loggerName, LoggerConfig def) { - PrivilegedAction action = () -> System.getProperty(loggerName); - @SuppressWarnings("removal") - var prop = AccessController.doPrivileged(action); + var prop = System.getProperty(loggerName); if (prop == null) return def; var config = LoggerConfig.OFF; for (var s : prop.split(",")) { @@ -449,41 +440,6 @@ public static Throwable wrapWithExtraDetail(Throwable t, private Utils() { } - /** - * Returns the security permissions required to connect to the proxy, or - * {@code null} if none is required or applicable. - */ - public static URLPermission permissionForProxy(InetSocketAddress proxyAddress) { - if (proxyAddress == null) - return null; - - StringBuilder sb = new StringBuilder(); - sb.append("socket://") - .append(proxyAddress.getHostString()).append(":") - .append(proxyAddress.getPort()); - String urlString = sb.toString(); - return new URLPermission(urlString, "CONNECT"); - } - - /** - * Returns the security permission required for the given details. - */ - public static URLPermission permissionForServer(URI uri, - String method, - Stream headers) { - String urlString = new StringBuilder() - .append(uri.getScheme()).append("://") - .append(uri.getRawAuthority()) - .append(uri.getRawPath()).toString(); - - StringBuilder actionStringBuilder = new StringBuilder(method); - String collected = headers.collect(joining(",")); - if (!collected.isEmpty()) { - actionStringBuilder.append(":").append(collected); - } - return new URLPermission(urlString, actionStringBuilder.toString()); - } - private static final boolean[] LOWER_CASE_CHARS = new boolean[128]; // ABNF primitives defined in RFC 7230 @@ -587,34 +543,24 @@ public static boolean isValidValue(String token) { return true; } - @SuppressWarnings("removal") public static int getIntegerNetProperty(String name, int defaultValue) { - return AccessController.doPrivileged((PrivilegedAction) () -> - NetProperties.getInteger(name, defaultValue)); + return NetProperties.getInteger(name, defaultValue); } - @SuppressWarnings("removal") public static String getNetProperty(String name) { - return AccessController.doPrivileged((PrivilegedAction) () -> - NetProperties.get(name)); + return NetProperties.get(name); } - @SuppressWarnings("removal") public static boolean getBooleanProperty(String name, boolean def) { - return AccessController.doPrivileged((PrivilegedAction) () -> - Boolean.parseBoolean(System.getProperty(name, String.valueOf(def)))); + return Boolean.parseBoolean(System.getProperty(name, String.valueOf(def))); } - @SuppressWarnings("removal") public static String getProperty(String name) { - return AccessController.doPrivileged((PrivilegedAction) () -> - System.getProperty(name)); + return System.getProperty(name); } - @SuppressWarnings("removal") public static int getIntegerProperty(String name, int defaultValue) { - return AccessController.doPrivileged((PrivilegedAction) () -> - Integer.parseInt(System.getProperty(name, String.valueOf(defaultValue)))); + return Integer.parseInt(System.getProperty(name, String.valueOf(defaultValue))); } public static int getIntegerNetProperty(String property, int min, int max, int defaultValue, boolean log) { diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/hpack/HPACK.java b/src/java.net.http/share/classes/jdk/internal/net/http/hpack/HPACK.java index abecde71665..d49b8c391cb 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/hpack/HPACK.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/hpack/HPACK.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. * 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,8 +28,6 @@ import jdk.internal.net.http.hpack.HPACK.Logger.Level; import java.nio.ByteBuffer; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Map; import java.util.ResourceBundle; import java.util.function.Supplier; @@ -52,9 +50,7 @@ public final class HPACK { static { String PROPERTY = "jdk.internal.httpclient.hpack.log.level"; - @SuppressWarnings("removal") - String value = AccessController.doPrivileged( - (PrivilegedAction) () -> System.getProperty(PROPERTY)); + String value = System.getProperty(PROPERTY); if (value == null) { LOGGER = new RootLogger(NONE); diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/websocket/OpeningHandshake.java b/src/java.net.http/share/classes/jdk/internal/net/http/websocket/OpeningHandshake.java index f88ec774dc0..c1c0853504c 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/websocket/OpeningHandshake.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/websocket/OpeningHandshake.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,17 +39,13 @@ import jdk.internal.net.http.common.Utils; import java.io.IOException; -import java.net.InetSocketAddress; import java.net.Proxy; import java.net.ProxySelector; import java.net.URI; import java.net.URISyntaxException; -import java.net.URLPermission; import java.nio.charset.StandardCharsets; -import java.security.AccessController; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.security.PrivilegedAction; import java.security.SecureRandom; import java.time.Duration; import java.util.Base64; @@ -61,11 +57,9 @@ import java.util.Set; import java.util.TreeSet; import java.util.concurrent.CompletableFuture; -import java.util.stream.Stream; import static java.lang.String.format; import static jdk.internal.net.http.common.Utils.isValidName; -import static jdk.internal.net.http.common.Utils.permissionForProxy; import static jdk.internal.net.http.common.Utils.stringOf; public class OpeningHandshake { @@ -112,7 +106,6 @@ public class OpeningHandshake { public OpeningHandshake(BuilderImpl b) { checkURI(b.getUri()); Proxy proxy = proxyFor(b.getProxySelector(), b.getUri()); - checkPermissions(b, proxy); this.client = b.getClient(); URI httpURI = createRequestURI(b.getUri()); HttpRequestBuilderImpl requestBuilder = new HttpRequestBuilderImpl(httpURI); @@ -185,12 +178,9 @@ static URI createRequestURI(URI uri) { } } - @SuppressWarnings("removal") public CompletableFuture send() { - PrivilegedAction> pa = () -> - client.sendAsync(this.request, BodyHandlers.ofString()) + return client.sendAsync(this.request, BodyHandlers.ofString()) .thenCompose(this::resultFrom); - return AccessController.doPrivileged(pa); } /* @@ -376,27 +366,4 @@ private static Proxy proxyFor(Optional selector, URI uri) { return proxy; } - /** - * Performs the necessary security permissions checks to connect ( possibly - * through a proxy ) to the builders WebSocket URI. - * - * @throws SecurityException if the security manager denies access - */ - static void checkPermissions(BuilderImpl b, Proxy proxy) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm == null) { - return; - } - Stream headers = b.getHeaders().stream().map(p -> p.first).distinct(); - URLPermission perm1 = Utils.permissionForServer(b.getUri(), "", headers); - sm.checkPermission(perm1); - if (proxy == null) { - return; - } - URLPermission perm2 = permissionForProxy((InetSocketAddress) proxy.address()); - if (perm2 != null) { - sm.checkPermission(perm2); - } - } } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Kinds.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Kinds.java index e5d9a9e2ac4..2491cd31f0d 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Kinds.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Kinds.java @@ -70,7 +70,6 @@ public enum Kind { AMBIGUOUS(Category.RESOLUTION_TARGET), // overloaded target HIDDEN(Category.RESOLUTION_TARGET), // not overloaded non-target STATICERR(Category.RESOLUTION_TARGET), // overloaded? target - MISSING_ENCL(Category.RESOLUTION), // not overloaded non-target BAD_RESTRICTED_TYPE(Category.RESOLUTION), // not overloaded non-target ABSENT_VAR(Category.RESOLUTION_TARGET, KindName.VAR), // not overloaded non-target WRONG_MTHS(Category.RESOLUTION_TARGET, KindName.METHOD), // overloaded target diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Lint.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Lint.java index 67f14941532..77cdd248c57 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Lint.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Lint.java @@ -181,7 +181,7 @@ public enum LintCategory { CLASSFILE("classfile"), /** - * Warn about"dangling" documentation comments, + * Warn about "dangling" documentation comments, * not attached to any declaration. */ DANGLING_DOC_COMMENTS("dangling-doc-comments"), 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 3fe5b9ba8ec..4bec78a8b40 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 @@ -2618,8 +2618,7 @@ public void visitApply(JCMethodInvocation tree) { } else if (methName == names._super) { // qualifier omitted; check for existence // of an appropriate implicit qualifier. - rs.resolveImplicitThis(tree.meth.pos(), - localEnv, site, true); + checkNewInnerClass(tree.meth.pos(), localEnv, site, true); } } else if (tree.meth.hasTag(SELECT)) { log.error(tree.meth.pos(), @@ -2826,11 +2825,9 @@ public void visitNewClass(final JCNewClass tree) { log.error(tree.encl.pos(), Errors.QualifiedNewOfStaticClass(clazztype.tsym)); } } - } else if (!clazztype.tsym.isInterface() && - (clazztype.tsym.flags_field & NOOUTERTHIS) == 0 && - clazztype.getEnclosingType().hasTag(CLASS)) { + } else { // Check for the existence of an apropos outer instance - rs.resolveImplicitThis(tree.pos(), env, clazztype); + checkNewInnerClass(tree.pos(), env, clazztype, false); } // Attribute constructor arguments. @@ -3095,6 +3092,24 @@ public void report(DiagnosticPosition _unused, JCDiagnostic details) { }; } + void checkNewInnerClass(DiagnosticPosition pos, Env env, Type type, boolean isSuper) { + boolean isLocal = type.tsym.owner.kind == MTH; + if ((type.tsym.flags() & (INTERFACE | ENUM | RECORD)) != 0 || + (!isLocal && !type.tsym.isInner()) || + (isSuper && env.enclClass.sym.isAnonymous())) { + // nothing to check + return; + } + Symbol res = isLocal ? + rs.findLocalClassOwner(env, type.tsym) : + rs.findSelfContaining(pos, env, type.getEnclosingType().tsym, isSuper); + if (res.exists()) { + rs.accessBase(res, pos, env.enclClass.sym.type, names._this, true); + } else { + log.error(pos, Errors.EnclClassRequired(type.tsym)); + } + } + /** Make an attributed null check tree. */ public JCExpression makeNullCheck(JCExpression arg) { @@ -3667,7 +3682,6 @@ public void visitReference(final JCMemberReference that) { boolean targetError; switch (refSym.kind) { case ABSENT_MTH: - case MISSING_ENCL: targetError = false; break; case WRONG_MTH: @@ -3718,11 +3732,7 @@ public void visitReference(final JCMemberReference that) { } if (!env.info.attributionMode.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) { - Type enclosingType = exprType.getEnclosingType(); - if (enclosingType != null && enclosingType.hasTag(CLASS)) { - // Check for the existence of an appropriate outer instance - rs.resolveImplicitThis(that.pos(), env, exprType); - } + checkNewInnerClass(that.pos(), env, exprType, false); } if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) { diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java index 2c7febf1496..ff3f675fe04 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java @@ -3764,11 +3764,10 @@ class ConstructorReferenceLookupHelper extends ReferenceLookupHelper { @Override protected Symbol lookup(Env env, MethodResolutionPhase phase) { - Symbol sym = needsInference ? + return needsInference ? findDiamond(env, site, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()) : findMethod(env, site, name, argtypes, typeargtypes, phase.isBoxingRequired(), phase.isVarargsRequired()); - return enclosingInstanceMissing(env, site) ? new BadConstructorReferenceError(sym) : sym; } @Override @@ -3813,6 +3812,63 @@ Symbol lookupMethod(Env env, DiagnosticPosition pos, Symbol locatio } } + /** + * Find a "valid" reference to an enclosing 'A.this' such that A is a subclass of the provided class symbol. + * A reference to an enclosing 'A.this' is "valid" if (a) we're not in the early-construction context for A + * and (b) if the current class is not an inner class of A. + */ + Symbol findSelfContaining(DiagnosticPosition pos, + Env env, + TypeSymbol c, + boolean isSuper) { + Env env1 = isSuper ? env.outer : env; + boolean staticOnly = false; + while (env1.outer != null) { + if (isStatic(env1)) staticOnly = true; + if (env1.enclClass.sym.isSubClass(c, types)) { + Symbol sym = env1.info.scope.findFirst(names._this); + if (sym != null) { + if (staticOnly) { + // current class is not an inner class, stop search + return new StaticError(sym); + } else if (env1.info.ctorPrologue && !isAllowedEarlyReference(pos, env1, (VarSymbol)sym)) { + // early construction context, stop search + return new RefBeforeCtorCalledError(sym); + } else { + // found it + return sym; + } + } + } + if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true; + env1 = env1.outer; + } + return varNotFound; + } + + /** + * Resolve the (method) owner of a local class. This can fail if the local class + * is referenced from a static context nested inside the local class. Effectively, + * this lookup succeeds if we can access a local variable declared inside the owner + * method from the provided env. + */ + Symbol findLocalClassOwner(Env env, TypeSymbol c) { + Symbol owner = c.owner; + Assert.check(owner.kind == MTH); + Env env1 = env; + boolean staticOnly = false; + while (env1.outer != null) { + if (env1.info.scope.owner == owner) { + return (staticOnly) ? + new BadLocalClassCreation(c) : + owner; + } + if (isStatic(env1)) staticOnly = true; + env1 = env1.outer; + } + return methodNotFound; + } + /** * Resolve `c.name' where name == this or name == super. * @param pos The position to use for error reporting. @@ -3837,15 +3893,15 @@ Symbol resolveSelf(DiagnosticPosition pos, else if (env1.info.ctorPrologue && !isAllowedEarlyReference(pos, env1, (VarSymbol)sym)) sym = new RefBeforeCtorCalledError(sym); return accessBase(sym, pos, env.enclClass.sym.type, - name, true); + name, true); } } if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true; env1 = env1.outer; } if (c.isInterface() && - name == names._super && !isStatic(env) && - types.isDirectSuperInterface(c, env.enclClass.sym)) { + name == names._super && !isStatic(env) && + types.isDirectSuperInterface(c, env.enclClass.sym)) { //this might be a default super call if one of the superinterfaces is 'c' for (Type t : pruneInterfaces(env.enclClass.type)) { if (t.tsym == c) { @@ -3860,8 +3916,8 @@ else if (env1.info.ctorPrologue && !isAllowedEarlyReference(pos, env1, (VarSymbo for (Type i : types.directSupertypes(env.enclClass.type)) { if (i.tsym.isSubClass(c, types) && i.tsym != c) { log.error(pos, - Errors.IllegalDefaultSuperCall(c, - Fragments.RedundantSupertype(c, i))); + Errors.IllegalDefaultSuperCall(c, + Fragments.RedundantSupertype(c, i))); return syms.errSymbol; } } @@ -3968,76 +4024,6 @@ public boolean isEarlyReference(Env env, JCTree base, VarSymbol v) (base == null || TreeInfo.isExplicitThisReference(types, (ClassType)env.enclClass.type, base)); } - /** - * Resolve `c.this' for an enclosing class c that contains the - * named member. - * @param pos The position to use for error reporting. - * @param env The environment current at the expression. - * @param member The member that must be contained in the result. - */ - Symbol resolveSelfContaining(DiagnosticPosition pos, - Env env, - Symbol member, - boolean isSuperCall) { - Symbol sym = resolveSelfContainingInternal(env, member, isSuperCall); - if (sym == null) { - log.error(pos, Errors.EnclClassRequired(member)); - return syms.errSymbol; - } else { - return accessBase(sym, pos, env.enclClass.sym.type, sym.name, true); - } - } - - boolean enclosingInstanceMissing(Env env, Type type) { - if (type.hasTag(CLASS) && type.getEnclosingType().hasTag(CLASS)) { - Symbol encl = resolveSelfContainingInternal(env, type.tsym, false); - return encl == null || encl.kind.isResolutionError(); - } - return false; - } - - private Symbol resolveSelfContainingInternal(Env env, - Symbol member, - boolean isSuperCall) { - Name name = names._this; - Env env1 = isSuperCall ? env.outer : env; - boolean staticOnly = false; - if (env1 != null) { - while (env1 != null && env1.outer != null) { - if (isStatic(env1)) staticOnly = true; - if (env1.enclClass.sym.isSubClass(member.owner.enclClass(), types)) { - Symbol sym = env1.info.scope.findFirst(name); - if (sym != null) { - if (staticOnly) sym = new StaticError(sym); - return sym; - } - } - if ((env1.enclClass.sym.flags() & STATIC) != 0) - staticOnly = true; - env1 = env1.outer; - } - } - return null; - } - - /** - * Resolve an appropriate implicit this instance for t's container. - * JLS 8.8.5.1 and 15.9.2 - */ - Type resolveImplicitThis(DiagnosticPosition pos, Env env, Type t) { - return resolveImplicitThis(pos, env, t, false); - } - - Type resolveImplicitThis(DiagnosticPosition pos, Env env, Type t, boolean isSuperCall) { - Type thisType = (t.tsym.owner.kind.matches(KindSelector.VAL_MTH) - ? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this) - : resolveSelfContaining(pos, env, t.tsym, isSuperCall)).type; - if (env.info.ctorPrologue && thisType.tsym == env.enclClass.sym) { - log.error(pos, Errors.CantRefBeforeCtorCalled(names._this)); - } - return thisType; - } - /* *************************************************************************** * ResolveError classes, indicating error situations when accessing symbols ****************************************************************************/ @@ -4760,6 +4746,28 @@ JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, } } + /** + * Specialization of {@link StaticError} for illegal + * creation of local class instances from a static context. + */ + class BadLocalClassCreation extends StaticError { + BadLocalClassCreation(Symbol sym) { + super(sym, "bad local class creation"); + } + + @Override + JCDiagnostic getDiagnostic(JCDiagnostic.DiagnosticType dkind, + DiagnosticPosition pos, + Symbol location, + Type site, + Name name, + List argtypes, + List typeargtypes) { + return diags.create(dkind, log.currentSource(), pos, + "local.cant.be.inst.static", kindName(sym), sym); + } + } + /** * Specialization of {@link InvalidSymbolError} for illegal * early accesses within a constructor prologue. @@ -4919,23 +4927,6 @@ JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol } } - /** - * BadConstructorReferenceError error class indicating that a constructor reference symbol has been found, - * but pointing to a class for which an enclosing instance is not available. - */ - class BadConstructorReferenceError extends InvalidSymbolError { - - public BadConstructorReferenceError(Symbol sym) { - super(MISSING_ENCL, sym, "BadConstructorReferenceError"); - } - - @Override - JCDiagnostic getDiagnostic(DiagnosticType dkind, DiagnosticPosition pos, Symbol location, Type site, Name name, List argtypes, List typeargtypes) { - return diags.create(dkind, log.currentSource(), pos, - "cant.access.inner.cls.constr", site.tsym.name, argtypes, site.getEnclosingType()); - } - } - class BadClassFileError extends InvalidSymbolError { private final CompletionFailure ex; 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 52c2987339b..4eafda8fc93 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 @@ -679,7 +679,8 @@ void reportDanglingDocComment(Comment c) { var pos = c.getPos(); if (pos != null) { deferredLintHandler.report(lint -> { - if (lint.isEnabled(Lint.LintCategory.DANGLING_DOC_COMMENTS)) { + if (lint.isEnabled(Lint.LintCategory.DANGLING_DOC_COMMENTS) && + !shebang(c, pos)) { log.warning(Lint.LintCategory.DANGLING_DOC_COMMENTS, pos, Warnings.DanglingDocComment); } @@ -687,6 +688,14 @@ void reportDanglingDocComment(Comment c) { } } + /** Returns true for a comment that acts similarly to shebang in UNIX */ + private boolean shebang(Comment c, JCDiagnostic.DiagnosticPosition pos) { + var src = log.currentSource(); + return c.getStyle() == Comment.CommentStyle.JAVADOC_LINE && + c.getPos().getStartPosition() == 0 && + src.getLineNumber(pos.getEndPosition(src.getEndPosTable())) == 1; + } + /** * Ignores any recent documentation comments found by the scanner, * such as those that cannot be associated with a nearby declaration. diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties b/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties index e9a5d80c935..3dc43bfdd94 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties @@ -1095,11 +1095,6 @@ compiler.misc.not.def.access.class.intf.cant.access.reason=\ {1}.{0} in package {2} is not accessible\n\ ({3}) -# 0: symbol, 1: list of type, 2: type -compiler.misc.cant.access.inner.cls.constr=\ - cannot access constructor {0}({1})\n\ - an enclosing instance of type {2} is not in scope - # 0: symbol, 1: symbol compiler.err.not.def.public.cant.access=\ {0} is not public in {1}; cannot be accessed from outside package @@ -2892,6 +2887,11 @@ compiler.err.abstract.cant.be.accessed.directly=\ compiler.err.non-static.cant.be.ref=\ non-static {0} {1} cannot be referenced from a static context +## The first argument ({0}) is a "kindname". +# 0: symbol kind, 1: symbol +compiler.err.local.cant.be.inst.static=\ + local {0} {1} cannot be instantiated from a static context + # 0: symbol kind, 1: symbol compiler.misc.bad.static.method.in.unbound.lookup=\ unexpected static {0} {1} found in unbound lookup diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyStore.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyStore.java index 4e352bf4950..41580151f2b 100644 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyStore.java +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/CKeyStore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. * 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,15 +29,12 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.security.AccessController; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyStoreSpi; import java.security.KeyStoreException; -import java.security.PrivilegedAction; import java.security.UnrecoverableKeyException; import java.security.NoSuchAlgorithmException; -import java.security.SecurityPermission; import java.security.cert.X509Certificate; import java.security.cert.Certificate; import java.security.cert.CertificateException; @@ -242,9 +239,7 @@ public void delete() throws KeyStoreException { CKeyStore(String storeName, int storeLocation) { // Get the compatibility mode - @SuppressWarnings("removal") - String prop = AccessController.doPrivileged( - (PrivilegedAction) () -> System.getProperty(KEYSTORE_COMPATIBILITY_MODE_PROP)); + String prop = System.getProperty(KEYSTORE_COMPATIBILITY_MODE_PROP); if ("false".equalsIgnoreCase(prop)) { keyStoreCompatibilityMode = false; @@ -695,10 +690,6 @@ public void engineStore(OutputStream stream, char[] password) * the integrity of the keystore cannot be found * @exception CertificateException if any of the certificates in the * keystore could not be loaded - * @exception SecurityException if the security check for - * SecurityPermission("authProvider.name") does not - * pass, where name is the value returned by - * this provider's getName method. */ public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { @@ -710,16 +701,6 @@ public void engineLoad(InputStream stream, char[] password) throw new IOException("Keystore password must be null"); } - /* - * Use the same security check as AuthProvider.login - */ - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(new SecurityPermission( - "authProvider.SunMSCAPI")); - } - // Clear all key entries entries.clear(); diff --git a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java index e57fe331f28..8ee16cf6bb8 100644 --- a/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java +++ b/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. * 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,8 +25,6 @@ package sun.security.mscapi; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.security.Provider; import java.security.NoSuchAlgorithmException; import java.security.InvalidParameterException; @@ -50,14 +48,14 @@ public final class SunMSCAPI extends Provider { private static final String INFO = "Sun's Microsoft Crypto API provider"; static { - @SuppressWarnings({"removal", "restricted"}) - var dummy = AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - System.loadLibrary("sunmscapi"); - return null; - } - }); + loadLibrary(); + } + + @SuppressWarnings("restricted") + private static void loadLibrary() { + System.loadLibrary("sunmscapi"); } + private static class ProviderServiceA extends ProviderService { ProviderServiceA(Provider p, String type, String algo, String cn, HashMap attrs) { @@ -148,119 +146,113 @@ public Object newInstance(Object ctrParamObj) } } - @SuppressWarnings("removal") public SunMSCAPI() { super("SunMSCAPI", PROVIDER_VER, INFO); final Provider p = this; - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - /* - * Secure random - */ - HashMap srattrs = new HashMap<>(1); - srattrs.put("ThreadSafe", "true"); - putService(new ProviderService(p, "SecureRandom", - "Windows-PRNG", "sun.security.mscapi.PRNG", - null, srattrs)); + /* + * Secure random + */ + HashMap srattrs = new HashMap<>(1); + srattrs.put("ThreadSafe", "true"); + putService(new ProviderService(p, "SecureRandom", + "Windows-PRNG", "sun.security.mscapi.PRNG", + null, srattrs)); - /* - * Key store - */ - putService(new ProviderService(p, "KeyStore", - "Windows-MY", "sun.security.mscapi.CKeyStore$MY")); - putService(new ProviderService(p, "KeyStore", - "Windows-MY-CURRENTUSER", "sun.security.mscapi.CKeyStore$MY")); - putService(new ProviderService(p, "KeyStore", - "Windows-ROOT", "sun.security.mscapi.CKeyStore$ROOT")); - putService(new ProviderService(p, "KeyStore", - "Windows-ROOT-CURRENTUSER", "sun.security.mscapi.CKeyStore$ROOT")); - putService(new ProviderService(p, "KeyStore", - "Windows-MY-LOCALMACHINE", "sun.security.mscapi.CKeyStore$MYLocalMachine")); - putService(new ProviderService(p, "KeyStore", - "Windows-ROOT-LOCALMACHINE", "sun.security.mscapi.CKeyStore$ROOTLocalMachine")); + /* + * Key store + */ + putService(new ProviderService(p, "KeyStore", + "Windows-MY", "sun.security.mscapi.CKeyStore$MY")); + putService(new ProviderService(p, "KeyStore", + "Windows-MY-CURRENTUSER", "sun.security.mscapi.CKeyStore$MY")); + putService(new ProviderService(p, "KeyStore", + "Windows-ROOT", "sun.security.mscapi.CKeyStore$ROOT")); + putService(new ProviderService(p, "KeyStore", + "Windows-ROOT-CURRENTUSER", "sun.security.mscapi.CKeyStore$ROOT")); + putService(new ProviderService(p, "KeyStore", + "Windows-MY-LOCALMACHINE", "sun.security.mscapi.CKeyStore$MYLocalMachine")); + putService(new ProviderService(p, "KeyStore", + "Windows-ROOT-LOCALMACHINE", "sun.security.mscapi.CKeyStore$ROOTLocalMachine")); - /* - * Signature engines - */ - HashMap attrs = new HashMap<>(1); - attrs.put("SupportedKeyClasses", "sun.security.mscapi.CKey"); + /* + * Signature engines + */ + HashMap attrs = new HashMap<>(1); + attrs.put("SupportedKeyClasses", "sun.security.mscapi.CKey"); - // NONEwithRSA must be supplied with a pre-computed message digest. - // Only the following digest algorithms are supported: MD5, SHA-1, - // SHA-256, SHA-384, SHA-512 and a special-purpose digest - // algorithm which is a concatenation of SHA-1 and MD5 digests. - putService(new ProviderService(p, "Signature", - "NONEwithRSA", "sun.security.mscapi.CSignature$NONEwithRSA", - null, attrs)); - putService(new ProviderService(p, "Signature", - "SHA1withRSA", "sun.security.mscapi.CSignature$SHA1withRSA", - null, attrs)); - putService(new ProviderServiceA(p, "Signature", - "SHA256withRSA", - "sun.security.mscapi.CSignature$SHA256withRSA", - attrs)); - putService(new ProviderServiceA(p, "Signature", - "SHA384withRSA", - "sun.security.mscapi.CSignature$SHA384withRSA", - attrs)); - putService(new ProviderServiceA(p, "Signature", - "SHA512withRSA", - "sun.security.mscapi.CSignature$SHA512withRSA", - attrs)); - putService(new ProviderServiceA(p, "Signature", - "RSASSA-PSS", "sun.security.mscapi.CSignature$PSS", - attrs)); - putService(new ProviderService(p, "Signature", - "MD5withRSA", "sun.security.mscapi.CSignature$MD5withRSA", - null, attrs)); - putService(new ProviderService(p, "Signature", - "MD2withRSA", "sun.security.mscapi.CSignature$MD2withRSA", - null, attrs)); - putService(new ProviderServiceA(p, "Signature", - "SHA1withECDSA", - "sun.security.mscapi.CSignature$SHA1withECDSA", - attrs)); - putService(new ProviderServiceA(p, "Signature", - "SHA224withECDSA", - "sun.security.mscapi.CSignature$SHA224withECDSA", - attrs)); - putService(new ProviderServiceA(p, "Signature", - "SHA256withECDSA", - "sun.security.mscapi.CSignature$SHA256withECDSA", - attrs)); - putService(new ProviderServiceA(p, "Signature", - "SHA384withECDSA", - "sun.security.mscapi.CSignature$SHA384withECDSA", - attrs)); - putService(new ProviderServiceA(p, "Signature", - "SHA512withECDSA", - "sun.security.mscapi.CSignature$SHA512withECDSA", - attrs)); - /* - * Key Pair Generator engines - */ - attrs.clear(); - attrs.put("KeySize", "16384"); - putService(new ProviderService(p, "KeyPairGenerator", - "RSA", "sun.security.mscapi.CKeyPairGenerator$RSA", - null, attrs)); + // NONEwithRSA must be supplied with a pre-computed message digest. + // Only the following digest algorithms are supported: MD5, SHA-1, + // SHA-256, SHA-384, SHA-512 and a special-purpose digest + // algorithm which is a concatenation of SHA-1 and MD5 digests. + putService(new ProviderService(p, "Signature", + "NONEwithRSA", "sun.security.mscapi.CSignature$NONEwithRSA", + null, attrs)); + putService(new ProviderService(p, "Signature", + "SHA1withRSA", "sun.security.mscapi.CSignature$SHA1withRSA", + null, attrs)); + putService(new ProviderServiceA(p, "Signature", + "SHA256withRSA", + "sun.security.mscapi.CSignature$SHA256withRSA", + attrs)); + putService(new ProviderServiceA(p, "Signature", + "SHA384withRSA", + "sun.security.mscapi.CSignature$SHA384withRSA", + attrs)); + putService(new ProviderServiceA(p, "Signature", + "SHA512withRSA", + "sun.security.mscapi.CSignature$SHA512withRSA", + attrs)); + putService(new ProviderServiceA(p, "Signature", + "RSASSA-PSS", "sun.security.mscapi.CSignature$PSS", + attrs)); + putService(new ProviderService(p, "Signature", + "MD5withRSA", "sun.security.mscapi.CSignature$MD5withRSA", + null, attrs)); + putService(new ProviderService(p, "Signature", + "MD2withRSA", "sun.security.mscapi.CSignature$MD2withRSA", + null, attrs)); + putService(new ProviderServiceA(p, "Signature", + "SHA1withECDSA", + "sun.security.mscapi.CSignature$SHA1withECDSA", + attrs)); + putService(new ProviderServiceA(p, "Signature", + "SHA224withECDSA", + "sun.security.mscapi.CSignature$SHA224withECDSA", + attrs)); + putService(new ProviderServiceA(p, "Signature", + "SHA256withECDSA", + "sun.security.mscapi.CSignature$SHA256withECDSA", + attrs)); + putService(new ProviderServiceA(p, "Signature", + "SHA384withECDSA", + "sun.security.mscapi.CSignature$SHA384withECDSA", + attrs)); + putService(new ProviderServiceA(p, "Signature", + "SHA512withECDSA", + "sun.security.mscapi.CSignature$SHA512withECDSA", + attrs)); + /* + * Key Pair Generator engines + */ + attrs.clear(); + attrs.put("KeySize", "16384"); + putService(new ProviderService(p, "KeyPairGenerator", + "RSA", "sun.security.mscapi.CKeyPairGenerator$RSA", + null, attrs)); - /* - * Cipher engines - */ - attrs.clear(); - attrs.put("SupportedModes", "ECB"); - attrs.put("SupportedPaddings", "PKCS1PADDING"); - attrs.put("SupportedKeyClasses", "sun.security.mscapi.CKey"); - putService(new ProviderService(p, "Cipher", - "RSA", "sun.security.mscapi.CRSACipher", - null, attrs)); - putService(new ProviderService(p, "Cipher", - "RSA/ECB/PKCS1Padding", "sun.security.mscapi.CRSACipher", - null, attrs)); - return null; - } - }); + /* + * Cipher engines + */ + attrs.clear(); + attrs.put("SupportedModes", "ECB"); + attrs.put("SupportedPaddings", "PKCS1PADDING"); + attrs.put("SupportedKeyClasses", "sun.security.mscapi.CKey"); + putService(new ProviderService(p, "Cipher", + "RSA", "sun.security.mscapi.CRSACipher", + null, attrs)); + putService(new ProviderService(p, "Cipher", + "RSA/ECB/PKCS1Padding", "sun.security.mscapi.CRSACipher", + null, attrs)); } } diff --git a/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/Float16.java b/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/Float16.java index 5a7cdb89dde..f5f5a5a4e7e 100644 --- a/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/Float16.java +++ b/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/Float16.java @@ -95,8 +95,7 @@ // Currently Float16 is a value-based class and in future it is // expected to be aligned with Value Classes and Object as described in // JEP-401 (https://openjdk.org/jeps/401). -// @jdk.internal.MigratedValueClass -// @jdk.internal.ValueBased +@jdk.internal.ValueBased public final class Float16 extends Number implements Comparable { @@ -323,7 +322,7 @@ public static Float16 valueOf(long value) { * @param f a {@code float} */ public static Float16 valueOf(float f) { - return new Float16(Float.floatToFloat16(f)); + return new Float16(floatToFloat16(f)); } /** diff --git a/src/jdk.jdeps/share/classes/com/sun/tools/javap/AttributeWriter.java b/src/jdk.jdeps/share/classes/com/sun/tools/javap/AttributeWriter.java index e0d2a418447..e20b152ece8 100644 --- a/src/jdk.jdeps/share/classes/com/sun/tools/javap/AttributeWriter.java +++ b/src/jdk.jdeps/share/classes/com/sun/tools/javap/AttributeWriter.java @@ -84,7 +84,7 @@ public void write(Attribute a, CodeAttribute lr) { int i = 0; int j = 0; print(" "); - print(attr.attributeName()); + print(attr.attributeName().stringValue()); print(": "); print("length = 0x" + toHex(data.length)); print(" (unknown attribute)"); 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 20ed86eae4f..9ea935551b8 100644 --- a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java +++ b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java @@ -44,10 +44,6 @@ import java.nio.file.*; import java.nio.file.attribute.*; import java.nio.file.spi.FileSystemProvider; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.*; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; @@ -82,10 +78,8 @@ */ class ZipFileSystem extends FileSystem { // statics - @SuppressWarnings("removal") - private static final boolean isWindows = AccessController.doPrivileged( - (PrivilegedAction)()->System.getProperty("os.name") - .startsWith("Windows")); + private static final boolean isWindows = System.getProperty("os.name") + .startsWith("Windows"); private static final byte[] ROOTPATH = new byte[] { '/' }; private static final String PROPERTY_POSIX = "enablePosixFileAttributes"; private static final String PROPERTY_DEFAULT_OWNER = "defaultOwner"; @@ -168,9 +162,7 @@ class ZipFileSystem extends FileSystem { } // sm and existence check zfpath.getFileSystem().provider().checkAccess(zfpath, AccessMode.READ); - @SuppressWarnings("removal") - boolean writeable = AccessController.doPrivileged( - (PrivilegedAction)()->Files.isWritable(zfpath)); + boolean writeable = Files.isWritable(zfpath); this.readOnly = !writeable; this.zc = ZipCoder.get(nameEncoding); this.rootdir = new ZipPath(this, new byte[]{'/'}); @@ -244,23 +236,14 @@ private static boolean isTrue(Map env, String name) { // If not specified in env, it is the owner of the archive. If no owner can // be determined, we try to go with system property "user.name". If that's not // accessible, we return "". - @SuppressWarnings("removal") private UserPrincipal initOwner(Path zfpath, Map env) throws IOException { Object o = env.get(PROPERTY_DEFAULT_OWNER); if (o == null) { try { - PrivilegedExceptionAction pa = ()->Files.getOwner(zfpath); - return AccessController.doPrivileged(pa); - } catch (UnsupportedOperationException | PrivilegedActionException e) { - if (e instanceof UnsupportedOperationException || - e.getCause() instanceof NoSuchFileException) - { - PrivilegedAction pa = ()->System.getProperty("user.name"); - String userName = AccessController.doPrivileged(pa); - return ()->userName; - } else { - throw new IOException(e); - } + return Files.getOwner(zfpath); + } catch (UnsupportedOperationException | NoSuchFileException e) { + String userName = System.getProperty("user.name"); + return ()->userName; } } if (o instanceof String) { @@ -282,7 +265,6 @@ private UserPrincipal initOwner(Path zfpath, Map env) throws IOExcept // If not specified in env, we try to determine the group of the zip archive itself. // If this is not possible/unsupported, we will return a group principal going by // the same name as the default owner. - @SuppressWarnings("removal") private GroupPrincipal initGroup(Path zfpath, Map env) throws IOException { Object o = env.get(PROPERTY_DEFAULT_GROUP); if (o == null) { @@ -291,16 +273,9 @@ private GroupPrincipal initGroup(Path zfpath, Map env) throws IOExcep if (zfpv == null) { return defaultOwner::getName; } - PrivilegedExceptionAction pa = ()->zfpv.readAttributes().group(); - return AccessController.doPrivileged(pa); - } catch (UnsupportedOperationException | PrivilegedActionException e) { - if (e instanceof UnsupportedOperationException || - e.getCause() instanceof NoSuchFileException) - { - return defaultOwner::getName; - } else { - throw new IOException(e); - } + return zfpv.readAttributes().group(); + } catch (UnsupportedOperationException | NoSuchFileException e) { + return defaultOwner::getName; } } if (o instanceof String) { @@ -462,7 +437,6 @@ public PathMatcher getPathMatcher(String syntaxAndInput) { return (path)->pattern.matcher(path.toString()).matches(); } - @SuppressWarnings("removal") @Override public void close() throws IOException { beginWrite(); @@ -480,13 +454,9 @@ public void close() throws IOException { } beginWrite(); // lock and sync try { - AccessController.doPrivileged((PrivilegedExceptionAction)() -> { - sync(); return null; - }); + sync(); ch.close(); // close the ch just in case no update // and sync didn't close the ch - } catch (PrivilegedActionException e) { - throw (IOException)e.getException(); } finally { endWrite(); } @@ -512,10 +482,8 @@ public void close() throws IOException { synchronized (tmppaths) { for (Path p : tmppaths) { try { - AccessController.doPrivileged( - (PrivilegedExceptionAction)() -> Files.deleteIfExists(p)); - } catch (PrivilegedActionException e) { - IOException x = (IOException)e.getException(); + Files.deleteIfExists(p); + } catch (IOException x) { if (ioe == null) ioe = x; else diff --git a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystemProvider.java b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystemProvider.java index 615d2a42e20..a8336b0f8f6 100644 --- a/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystemProvider.java +++ b/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystemProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,9 +39,6 @@ import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.FileAttributeView; import java.nio.file.spi.FileSystemProvider; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -317,17 +314,9 @@ public void setAttribute(Path path, String attribute, } ////////////////////////////////////////////////////////////// - @SuppressWarnings("removal") void removeFileSystem(Path zfpath, ZipFileSystem zfs) throws IOException { synchronized (filesystems) { - Path tempPath = zfpath; - PrivilegedExceptionAction action = tempPath::toRealPath; - try { - zfpath = AccessController.doPrivileged(action); - } catch (PrivilegedActionException e) { - throw (IOException) e.getException(); - } - filesystems.remove(zfpath, zfs); + filesystems.remove(zfpath.toRealPath(), zfs); } } } diff --git a/test/hotspot/gtest/classfile/test_stringConversion.cpp b/test/hotspot/gtest/classfile/test_stringConversion.cpp new file mode 100644 index 00000000000..13553464229 --- /dev/null +++ b/test/hotspot/gtest/classfile/test_stringConversion.cpp @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#include "precompiled.hpp" +#include "runtime/interfaceSupport.inline.hpp" +#include "unittest.hpp" + +// Tests that string functions (hash code/equals) stay consistant when comparing equal strings and converting between strings types + +// Simple ASCII string "Java(R)!!" +// Same length in both UTF8 and Unicode +static const char static_ascii_utf8_str[] = {0x4A, 0x61, 0x76, 0x61, 0x28, 0x52, 0x29, 0x21, 0x21}; +static const jchar static_ascii_unicode_str[] = {0x004A, 0x0061, 0x0076, 0x0061, 0x0028, 0x0052, 0x0029, 0x0021, 0x0021}; + +// Complex string "Jāvá®!☺☻", UTF8 has character lengths 13122133 = 16 +static const unsigned char static_utf8_str[] = {0x4A, 0x61, 0xCC, 0x84, 0x76, 0xC3, 0xA1, 0xC2, 0xAE, 0x21, 0xE2, 0x98, 0xBA, 0xE2, 0x98, 0xBB}; +static const jchar static_unicode_str[] = { 0x004A, 0x0061, 0x0304, 0x0076, 0x00E1, 0x00AE, 0x0021, 0x263A, 0x263B}; + +static const int ASCII_LENGTH = 9; +static const size_t UTF8_LENGTH = 16; +static const int UNICODE_LENGTH = 9; + +void compare_utf8_utf8(const char* utf8_str1, const char* utf8_str2, size_t utf8_len) { + EXPECT_EQ(java_lang_String::hash_code(utf8_str1, utf8_len), java_lang_String::hash_code(utf8_str2, utf8_len)); + EXPECT_STREQ(utf8_str1, utf8_str2); +} + +void compare_utf8_unicode(const char* utf8_str, const jchar* unicode_str, size_t utf8_len, int unicode_len) { + EXPECT_EQ(java_lang_String::hash_code(utf8_str, utf8_len), java_lang_String::hash_code(unicode_str, unicode_len)); +} + +void compare_utf8_oop(const char* utf8_str, Handle oop_str, size_t utf8_len, int unicode_len) { + EXPECT_EQ(java_lang_String::hash_code(utf8_str, utf8_len), java_lang_String::hash_code(oop_str())); + EXPECT_TRUE(java_lang_String::equals(oop_str(), utf8_str, utf8_len)); +} + +void compare_unicode_unicode(const jchar* unicode_str1, const jchar* unicode_str2, int unicode_len) { + EXPECT_EQ(java_lang_String::hash_code(unicode_str1, unicode_len), java_lang_String::hash_code(unicode_str2, unicode_len)); + for (int i = 0; i < unicode_len; i++) { + EXPECT_EQ(unicode_str1[i], unicode_str2[i]); + } +} + +void compare_unicode_oop(const jchar* unicode_str, Handle oop_str, int unicode_len) { + EXPECT_EQ(java_lang_String::hash_code(unicode_str, unicode_len), java_lang_String::hash_code(oop_str())); + EXPECT_TRUE(java_lang_String::equals(oop_str(), unicode_str, unicode_len)); +} + +void compare_oop_oop(Handle oop_str1, Handle oop_str2) { + EXPECT_EQ(java_lang_String::hash_code(oop_str1()), java_lang_String::hash_code(oop_str2())); + EXPECT_TRUE(java_lang_String::equals(oop_str1(), oop_str2())); +} + +void test_utf8_convert(const char* utf8_str, size_t utf8_len, int unicode_len) { + EXPECT_TRUE(UTF8::is_legal_utf8((unsigned char*)utf8_str, strlen(utf8_str), false)); + + JavaThread* THREAD = JavaThread::current(); + ThreadInVMfromNative ThreadInVMfromNative(THREAD); + ResourceMark rm(THREAD); + HandleMark hm(THREAD); + + jchar* unicode_str_from_utf8 = NEW_RESOURCE_ARRAY(jchar, unicode_len); + UTF8::convert_to_unicode(utf8_str, unicode_str_from_utf8, unicode_len); + Handle oop_str_from_utf8 = java_lang_String::create_from_str(utf8_str, THREAD); + + compare_utf8_unicode(utf8_str, unicode_str_from_utf8, utf8_len, unicode_len); + compare_utf8_oop(utf8_str, oop_str_from_utf8, utf8_len, unicode_len); + + size_t length = unicode_len; + const char* utf8_str_from_unicode = UNICODE::as_utf8(unicode_str_from_utf8, length); + const char* utf8_str_from_oop = java_lang_String::as_utf8_string(oop_str_from_utf8()); + + EXPECT_TRUE(UTF8::is_legal_utf8((unsigned char*)utf8_str_from_unicode, strlen(utf8_str_from_unicode), false)); + EXPECT_TRUE(UTF8::is_legal_utf8((unsigned char*)utf8_str_from_oop, strlen(utf8_str_from_oop), false)); + + compare_utf8_utf8(utf8_str, utf8_str_from_unicode, utf8_len); + compare_utf8_utf8(utf8_str, utf8_str_from_oop, utf8_len); +} + +void test_unicode_convert(const jchar* unicode_str, size_t utf8_len, int unicode_len) { + JavaThread* THREAD = JavaThread::current(); + ThreadInVMfromNative ThreadInVMfromNative(THREAD); + ResourceMark rm(THREAD); + HandleMark hm(THREAD); + + size_t length = unicode_len; + const char* utf8_str_from_unicode = UNICODE::as_utf8(unicode_str, length); + Handle oop_str_from_unicode = java_lang_String::create_from_unicode(unicode_str, unicode_len, THREAD); + + EXPECT_TRUE(UTF8::is_legal_utf8((unsigned char*)utf8_str_from_unicode, strlen(utf8_str_from_unicode), false)); + + compare_utf8_unicode(utf8_str_from_unicode, unicode_str, utf8_len, unicode_len); + compare_unicode_oop(unicode_str, oop_str_from_unicode, unicode_len); + + int _; + jchar* unicode_str_from_utf8 = NEW_RESOURCE_ARRAY(jchar, unicode_len); + UTF8::convert_to_unicode(utf8_str_from_unicode, unicode_str_from_utf8, unicode_len); + const jchar* unicode_str_from_oop = java_lang_String::as_unicode_string(oop_str_from_unicode(), _, THREAD); + + compare_unicode_unicode(unicode_str, unicode_str_from_utf8, unicode_len); + compare_unicode_unicode(unicode_str, unicode_str_from_oop, unicode_len); +} + +void test_utf8_unicode_cross(const char* utf8_str, const jchar* unicode_str, size_t utf8_len, int unicode_len) { + compare_utf8_unicode(utf8_str, unicode_str, utf8_len, unicode_len); + + JavaThread* THREAD = JavaThread::current(); + ThreadInVMfromNative ThreadInVMfromNative(THREAD); + ResourceMark rm(THREAD); + HandleMark hm(THREAD); + + size_t length = unicode_len; + const char* utf8_str_from_unicode = UNICODE::as_utf8(unicode_str, length); + + jchar* unicode_str_from_utf8 = NEW_RESOURCE_ARRAY(jchar, unicode_len); + UTF8::convert_to_unicode(utf8_str, unicode_str_from_utf8, unicode_len); + + Handle oop_str_from_unicode = java_lang_String::create_from_unicode(unicode_str, unicode_len, THREAD); + Handle oop_str_from_utf8 = java_lang_String::create_from_str(utf8_str, THREAD); + + compare_utf8_utf8(utf8_str, utf8_str_from_unicode, utf8_len); + compare_utf8_oop(utf8_str, oop_str_from_unicode, utf8_len, unicode_len); + + compare_unicode_unicode(unicode_str, unicode_str_from_utf8, unicode_len); + compare_unicode_oop(unicode_str, oop_str_from_utf8, unicode_len); + + compare_utf8_oop(utf8_str_from_unicode, oop_str_from_utf8, utf8_len, unicode_len); + compare_unicode_oop(unicode_str_from_utf8, oop_str_from_unicode, unicode_len); + + compare_utf8_unicode(utf8_str_from_unicode, unicode_str_from_utf8, utf8_len, unicode_len); + compare_oop_oop(oop_str_from_utf8, oop_str_from_unicode); +} + +TEST_VM(StringConversion, fromUTF8_ascii) { + const char utf8_str[ASCII_LENGTH + 1] = { }; + memcpy((unsigned char*)utf8_str, static_ascii_utf8_str, ASCII_LENGTH); + test_utf8_convert(utf8_str, ASCII_LENGTH, ASCII_LENGTH); +} + +TEST_VM(StringConversion, fromUTF8_varlen) { + const char utf8_str[UTF8_LENGTH + 1] = { }; + memcpy((unsigned char*)utf8_str, static_utf8_str, UTF8_LENGTH); + test_utf8_convert(utf8_str, UTF8_LENGTH, UNICODE_LENGTH); +} + +TEST_VM(StringConversion, fromUnicode_ascii) { + jchar unicode_str[ASCII_LENGTH] = { }; + memcpy(unicode_str, static_ascii_unicode_str, ASCII_LENGTH * sizeof(jchar)); + test_unicode_convert(unicode_str, ASCII_LENGTH, ASCII_LENGTH); +} + +TEST_VM(StringConversion, fromUnicode_varlen) { + jchar unicode_str[UNICODE_LENGTH] = { }; + memcpy(unicode_str, static_unicode_str, UNICODE_LENGTH * sizeof(jchar)); + test_unicode_convert(unicode_str, UTF8_LENGTH, UNICODE_LENGTH); +} + +TEST_VM(StringConversion, cross_ascii) { + const char utf8_str[ASCII_LENGTH + 1] = { }; + jchar unicode_str[ASCII_LENGTH] = { }; + memcpy((unsigned char*)utf8_str, static_ascii_utf8_str, ASCII_LENGTH); + memcpy(unicode_str, static_ascii_unicode_str, ASCII_LENGTH * sizeof(jchar)); + + test_utf8_unicode_cross(utf8_str, unicode_str, ASCII_LENGTH, ASCII_LENGTH); +} + +TEST_VM(StringConversion, cross_varlen) { + const char utf8_str[UTF8_LENGTH + 1] = { }; + jchar unicode_str[UNICODE_LENGTH] = { }; + memcpy((unsigned char*)utf8_str, static_utf8_str, UTF8_LENGTH); + memcpy(unicode_str, static_unicode_str, UNICODE_LENGTH * sizeof(jchar)); + + test_utf8_unicode_cross(utf8_str, unicode_str, UTF8_LENGTH, UNICODE_LENGTH); +} diff --git a/test/hotspot/gtest/classfile/test_stringIntern.cpp b/test/hotspot/gtest/classfile/test_stringIntern.cpp new file mode 100644 index 00000000000..69c0a5b2aa4 --- /dev/null +++ b/test/hotspot/gtest/classfile/test_stringIntern.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#include "precompiled.hpp" +#include "classfile/stringTable.hpp" +#include "classfile/symbolTable.hpp" +#include "runtime/interfaceSupport.inline.hpp" +#include "unittest.hpp" + +// Tests that strings are interned and returns the same string when interning from different string types + +// Simple ASCII string "Java(R)!!" +static const char static_ascii_utf8_str[] = {0x4A, 0x61, 0x76, 0x61, 0x28, 0x52, 0x29, 0x21, 0x21}; +static const size_t ASCII_LENGTH = 9; + +// Complex string "Jāvá®!☺☻", has character lengths 13122133 = 16 +static const unsigned char static_utf8_str[] = {0x4A, 0x61, 0xCC, 0x84, 0x76, 0xC3, 0xA1, 0xC2, 0xAE, 0x21, 0xE2, 0x98, 0xBA, 0xE2, 0x98, 0xBB}; +static const size_t COMPLEX_LENGTH = 16; + +void test_intern(const char* utf8_str, size_t utf8_length) { + JavaThread* THREAD = JavaThread::current(); + ThreadInVMfromNative ThreadInVMfromNative(THREAD); + HandleMark hm(THREAD); + + oop interned_string_from_utf8 = StringTable::intern(utf8_str, THREAD); + + EXPECT_TRUE(java_lang_String::equals(interned_string_from_utf8, utf8_str, utf8_length)); + EXPECT_EQ(java_lang_String::hash_code(utf8_str, utf8_length),java_lang_String::hash_code(interned_string_from_utf8)); + + Symbol* symbol_from_utf8 = SymbolTable::new_symbol(utf8_str, static_cast(utf8_length)); + oop interned_string_from_symbol = StringTable::intern(symbol_from_utf8, THREAD); + + EXPECT_EQ(interned_string_from_utf8, interned_string_from_symbol); + + oop interned_string_from_oop1 = StringTable::intern(interned_string_from_utf8, THREAD); + + EXPECT_EQ(interned_string_from_utf8, interned_string_from_oop1); + +} + +TEST_VM(StringIntern, intern_ascii) { + const char utf8_str[ASCII_LENGTH + 1] = { }; + memcpy((unsigned char*)utf8_str, static_ascii_utf8_str, ASCII_LENGTH); + test_intern(utf8_str, ASCII_LENGTH); +} + +TEST_VM(StringIntern, intern_varlen) { + const char utf8_str[COMPLEX_LENGTH + 1] = { }; + memcpy((unsigned char*)utf8_str, static_utf8_str, COMPLEX_LENGTH); + test_intern(utf8_str, COMPLEX_LENGTH); +} diff --git a/test/hotspot/jtreg/ProblemList-AotJdk.txt b/test/hotspot/jtreg/ProblemList-AotJdk.txt new file mode 100644 index 00000000000..2528f8d377e --- /dev/null +++ b/test/hotspot/jtreg/ProblemList-AotJdk.txt @@ -0,0 +1,18 @@ +runtime/modules/PatchModule/PatchModuleClassList.java 0000000 generic-all +runtime/NMT/NMTWithCDS.java 0000000 generic-all +runtime/symbols/TestSharedArchiveConfigFile.java 0000000 generic-all + +gc/arguments/TestSerialHeapSizeFlags.java 0000000 generic-all +gc/TestAllocateHeapAtMultiple.java 0000000 generic-all +gc/TestAllocateHeapAt.java 0000000 generic-all + +# use -Xshare +serviceability/sa/ClhsdbCDSJstackPrintAll.java 0000000 generic-all +serviceability/sa/ClhsdbCDSCore.java 0000000 generic-all +serviceability/sa/CDSJMapClstats.java 0000000 generic-all +compiler/intrinsics/klass/TestIsPrimitive.java 0000000 generic-all + +# This test is incompatible with AOTClassLinking. +# It has the assumption about unresolved Integer. +# However when AOTClassLinking is enabled, Integer is always resolved at JVM start-up. +compiler/ciReplay/TestInliningProtectionDomain.java 0000000 generic-all diff --git a/test/hotspot/jtreg/ProblemList.txt b/test/hotspot/jtreg/ProblemList.txt index d09fcece8d2..06b6fb0f13a 100644 --- a/test/hotspot/jtreg/ProblemList.txt +++ b/test/hotspot/jtreg/ProblemList.txt @@ -118,6 +118,7 @@ runtime/cds/appcds/customLoader/HelloCustom_JFR.java 8241075 linux-all,windows-x runtime/Dictionary/CleanProtectionDomain.java 8341916 generic-all runtime/Dictionary/ProtectionDomainCacheTest.java 8341916 generic-all runtime/logging/ProtectionDomainVerificationTest.java 8341916 generic-all +runtime/NMT/VirtualAllocCommitMerge.java 8309698 linux-s390x # Fails with +UseCompactObjectHeaders on aarch64 runtime/cds/appcds/SharedBaseAddress.java 8340212 linux-aarch64,macosx-aarch64 diff --git a/test/hotspot/jtreg/TEST.ROOT b/test/hotspot/jtreg/TEST.ROOT index 8cf4a56a3b0..befefd75550 100644 --- a/test/hotspot/jtreg/TEST.ROOT +++ b/test/hotspot/jtreg/TEST.ROOT @@ -74,6 +74,7 @@ requires.properties= \ vm.rtm.compiler \ vm.cds \ vm.cds.custom.loaders \ + vm.cds.supports.aot.class.linking \ vm.cds.write.archived.java.heap \ vm.continuations \ vm.jvmti \ diff --git a/test/hotspot/jtreg/TEST.groups b/test/hotspot/jtreg/TEST.groups index 7ff9d800352..78f90bda91b 100644 --- a/test/hotspot/jtreg/TEST.groups +++ b/test/hotspot/jtreg/TEST.groups @@ -56,6 +56,7 @@ hotspot_runtime_no_cds = \ hotspot_runtime_non_cds_mode = \ runtime \ -runtime/cds/CheckSharingWithDefaultArchive.java \ + -runtime/cds/appcds/aotClassLinking/BulkLoaderTest.java \ -runtime/cds/appcds/dynamicArchive/DynamicSharedSymbols.java \ -runtime/cds/appcds/dynamicArchive/TestAutoCreateSharedArchive.java \ -runtime/cds/appcds/jcmd @@ -451,6 +452,7 @@ hotspot_cds_only = \ hotspot_appcds_dynamic = \ runtime/cds/appcds/ \ + -runtime/cds/appcds/applications \ -runtime/cds/appcds/cacheObject \ -runtime/cds/appcds/complexURI \ -runtime/cds/appcds/customLoader \ @@ -468,10 +470,12 @@ hotspot_appcds_dynamic = \ -runtime/cds/appcds/jvmti/redefineClasses/OldClassAndRedefineClass.java \ -runtime/cds/appcds/lambdaForm/DefaultClassListLFInvokers.java \ -runtime/cds/appcds/methodHandles \ + -runtime/cds/appcds/aotClassLinking/BulkLoaderTest.java \ -runtime/cds/appcds/sharedStrings \ -runtime/cds/appcds/resolvedConstants \ -runtime/cds/appcds/ArchiveRelocationTest.java \ -runtime/cds/appcds/BadBSM.java \ + -runtime/cds/appcds/CommandLineFlagCombo.java \ -runtime/cds/appcds/DumpClassList.java \ -runtime/cds/appcds/DumpClassListWithLF.java \ -runtime/cds/appcds/DumpRuntimeClassesTest.java \ @@ -539,6 +543,61 @@ hotspot_cds_epsilongc = \ runtime/cds/appcds/jigsaw \ runtime/cds/appcds/loaderConstraints +# Run CDS tests with -XX:+AOTClassLinking. This should include most CDS tests, except for +# those that rely on redefining classes that are already archived. +hotspot_aot_classlinking = \ + runtime/cds \ + -runtime/cds/appcds/aotClassLinking \ + -runtime/cds/appcds/BadBSM.java \ + -runtime/cds/appcds/cacheObject/ArchivedIntegerCacheTest.java \ + -runtime/cds/appcds/cacheObject/ArchivedModuleCompareTest.java \ + -runtime/cds/appcds/CDSandJFR.java \ + -runtime/cds/appcds/customLoader/HelloCustom_JFR.java \ + -runtime/cds/appcds/customLoader/ParallelTestMultiFP.java \ + -runtime/cds/appcds/customLoader/ParallelTestSingleFP.java \ + -runtime/cds/appcds/customLoader/SameNameInTwoLoadersTest.java \ + -runtime/cds/appcds/DumpClassListWithLF.java \ + -runtime/cds/appcds/dynamicArchive/ModulePath.java \ + -runtime/cds/appcds/dynamicArchive/LambdaInBaseArchive.java \ + -runtime/cds/appcds/dynamicArchive/LambdasInTwoArchives.java \ + -runtime/cds/appcds/HelloExtTest.java \ + -runtime/cds/appcds/javaldr/AnonVmClassesDuringDump.java \ + -runtime/cds/appcds/javaldr/GCDuringDump.java \ + -runtime/cds/appcds/javaldr/LockDuringDump.java \ + -runtime/cds/appcds/jigsaw/classpathtests/EmptyClassInBootClassPath.java \ + -runtime/cds/appcds/jigsaw/JigsawOptionsCombo.java \ + -runtime/cds/appcds/jigsaw/modulepath/AddOpens.java \ + -runtime/cds/appcds/jigsaw/modulepath/AddModules.java \ + -runtime/cds/appcds/jigsaw/modulepath/JvmtiAddPath.java \ + -runtime/cds/appcds/jigsaw/modulepath/MainModuleOnly.java \ + -runtime/cds/appcds/jigsaw/modulepath/ModulePathAndCP.java \ + -runtime/cds/appcds/jigsaw/modulepath/ModulePathAndCP_JFR.java \ + -runtime/cds/appcds/jigsaw/modulepath/ModulePathAndFMG.java \ + -runtime/cds/appcds/jigsaw/modulepath/OptimizeModuleHandlingTest.java \ + -runtime/cds/appcds/jigsaw/overridetests/OverrideTests.java \ + -runtime/cds/appcds/jigsaw/RedefineClassesInModuleGraph.java \ + -runtime/cds/appcds/JvmtiAddPath.java \ + -runtime/cds/appcds/jvmti \ + -runtime/cds/appcds/LambdaProxyClasslist.java \ + -runtime/cds/appcds/loaderConstraints/LoaderConstraintsTest.java \ + -runtime/cds/appcds/redefineClass \ + -runtime/cds/appcds/resolvedConstants/AOTLinkedLambdas.java \ + -runtime/cds/appcds/resolvedConstants/AOTLinkedVarHandles.java \ + -runtime/cds/appcds/resolvedConstants/ResolvedConstants.java \ + -runtime/cds/appcds/RewriteBytecodesTest.java \ + -runtime/cds/appcds/SpecifySysLoaderProp.java \ + -runtime/cds/appcds/StaticArchiveWithLambda.java \ + -runtime/cds/appcds/TestEpsilonGCWithCDS.java \ + -runtime/cds/appcds/TestParallelGCWithCDS.java \ + -runtime/cds/appcds/TestSerialGCWithCDS.java \ + -runtime/cds/appcds/TestZGCWithCDS.java \ + -runtime/cds/appcds/TestWithProfiler.java \ + -runtime/cds/serviceability/ReplaceCriticalClassesForSubgraphs.java \ + -runtime/cds/serviceability/ReplaceCriticalClasses.java \ + -runtime/cds/serviceability/transformRelatedClasses/TransformInterfaceAndImplementor.java \ + -runtime/cds/serviceability/transformRelatedClasses/TransformSuperAndSubClasses.java \ + -runtime/cds/serviceability/transformRelatedClasses/TransformSuperSubTwoPckgs.java + # needs -nativepath:/images/test/hotspot/jtreg/native/ hotspot_metaspace = \ gtest/MetaspaceGtests.java \ @@ -558,6 +617,10 @@ tier1_runtime_appcds_exclude = \ runtime/cds/appcds/ \ -:tier1_runtime_appcds +tier1_runtime_no_cds = \ + :tier1_runtime \ + -runtime/cds + # This group should be executed with "jtreg -Dtest.cds.run.with.jfr=true ..." # to test interaction between AppCDS and JFR. It also has the side effect of # testing JVMTI ClassFileLoadHook. diff --git a/test/hotspot/jtreg/compiler/c2/TestMergeStores.java b/test/hotspot/jtreg/compiler/c2/TestMergeStores.java index c8e8bd337ad..3598b8eae71 100644 --- a/test/hotspot/jtreg/compiler/c2/TestMergeStores.java +++ b/test/hotspot/jtreg/compiler/c2/TestMergeStores.java @@ -340,8 +340,8 @@ public void runTests(RunInfo info) { set_random(aL); set_random(bL); - offset1 = Math.abs(RANDOM.nextInt()) % 100; - offset2 = Math.abs(RANDOM.nextInt()) % 100; + offset1 = RANDOM.nextInt(100); + offset2 = RANDOM.nextInt(100); vB1 = (byte)RANDOM.nextInt(); vB2 = (byte)RANDOM.nextInt(); vS1 = (short)RANDOM.nextInt(); diff --git a/test/hotspot/jtreg/runtime/cds/SharedBaseAddress.java b/test/hotspot/jtreg/runtime/cds/SharedBaseAddress.java index a7f31cf1a08..49265680ef2 100644 --- a/test/hotspot/jtreg/runtime/cds/SharedBaseAddress.java +++ b/test/hotspot/jtreg/runtime/cds/SharedBaseAddress.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved. * 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,8 +67,23 @@ import jdk.test.lib.cds.CDSOptions; import jdk.test.lib.Platform; import jdk.test.lib.process.OutputAnalyzer; +import jtreg.SkippedException; public class SharedBaseAddress { + static final boolean skipUncompressedOopsTests; + static boolean checkSkipUncompressedOopsTests(String prop) { + String opts = System.getProperty(prop); + return opts.contains("+AOTClassLinking") && + opts.matches(".*[+]Use[A-Za-z]+GC.*") && !opts.contains("+UseG1GC"); + } + static { + // AOTClassLinking requires the ability to load archived heap objects. However, + // due to JDK-8341371, only G1GC supports loading archived heap objects + // with uncompressed oops. + skipUncompressedOopsTests = + checkSkipUncompressedOopsTests("test.vm.opts") || + checkSkipUncompressedOopsTests("test.java.opts"); + } // shared base address test table for {32, 64}bit VM private static final String[] testTableShared = { @@ -100,6 +115,10 @@ public static void test(String[] args, String[] testTable) throws Exception { int end = args[0].equals("0") ? mid : testTable.length; boolean provoke = (args.length > 1 && args[1].equals("provoke")); + if (provoke && skipUncompressedOopsTests) { + throw new SkippedException("Test skipped due to JDK-8341371"); + } + // provoke == true: we want to increase the chance that mapping the generated archive at the designated base // succeeds, to test Klass pointer encoding at that weird location. We do this by sizing heap + class space // small, and by switching off compressed oops. diff --git a/test/hotspot/jtreg/runtime/cds/appcds/AOTFlags.java b/test/hotspot/jtreg/runtime/cds/appcds/AOTFlags.java new file mode 100644 index 00000000000..3a678eefc5b --- /dev/null +++ b/test/hotspot/jtreg/runtime/cds/appcds/AOTFlags.java @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * 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 "AOT" aliases for traditional CDS command-line options + * @requires vm.cds + * @library /test/lib /test/hotspot/jtreg/runtime/cds/appcds/test-classes + * @build Hello + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar hello.jar Hello + * @run driver AOTFlags + */ + +import jdk.test.lib.cds.CDSTestUtils; +import jdk.test.lib.helpers.ClassFileInstaller; +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; + +public class AOTFlags { + static String appJar = ClassFileInstaller.getJarPath("hello.jar"); + static String aotConfigFile = "hello.aotconfig"; + static String aotCacheFile = "hello.aot"; + static String helloClass = "Hello"; + + public static void main(String[] args) throws Exception { + positiveTests(); + negativeTests(); + } + + static void positiveTests() throws Exception { + // (1) Training Run + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-XX:AOTMode=record", + "-XX:AOTConfiguration=" + aotConfigFile, + "-cp", appJar, helloClass); + + OutputAnalyzer out = CDSTestUtils.executeAndLog(pb, "train"); + out.shouldContain("Hello World"); + out.shouldHaveExitValue(0); + + // (2) Assembly Phase + pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-XX:AOTMode=create", + "-XX:AOTConfiguration=" + aotConfigFile, + "-XX:AOTCache=" + aotCacheFile, + "-Xlog:cds", + "-cp", appJar); + out = CDSTestUtils.executeAndLog(pb, "asm"); + out.shouldContain("Dumping shared data to file:"); + out.shouldMatch("cds.*hello[.]aot"); + out.shouldHaveExitValue(0); + + // (3) Production Run with AOTCache + pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-XX:AOTCache=" + aotCacheFile, + "-Xlog:cds", + "-cp", appJar, helloClass); + out = CDSTestUtils.executeAndLog(pb, "prod"); + out.shouldContain("Opened archive hello.aot."); + out.shouldContain("Hello World"); + out.shouldHaveExitValue(0); + + // (4) AOTMode=off + pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-XX:AOTCache=" + aotCacheFile, + "--show-version", + "-Xlog:cds", + "-XX:AOTMode=off", + "-cp", appJar, helloClass); + out = CDSTestUtils.executeAndLog(pb, "prod"); + out.shouldNotContain(", sharing"); + out.shouldNotContain("Opened archive hello.aot."); + out.shouldContain("Hello World"); + out.shouldHaveExitValue(0); + + // (5) AOTMode=auto + pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-XX:AOTCache=" + aotCacheFile, + "--show-version", + "-Xlog:cds", + "-XX:AOTMode=auto", + "-cp", appJar, helloClass); + out = CDSTestUtils.executeAndLog(pb, "prod"); + out.shouldContain(", sharing"); + out.shouldContain("Opened archive hello.aot."); + out.shouldContain("Hello World"); + out.shouldHaveExitValue(0); + + // (5) AOTMode=on + pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-XX:AOTCache=" + aotCacheFile, + "--show-version", + "-Xlog:cds", + "-XX:AOTMode=on", + "-cp", appJar, helloClass); + out = CDSTestUtils.executeAndLog(pb, "prod"); + out.shouldContain(", sharing"); + out.shouldContain("Opened archive hello.aot."); + out.shouldContain("Hello World"); + out.shouldHaveExitValue(0); + } + + static void negativeTests() throws Exception { + // (1) Mixing old and new options + String mixOldNewErrSuffix = " cannot be used at the same time with -Xshare:on, -Xshare:auto, " + + "-Xshare:off, -Xshare:dump, DumpLoadedClassList, SharedClassListFile, " + + "or SharedArchiveFile"; + + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-Xshare:off", + "-XX:AOTConfiguration=" + aotConfigFile, + "-cp", appJar, helloClass); + + OutputAnalyzer out = CDSTestUtils.executeAndLog(pb, "neg"); + out.shouldContain("Option AOTConfiguration" + mixOldNewErrSuffix); + out.shouldNotHaveExitValue(0); + + pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-XX:SharedArchiveFile=" + aotCacheFile, + "-XX:AOTCache=" + aotCacheFile, + "-cp", appJar, helloClass); + out = CDSTestUtils.executeAndLog(pb, "neg"); + out.shouldContain("Option AOTCache" + mixOldNewErrSuffix); + out.shouldNotHaveExitValue(0); + + // (2) Use AOTConfiguration without AOTMode + pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-XX:AOTConfiguration=" + aotConfigFile, + "-cp", appJar, helloClass); + + out = CDSTestUtils.executeAndLog(pb, "neg"); + out.shouldContain("AOTConfiguration can only be used with -XX:AOTMode=record or -XX:AOTMode=create"); + out.shouldNotHaveExitValue(0); + + // (3) Use AOTMode without AOTConfiguration + pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-XX:AOTMode=record", + "-cp", appJar, helloClass); + + out = CDSTestUtils.executeAndLog(pb, "neg"); + out.shouldContain("-XX:AOTMode=record cannot be used without setting AOTConfiguration"); + + pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-XX:AOTMode=create", + "-cp", appJar, helloClass); + + out = CDSTestUtils.executeAndLog(pb, "neg"); + out.shouldContain("-XX:AOTMode=create cannot be used without setting AOTConfiguration"); + out.shouldNotHaveExitValue(0); + + // (4) Bad AOTMode + pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-XX:AOTMode=foo", + "-cp", appJar, helloClass); + + out = CDSTestUtils.executeAndLog(pb, "neg"); + out.shouldContain("Unrecognized value foo for AOTMode. Must be one of the following: off, record, create, auto, on"); + out.shouldNotHaveExitValue(0); + + // (5) AOTCache specified with -XX:AOTMode=record + pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-XX:AOTMode=record", + "-XX:AOTConfiguration=" + aotConfigFile, + "-XX:AOTCache=" + aotCacheFile, + "-cp", appJar, helloClass); + + out = CDSTestUtils.executeAndLog(pb, "neg"); + out.shouldContain("AOTCache must not be specified when using -XX:AOTMode=record"); + out.shouldNotHaveExitValue(0); + + // (5) AOTCache not specified with -XX:AOTMode=create + pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-XX:AOTMode=create", + "-XX:AOTConfiguration=" + aotConfigFile, + "-cp", appJar, helloClass); + + out = CDSTestUtils.executeAndLog(pb, "neg"); + out.shouldContain("AOTCache must be specified when using -XX:AOTMode=create"); + out.shouldNotHaveExitValue(0); + + } +} diff --git a/test/hotspot/jtreg/runtime/cds/appcds/ClassPathAttr.java b/test/hotspot/jtreg/runtime/cds/appcds/ClassPathAttr.java index fe618256f65..df47e6bebc8 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/ClassPathAttr.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/ClassPathAttr.java @@ -190,13 +190,20 @@ static void testNonExistentJars() throws Exception { Files.copy(Paths.get(cp), Paths.get(nonExistPath), StandardCopyOption.REPLACE_EXISTING); - TestCommon.run( + CDSTestUtils.Result result = TestCommon.run( "-Xlog:class+path", "-cp", cp, - "CpAttr6") - .assertNormalExit(output -> { - output.shouldMatch("Archived non-system classes are disabled because the file .*cpattrX.jar exists"); - }); + "CpAttr6"); + if (CDSTestUtils.isAOTClassLinkingEnabled()) { + result.assertAbnormalExit(output -> { + output.shouldMatch("CDS archive has aot-linked classes. It cannot be used because the file .*cpattrX.jar exists"); + }); + + } else { + result.assertNormalExit(output -> { + output.shouldMatch("Archived non-system classes are disabled because the file .*cpattrX.jar exists"); + }); + } } static void testClassPathAttrJarOnCP() throws Exception { diff --git a/test/hotspot/jtreg/runtime/cds/appcds/LambdaContainsOldInf.java b/test/hotspot/jtreg/runtime/cds/appcds/LambdaContainsOldInf.java index 8dec80b9f58..6d1b23628c5 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/LambdaContainsOldInf.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/LambdaContainsOldInf.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -64,7 +64,11 @@ public static void main(String[] args) throws Exception { OutputAnalyzer output = CDSTestUtils.createArchiveAndCheck(opts); TestCommon.checkExecReturn(output, 0, true, "Skipping OldProvider: Old class has been linked"); - output.shouldMatch("Skipping.LambdaContainsOldInfApp[$][$]Lambda.*0x.*:.*Old.class.has.been.linked"); + if (CDSTestUtils.isAOTClassLinkingEnabled()) { + output.shouldMatch("Cannot aot-resolve Lambda proxy because OldProvider is excluded"); + } else { + output.shouldMatch("Skipping.LambdaContainsOldInfApp[$][$]Lambda.*0x.*:.*Old.class.has.been.linked"); + } // run with archive CDSOptions runOpts = (new CDSOptions()) diff --git a/test/hotspot/jtreg/runtime/cds/appcds/LambdaWithOldClass.java b/test/hotspot/jtreg/runtime/cds/appcds/LambdaWithOldClass.java index 3a0bb740387..d7ce22e3cf1 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/LambdaWithOldClass.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/LambdaWithOldClass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -68,7 +68,11 @@ public static void main(String[] args) throws Exception { .addSuffix(mainClass); OutputAnalyzer output = CDSTestUtils.runWithArchive(runOpts); output.shouldContain("[class,load] LambdaWithOldClassApp source: shared objects file") - .shouldMatch(".class.load. LambdaWithOldClassApp[$][$]Lambda.*/0x.*source:.*shared objects file") .shouldHaveExitValue(0); + if (!CDSTestUtils.isAOTClassLinkingEnabled()) { + // With AOTClassLinking, we don't archive any lambda with old classes in the method + // signatures. + output.shouldMatch(".class.load. LambdaWithOldClassApp[$][$]Lambda.*/0x.*source:.*shared objects file"); + } } } diff --git a/test/hotspot/jtreg/runtime/cds/appcds/LambdaWithUseImplMethodHandle.java b/test/hotspot/jtreg/runtime/cds/appcds/LambdaWithUseImplMethodHandle.java index 513ec57d279..360fce5879a 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/LambdaWithUseImplMethodHandle.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/LambdaWithUseImplMethodHandle.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,6 +43,11 @@ public class LambdaWithUseImplMethodHandle { // See pkg2/Child.jcod for details about the condition that triggers JDK-8290417 public static void main(String[] args) throws Exception { + test(false); + test(true); + } + + static void test(boolean aotClassLinking) throws Exception { String appJar = ClassFileInstaller.getJarPath("test.jar"); String mainClass = "LambdaWithUseImplMethodHandleApp"; String expectedMsg = "Called BaseWithProtectedMethod::protectedMethod"; @@ -57,6 +62,9 @@ public static void main(String[] args) throws Exception { .addPrefix("-XX:ExtraSharedClassListFile=" + classList, "-cp", appJar) .setArchiveName(archiveName); + if (aotClassLinking) { + opts.addPrefix("-XX:+AOTClassLinking"); + } CDSTestUtils.createArchiveAndCheck(opts); // run with archive diff --git a/test/hotspot/jtreg/runtime/cds/appcds/TestParallelGCWithCDS.java b/test/hotspot/jtreg/runtime/cds/appcds/TestParallelGCWithCDS.java index 705df07f841..781e0276b27 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/TestParallelGCWithCDS.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/TestParallelGCWithCDS.java @@ -148,6 +148,7 @@ static void test(boolean dumpWithParallel, boolean execWithParallel, boolean use } else { String pattern = "((Too small maximum heap)" + "|(GC triggered before VM initialization completed)" + + "|(CDS archive has aot-linked classes but the archived heap objects cannot be loaded)" + "|(Initial heap size set to a larger value than the maximum heap size)" + "|(java.lang.OutOfMemoryError)" + "|(Error: A JNI error has occurred, please check your installation and try again))"; diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotClassLinking/AOTClassLinkingVMOptions.java b/test/hotspot/jtreg/runtime/cds/appcds/aotClassLinking/AOTClassLinkingVMOptions.java new file mode 100644 index 00000000000..05fdf7c06d6 --- /dev/null +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotClassLinking/AOTClassLinkingVMOptions.java @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +/* + * @test + * @requires vm.cds + * @requires vm.cds.supports.aot.class.linking + * @requires vm.flagless + * @summary Disable CDS when incompatible options related to AOTClassLinking are used + * @library /test/jdk/lib/testlibrary + * /test/lib + * /test/hotspot/jtreg/runtime/cds/appcds + * /test/hotspot/jtreg/runtime/cds/appcds/test-classes + * @build Hello + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar app.jar Hello + * @run driver AOTClassLinkingVMOptions + */ + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import jdk.test.lib.cds.CDSTestUtils; +import jdk.test.lib.helpers.ClassFileInstaller; +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; + +public class AOTClassLinkingVMOptions { + static final String appJar = ClassFileInstaller.getJarPath("app.jar"); + + static int testCaseNum = 0; + static void testCase(String s) { + testCaseNum++; + System.out.println("Test case " + testCaseNum + ": " + s); + } + + public static void main(String[] args) throws Exception { + TestCommon.testDump(appJar, TestCommon.list("Hello"), + "-XX:+AOTClassLinking"); + + testCase("Archived full module graph must be enabled at runtime"); + TestCommon.run("-cp", appJar, "-Djdk.module.validation=1", "Hello") + .assertAbnormalExit("CDS archive has aot-linked classes." + + " It cannot be used when archived full module graph is not used"); + + testCase("Cannot use -Djava.system.class.loader"); + TestCommon.run("-cp", appJar, "-Djava.system.class.loader=dummy", "Hello") + .assertAbnormalExit("CDS archive has aot-linked classes." + + " It cannot be used when the java.system.class.loader property is specified."); + + testCase("Cannot use a different main module"); + TestCommon.run("-cp", appJar, "-Xlog:cds", "-m", "jdk.compiler/com.sun.tools.javac.Main") + .assertAbnormalExit("CDS archive has aot-linked classes." + + " It cannot be used when archived full module graph is not used."); + testCase("Cannot use security manager"); + TestCommon.run("-cp", appJar, "-Xlog:cds", "-Djava.security.manager=allow") + .assertAbnormalExit("CDS archive has aot-linked classes." + + " It cannot be used with -Djava.security.manager=allow."); + TestCommon.run("-cp", appJar, "-Xlog:cds", "-Djava.security.manager=default") + .assertAbnormalExit("CDS archive has aot-linked classes." + + " It cannot be used with -Djava.security.manager=default."); + + // NOTE: tests for ClassFileLoadHook + AOTClassLinking is in + // ../jvmti/ClassFileLoadHookTest.java + + boolean dynamicMode = Boolean.getBoolean("test.dynamic.cds.archive"); + if (!dynamicMode) { + // These tests need to dump the full module graph, which is not possible with + // dynamic dump. + modulePathTests(); + } + } + + static void modulePathTests() throws Exception { + CDSModulePathUtils.init(); + + testCase("Cannot use mis-matched module path"); + String goodModulePath = CDSModulePathUtils.getModulesDir().toString(); + TestCommon.testDump(null, CDSModulePathUtils.getAppClasses(), + "--module-path", goodModulePath, + "-XX:+AOTClassLinking", + "-m", CDSModulePathUtils.MAIN_MODULE); + TestCommon.run("-Xlog:cds", + "--module-path", goodModulePath, + "-m", CDSModulePathUtils.MAIN_MODULE) + .assertNormalExit("Using AOT-linked classes: true"); + + TestCommon.run("-Xlog:cds", + "--module-path", goodModulePath + "/bad", + "-m", CDSModulePathUtils.MAIN_MODULE) + .assertAbnormalExit("CDS archive has aot-linked classes. It cannot be used when archived full module graph is not used."); + + testCase("Cannot use mis-matched --add-modules"); + TestCommon.testDump(null, CDSModulePathUtils.getAppClasses(), + "--module-path", goodModulePath, + "-XX:+AOTClassLinking", + "--add-modules", CDSModulePathUtils.MAIN_MODULE); + TestCommon.run("-Xlog:cds", + "--module-path", goodModulePath, + "--add-modules", CDSModulePathUtils.MAIN_MODULE, + CDSModulePathUtils.MAIN_CLASS) + .assertNormalExit("Using AOT-linked classes: true"); + + TestCommon.run("-Xlog:cds", + "--module-path", goodModulePath + "/bad", + "--add-modules", CDSModulePathUtils.TEST_MODULE, + CDSModulePathUtils.MAIN_CLASS) + .assertAbnormalExit("Mismatched --add-modules module name(s)", + "CDS archive has aot-linked classes. It cannot be used when archived full module graph is not used."); + } +} + +// TODO: enhance and move this class to jdk.test.lib.cds.CDSModulePathUtils + +class CDSModulePathUtils { + private static String TEST_SRC = System.getProperty("test.root"); + private static Path USER_DIR = Paths.get(CDSTestUtils.getOutputDir()); + private static Path SRC_DIR = Paths.get(TEST_SRC, "runtime/cds/appcds/jigsaw/modulepath/src"); + private static Path MODS_DIR = Paths.get("mods"); + + public static String MAIN_MODULE = "com.bars"; + public static String TEST_MODULE = "com.foos"; + + public static String MAIN_CLASS = "com.bars.Main"; + public static String TEST_CLASS = "com.foos.Test"; + private static String appClasses[] = {MAIN_CLASS, TEST_CLASS}; + + private static Path modulesDir; + + // This directory contains all the modular jar files + // $USER_DIR/modules/com.bars.jar + // $USER_DIR/modules/com.foos.jar + static Path getModulesDir() { + return modulesDir; + } + + static String[] getAppClasses() { + return appClasses; + } + + static void init() throws Exception { + JarBuilder.compileModule(SRC_DIR.resolve(TEST_MODULE), + MODS_DIR.resolve(TEST_MODULE), + null); + JarBuilder.compileModule(SRC_DIR.resolve(MAIN_MODULE), + MODS_DIR.resolve(MAIN_MODULE), + MODS_DIR.toString()); + + String PATH_LIBS = "modules"; + modulesDir = Files.createTempDirectory(USER_DIR, PATH_LIBS); + Path mainJar = modulesDir.resolve(MAIN_MODULE + ".jar"); + Path testJar = modulesDir.resolve(TEST_MODULE + ".jar"); + + // modylibs contains both modules com.foos.jar, com.bars.jar + // build com.foos.jar + String classes = MODS_DIR.resolve(TEST_MODULE).toString(); + JarBuilder.createModularJar(testJar.toString(), classes, TEST_CLASS); + + // build com.bars.jar + classes = MODS_DIR.resolve(MAIN_MODULE).toString(); + JarBuilder.createModularJar(mainJar.toString(), classes, MAIN_CLASS); + } +} diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotClassLinking/BulkLoaderTest.java b/test/hotspot/jtreg/runtime/cds/appcds/aotClassLinking/BulkLoaderTest.java new file mode 100644 index 00000000000..49544f50032 --- /dev/null +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotClassLinking/BulkLoaderTest.java @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * 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. + * + */ + +// AOT-linked classes are loaded during VM bootstrap by the C++ class AOTLinkedClassBulkLoader. +// Make sure that the Module, Package, CodeSource and ProtectionDomain of these classes are +// set up properly. + +/* + * @test id=static + * @requires vm.cds.supports.aot.class.linking + * @library /test/jdk/lib/testlibrary /test/lib + * @build InitiatingLoaderTester + * @build BulkLoaderTest + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar BulkLoaderTestApp.jar BulkLoaderTestApp MyUtil InitiatingLoaderTester + * @run driver BulkLoaderTest STATIC + */ + +/* + * @test id=dynamic + * @requires vm.cds.supports.aot.class.linking + * @library /test/jdk/lib/testlibrary /test/lib + * @build InitiatingLoaderTester + * @build BulkLoaderTest + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar BulkLoaderTestApp.jar BulkLoaderTestApp MyUtil InitiatingLoaderTester + * @run driver BulkLoaderTest DYNAMIC + */ + +import java.io.File; +import java.lang.StackWalker.StackFrame; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.Set; +import jdk.test.lib.cds.CDSAppTester; +import jdk.test.lib.helpers.ClassFileInstaller; +import jdk.test.lib.process.OutputAnalyzer; + +public class BulkLoaderTest { + static final String appJar = ClassFileInstaller.getJarPath("BulkLoaderTestApp.jar"); + static final String mainClass = "BulkLoaderTestApp"; + + public static void main(String[] args) throws Exception { + Tester t = new Tester(); + + // Run with archived FMG loaded + t.run(args); + + // Run with an extra classpath -- archived FMG can still load. + { + String extraVmArgs[] = { + "-cp", + appJar + File.pathSeparator + "foobar.jar" + }; + OutputAnalyzer out = t.productionRun(extraVmArgs); + out.shouldHaveExitValue(0); + } + + // Run without archived FMG -- fail to load + { + String extraVmArgs[] = { + "-Xshare:on", + "-Xlog:cds", + "-Djdk.module.showModuleResolution=true" + }; + t.setCheckExitValue(false); + OutputAnalyzer out = t.productionRun(extraVmArgs); + out.shouldHaveExitValue(1); + out.shouldContain("CDS archive has aot-linked classes. It cannot be used when archived full module graph is not used."); + t.setCheckExitValue(true); + } + } + + static class Tester extends CDSAppTester { + public Tester() { + super(mainClass); + } + + @Override + public String classpath(RunMode runMode) { + return appJar; + } + + @Override + public String[] vmArgs(RunMode runMode) { + return new String[] { + "-Xlog:cds,cds+aot+load", + "-XX:+AOTClassLinking", + }; + } + + @Override + public String[] appCommandLine(RunMode runMode) { + return new String[] { + mainClass, + }; + } + } +} + +class BulkLoaderTestApp { + static String allPerms = "null.*.*java.security.Permissions.*,*java.security.AllPermission.*.*"; + + public static void main(String args[]) throws Exception { + checkClasses(); + checkInitiatingLoader(); + } + + // Check the ClassLoader/Module/Package/ProtectionDomain/CodeSource of classes that are aot-linked + static void checkClasses() throws Exception { + check(String.class, + "null", // loader + "module java.base", + "package java.lang", + "null", + allPerms); + + check(Class.forName("sun.util.logging.internal.LoggingProviderImpl"), + "null", + "module java.logging", + "package sun.util.logging.internal", + "null", + allPerms); + + + check(javax.tools.FileObject.class, + "^jdk.internal.loader.ClassLoaders[$]PlatformClassLoader@", + "module java.compiler", + "package javax.tools", + "jrt:/java.compiler ", + "jdk.internal.loader.ClassLoaders[$]PlatformClassLoader.*.*java.security.Permissions"); + + check(BulkLoaderTestApp.class, + "jdk.internal.loader.ClassLoaders[$]AppClassLoader@", + "^unnamed module @", + "package ", + "file:.*BulkLoaderTestApp.jar ", + "jdk.internal.loader.ClassLoaders[$]AppClassLoader.*.*java.security.Permissions"); + + check(Class.forName("com.sun.tools.javac.Main"), + "jdk.internal.loader.ClassLoaders[$]AppClassLoader@", + "module jdk.compiler", + "package com.sun.tools.javac", + "jrt:/jdk.compiler ", + "jdk.internal.loader.ClassLoaders[$]AppClassLoader.*.*java.security.Permissions"); + + doit(() -> { + Class lambdaClass = MyUtil.getCallerClass(1); + check(lambdaClass, + "jdk.internal.loader.ClassLoaders[$]AppClassLoader@", + "unnamed module", + "package ", + "file:.*BulkLoaderTestApp.jar ", + "jdk.internal.loader.ClassLoaders[$]AppClassLoader.*.*java.security.Permissions"); + + }); + } + + static void check(Class c, String loader, String module, String pkg, String codeSource, String protectionDomain) { + System.out.println("===================================================================="); + System.out.println(c.getName() + ", loader = " + c.getClassLoader()); + System.out.println(c.getName() + ", module = " + c.getModule()); + System.out.println(c.getName() + ", package = " + c.getPackage()); + System.out.println(c.getName() + ", CS = " + c.getProtectionDomain().getCodeSource()); + System.out.println(c.getName() + ", PD = " + c.getProtectionDomain()); + + expectMatch("" + c.getClassLoader(), loader); + expectMatch("" + c.getModule(), module); + expectSame("" + c.getPackage(), pkg); + expectMatch("" + c.getProtectionDomain().getCodeSource(), codeSource); + expectMatch("" + c.getProtectionDomain(), protectionDomain); + } + + static void expectSame(String a, String b) { + if (!a.equals(b)) { + throw new RuntimeException("Expected \"" + b + "\" but got \"" + a + "\""); + } + } + static void expectMatch(String string, String pattern) { + Matcher matcher = Pattern.compile(pattern, Pattern.DOTALL).matcher(string); + if (!matcher.find()) { + throw new RuntimeException("Expected pattern \"" + pattern + "\" but got \"" + string + "\""); + } + } + + static void doit(Runnable t) { + t.run(); + } + + static void checkInitiatingLoader() throws Exception { + try { + InitiatingLoaderTester.tryAccess(); + } catch (IllegalAccessError t) { + if (t.getMessage().contains("cannot access class jdk.internal.misc.Unsafe (in module java.base)")) { + System.out.println("Expected exception:"); + t.printStackTrace(System.out); + // Class.forName() should still work. We just can't resolve it in CP entries. + Class c = Class.forName("jdk.internal.misc.Unsafe"); + System.out.println("App loader can still resolve by name: " + c); + return; + } + throw new RuntimeException("Unexpected exception", t); + } + + throw new RuntimeException("Should not have succeeded"); + } +} + +class MyUtil { + // depth is 0-based -- i.e., depth==0 returns the class of the immediate caller of getCallerClass + static Class getCallerClass(int depth) { + // Need to add the frame of the getCallerClass -- so the immediate caller (depth==0) of this method + // is at stack.get(1) == stack.get(depth+1); + StackWalker walker = StackWalker.getInstance( + Set.of(StackWalker.Option.RETAIN_CLASS_REFERENCE, + StackWalker.Option.SHOW_HIDDEN_FRAMES)); + List stack = walker.walk(s -> s.limit(depth+2).collect(Collectors.toList())); + return stack.get(depth+1).getDeclaringClass(); + } +} diff --git a/test/hotspot/jtreg/runtime/cds/appcds/aotClassLinking/InitiatingLoaderTester.jasm b/test/hotspot/jtreg/runtime/cds/appcds/aotClassLinking/InitiatingLoaderTester.jasm new file mode 100644 index 00000000000..ae1b38e20a9 --- /dev/null +++ b/test/hotspot/jtreg/runtime/cds/appcds/aotClassLinking/InitiatingLoaderTester.jasm @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * 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. + * + */ + +/* + + +class InitiatingLoaderTester { + public static Object tryAccess() { + return jdk.internal.misc.Unsafe.getUnsafe(); + } +} + + + +*/ + + +super class InitiatingLoaderTester + version 66:0 +{ + Method "":"()V" + stack 1 locals 1 + { + aload_0; + invokespecial Method java/lang/Object."":"()V"; + return; + } + public static Method tryAccess:"()Ljava/lang/Object;" + stack 2 locals 0 + { + invokestatic Method jdk/internal/misc/Unsafe."getUnsafe":"()Ljdk/internal/misc/Unsafe;"; + areturn; + } + +} // end Class InitiatingLoaderTester diff --git a/test/hotspot/jtreg/runtime/cds/appcds/cacheObject/ArchiveHeapTestClass.java b/test/hotspot/jtreg/runtime/cds/appcds/cacheObject/ArchiveHeapTestClass.java index f5975569447..1603d8430b2 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/cacheObject/ArchiveHeapTestClass.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/cacheObject/ArchiveHeapTestClass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,7 @@ * @bug 8214781 8293187 * @summary Test for the -XX:ArchiveHeapTestClass flag * @requires vm.debug == true & vm.cds.write.archived.java.heap - * @modules java.base/sun.invoke.util java.logging + * @modules java.logging * @library /test/jdk/lib/testlibrary /test/lib * /test/hotspot/jtreg/runtime/cds/appcds * /test/hotspot/jtreg/runtime/cds/appcds/test-classes @@ -35,12 +35,13 @@ * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar boot.jar * CDSTestClassA CDSTestClassA$XX CDSTestClassA$YY * CDSTestClassB CDSTestClassC CDSTestClassD - * CDSTestClassE CDSTestClassF CDSTestClassG + * CDSTestClassE CDSTestClassF CDSTestClassG CDSTestClassG$MyEnum CDSTestClassG$Wrapper * pkg.ClassInPackage * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar app.jar Hello * @run driver ArchiveHeapTestClass */ +import jdk.test.lib.cds.CDSTestUtils; import jdk.test.lib.Platform; import jdk.test.lib.helpers.ClassFileInstaller; import jdk.test.lib.process.OutputAnalyzer; @@ -151,19 +152,24 @@ static void testDebugBuild() throws Exception { output = dumpBootAndHello(CDSTestClassD_name); mustFail(output, "Unable to find the static T_OBJECT field CDSTestClassD::archivedObjects"); - testCase("Use a disallowed class: in unnamed module but not in unname package"); - output = dumpBootAndHello(CDSTestClassE_name); - mustFail(output, "Class pkg.ClassInPackage not allowed in archive heap"); + if (!CDSTestUtils.isAOTClassLinkingEnabled()) { + testCase("Use a disallowed class: in unnamed module but not in unname package"); + output = dumpBootAndHello(CDSTestClassE_name); + mustFail(output, "Class pkg.ClassInPackage not allowed in archive heap"); - testCase("Use a disallowed class: not in java.base module"); - output = dumpBootAndHello(CDSTestClassF_name); - mustFail(output, "Class java.util.logging.Level not allowed in archive heap"); - - if (false) { // JDK-8293187 - testCase("sun.invoke.util.Wrapper"); - output = dumpBootAndHello(CDSTestClassG_name); - mustSucceed(output); + testCase("Use a disallowed class: not in java.base module"); + output = dumpBootAndHello(CDSTestClassF_name); + mustFail(output, "Class java.util.logging.Level not allowed in archive heap"); } + + testCase("Complex enums"); + output = dumpBootAndHello(CDSTestClassG_name, "-XX:+AOTClassLinking", "-Xlog:cds+class=debug"); + mustSucceed(output); + + TestCommon.run("-Xbootclasspath/a:" + bootJar, "-cp", appJar, "-Xlog:cds+heap,cds+init", + CDSTestClassG_name) + .assertNormalExit("init subgraph " + CDSTestClassG_name, + "Initialized from CDS"); } } @@ -171,12 +177,27 @@ class CDSTestClassA { static final String output = "CDSTestClassA. was executed"; static Object[] archivedObjects; static { - archivedObjects = new Object[5]; - archivedObjects[0] = output; - archivedObjects[1] = new CDSTestClassA[0]; - archivedObjects[2] = new YY(); - archivedObjects[3] = new int[0]; - archivedObjects[4] = new int[2][2]; + // The usual convention would be to call this here: + // CDS.initializeFromArchive(CDSTestClassA.class); + // However, the CDS class is not exported to the unnamed module by default, + // and we don't want to use "--add-exports java.base/jdk.internal.misc=ALL-UNNAMED", as + // that would disable the archived full module graph, which will disable + // CDSConfig::is_using_aot_linked_classes(). + // + // Instead, HeapShared::initialize_test_class_from_archive() will set up the + // "archivedObjects" field first, before calling CDSTestClassA.. So + // if we see that archivedObjects is magically non-null here, that means + // it has been restored from the CDS archive. + if (archivedObjects == null) { + archivedObjects = new Object[5]; + archivedObjects[0] = output; + archivedObjects[1] = new CDSTestClassA[0]; + archivedObjects[2] = new YY(); + archivedObjects[3] = new int[0]; + archivedObjects[4] = new int[2][2]; + } else { + System.out.println("Initialized from CDS"); + } System.out.println(output); System.out.println("CDSTestClassA module = " + CDSTestClassA.class.getModule()); System.out.println("CDSTestClassA package = " + CDSTestClassA.class.getPackage()); @@ -269,8 +290,143 @@ class CDSTestClassF { class CDSTestClassG { static Object[] archivedObjects; static { - // Not in java.base - archivedObjects = new Object[1]; - archivedObjects[0] = sun.invoke.util.Wrapper.BOOLEAN; + if (archivedObjects == null) { + archivedObjects = new Object[13]; + archivedObjects[0] = Wrapper.BOOLEAN; + archivedObjects[1] = Wrapper.INT.zero(); + archivedObjects[2] = Wrapper.DOUBLE.zero(); + archivedObjects[3] = MyEnum.DUMMY1; + + archivedObjects[4] = Boolean.class; + archivedObjects[5] = Byte.class; + archivedObjects[6] = Character.class; + archivedObjects[7] = Short.class; + archivedObjects[8] = Integer.class; + archivedObjects[9] = Long.class; + archivedObjects[10] = Float.class; + archivedObjects[11] = Double.class; + archivedObjects[12] = Void.class; + } else { + System.out.println("Initialized from CDS"); + } + } + + public static void main(String args[]) { + if (archivedObjects[0] != Wrapper.BOOLEAN) { + throw new RuntimeException("Huh 0"); + } + + if (archivedObjects[1] != Wrapper.INT.zero()) { + throw new RuntimeException("Huh 1"); + } + + if (archivedObjects[2] != Wrapper.DOUBLE.zero()) { + throw new RuntimeException("Huh 2"); + } + + if (archivedObjects[3] != MyEnum.DUMMY1) { + throw new RuntimeException("Huh 3"); + } + + if (MyEnum.BOOLEAN != true) { + throw new RuntimeException("Huh 10.1"); + } + if (MyEnum.BYTE != -128) { + throw new RuntimeException("Huh 10.2"); + } + if (MyEnum.CHAR != 'c') { + throw new RuntimeException("Huh 10.3"); + } + if (MyEnum.SHORT != -12345) { + throw new RuntimeException("Huh 10.4"); + } + if (MyEnum.INT != -123456) { + throw new RuntimeException("Huh 10.5"); + } + if (MyEnum.LONG != 0x1234567890L) { + throw new RuntimeException("Huh 10.6"); + } + if (MyEnum.LONG2 != -0x1234567890L) { + throw new RuntimeException("Huh 10.7"); + } + if (MyEnum.FLOAT != 567891.0f) { + throw new RuntimeException("Huh 10.8"); + } + if (MyEnum.DOUBLE != 12345678905678.890) { + throw new RuntimeException("Huh 10.9"); + } + + checkClass(4, Boolean.class); + checkClass(5, Byte.class); + checkClass(6, Character.class); + checkClass(7, Short.class); + checkClass(8, Integer.class); + checkClass(9, Long.class); + checkClass(10, Float.class); + checkClass(11, Double.class); + checkClass(12, Void.class); + + System.out.println("Success!"); + } + + static void checkClass(int index, Class c) { + if (archivedObjects[index] != c) { + throw new RuntimeException("archivedObjects[" + index + "] should be " + c); + } + } + + // Simplified version of sun.invoke.util.Wrapper + public enum Wrapper { + // wrapperType simple primitiveType simple char emptyArray + BOOLEAN( Boolean.class, "Boolean", boolean.class, "boolean", 'Z', new boolean[0]), + INT ( Integer.class, "Integer", int.class, "int", 'I', new int[0]), + DOUBLE ( Double.class, "Double", double.class, "double", 'D', new double[0]) + ; + + public static final int COUNT = 10; + private static final Object DOUBLE_ZERO = (Double)(double)0; + + private final Class wrapperType; + private final Class primitiveType; + private final char basicTypeChar; + private final String basicTypeString; + private final Object emptyArray; + + Wrapper(Class wtype, + String wtypeName, + Class ptype, + String ptypeName, + char tchar, + Object emptyArray) { + this.wrapperType = wtype; + this.primitiveType = ptype; + this.basicTypeChar = tchar; + this.basicTypeString = String.valueOf(this.basicTypeChar); + this.emptyArray = emptyArray; + } + + public Object zero() { + return switch (this) { + case BOOLEAN -> Boolean.FALSE; + case INT -> (Integer)0; + case DOUBLE -> DOUBLE_ZERO; + default -> null; + }; + } + } + + enum MyEnum { + DUMMY1, + DUMMY2; + + static final boolean BOOLEAN = true; + static final byte BYTE = -128; + static final short SHORT = -12345; + static final char CHAR = 'c'; + static final int INT = -123456; + static final long LONG = 0x1234567890L; + static final long LONG2 = -0x1234567890L; + static final float FLOAT = 567891.0f; + static final double DOUBLE = 12345678905678.890; } } diff --git a/test/hotspot/jtreg/runtime/cds/appcds/customLoader/CustomClassListDump.java b/test/hotspot/jtreg/runtime/cds/appcds/customLoader/CustomClassListDump.java index 625ef1fbc92..27072bea35e 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/customLoader/CustomClassListDump.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/customLoader/CustomClassListDump.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. * 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,7 +94,7 @@ public static void main(String[] args) throws Exception { .shouldContain("unreg CustomLoadee") .shouldContain("unreg CustomLoadee2") .shouldContain("unreg CustomLoadee3Child") - .shouldContain("unreg OldClass ** unlinked"); + .shouldContain("unreg OldClass old unlinked"); // Use the dumped static archive opts = (new CDSOptions()) diff --git a/test/hotspot/jtreg/runtime/cds/appcds/jvmti/ClassFileLoadHookTest.java b/test/hotspot/jtreg/runtime/cds/appcds/jvmti/ClassFileLoadHookTest.java index 5751f62e148..7ccd4e5d312 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/jvmti/ClassFileLoadHookTest.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/jvmti/ClassFileLoadHookTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -96,5 +96,23 @@ public static void main(String[] args) throws Exception { "ClassFileLoadHook", "" + ClassFileLoadHook.TestCaseId.SHARING_ON_CFLH_ON); TestCommon.checkExec(out); + + // JEP 483: if dumped with -XX:+AOTClassLinking, cannot use archive when CFLH is enabled + TestCommon.testDump(appJar, sharedClasses, useWb, "-XX:+AOTClassLinking"); + out = TestCommon.exec(appJar, + "-XX:+UnlockDiagnosticVMOptions", + "-XX:+WhiteBoxAPI", useWb, + "-agentlib:SimpleClassFileLoadHook=LoadMe,beforeHook,after_Hook", + "-Xlog:cds", + "ClassFileLoadHook", + "" + ClassFileLoadHook.TestCaseId.SHARING_ON_CFLH_ON); + if (out.contains("Using AOT-linked classes: false (static archive: no aot-linked classes")) { + // JTREG is executed with VM options that do not support -XX:+AOTClassLinking, so + // the static archive was not created with aot-linked classes. + out.shouldHaveExitValue(0); + } else { + out.shouldContain("CDS archive has aot-linked classes. It cannot be used when JVMTI ClassFileLoadHook is in use."); + out.shouldNotHaveExitValue(0); + } } } diff --git a/test/hotspot/jtreg/runtime/cds/appcds/jvmti/redefineClasses/OldClassAndRedefineClass.java b/test/hotspot/jtreg/runtime/cds/appcds/jvmti/redefineClasses/OldClassAndRedefineClass.java index 8ca8b7d952e..7581b2367aa 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/jvmti/redefineClasses/OldClassAndRedefineClass.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/jvmti/redefineClasses/OldClassAndRedefineClass.java @@ -61,8 +61,8 @@ public static void runTest() throws Throwable { String agentCmdArg = "-javaagent:redefineagent.jar"; OutputAnalyzer out = TestCommon.testDump(appJar, sharedClasses, "-Xlog:cds,cds+class=debug"); - out.shouldMatch("klasses.*OldSuper.[*][*].unlinked") - .shouldMatch("klasses.*ChildOldSuper.[*][*].unlinked"); + out.shouldMatch("klasses.*OldSuper.* unlinked") + .shouldMatch("klasses.*ChildOldSuper.* unlinked"); out = TestCommon.exec( appJar, diff --git a/test/hotspot/jtreg/runtime/cds/appcds/resolvedConstants/AOTLinkedLambdas.java b/test/hotspot/jtreg/runtime/cds/appcds/resolvedConstants/AOTLinkedLambdas.java new file mode 100644 index 00000000000..5fb0a30cd61 --- /dev/null +++ b/test/hotspot/jtreg/runtime/cds/appcds/resolvedConstants/AOTLinkedLambdas.java @@ -0,0 +1,388 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * 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 AOT resolution of lambda expressions + * @bug 8340836 + * @requires vm.cds + * @requires vm.cds.supports.aot.class.linking + * @library /test/lib /test/hotspot/jtreg/runtime/cds/appcds/test-classes/ + * @build AOTLinkedLambdas + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar app.jar + * AOTLinkedLambdasApp InitTracker + * IntfWithNoClinit IntfWithNoClinit2 + * IA IB IC ID1 ID2 IE1 IE2 IF1 IF2 IG1 IG2 IH1 IH2 IH3 + * FooA FooB + * BarA BarB BarC + * @run driver AOTLinkedLambdas + */ + +import java.util.function.Supplier; +import static java.util.stream.Collectors.*; +import jdk.test.lib.cds.CDSOptions; +import jdk.test.lib.cds.CDSTestUtils; +import jdk.test.lib.helpers.ClassFileInstaller; +import jdk.test.lib.process.OutputAnalyzer; + +public class AOTLinkedLambdas { + static final String classList = "AOTLinkedLambdas.classlist"; + static final String appJar = ClassFileInstaller.getJarPath("app.jar"); + static final String mainClass = AOTLinkedLambdasApp.class.getName(); + + public static void main(String[] args) throws Exception { + CDSTestUtils.dumpClassList(classList, "-cp", appJar, mainClass) + .assertNormalExit(output -> { + output.shouldContain("Hello AOTLinkedLambdasApp"); + }); + + CDSOptions opts = (new CDSOptions()) + .addPrefix("-XX:ExtraSharedClassListFile=" + classList, + "-XX:+AOTClassLinking", + "-Xlog:cds+resolve=trace", + "-Xlog:cds+class=debug", + "-cp", appJar); + + OutputAnalyzer dumpOut = CDSTestUtils.createArchiveAndCheck(opts); + dumpOut.shouldContain("Can aot-resolve Lambda proxy of interface type IA"); + dumpOut.shouldContain("Can aot-resolve Lambda proxy of interface type IB"); + dumpOut.shouldContain("Cannot aot-resolve Lambda proxy of interface type IC"); + dumpOut.shouldContain("Can aot-resolve Lambda proxy of interface type ID2"); + dumpOut.shouldContain("Cannot aot-resolve Lambda proxy of interface type IE2"); // unsupported = IE1 + dumpOut.shouldContain("Cannot aot-resolve Lambda proxy of interface type IF2"); + dumpOut.shouldContain("Cannot aot-resolve Lambda proxy of interface type IG2"); + dumpOut.shouldContain("Cannot aot-resolve Lambda proxy of interface type IH3"); // unsupported = IH1 + + CDSOptions runOpts = (new CDSOptions()) + .setUseVersion(false) + .addPrefix("-Xlog:cds", + "-esa", // see JDK-8340836 + "-cp", appJar) + .addSuffix(mainClass); + + CDSTestUtils.run(runOpts) + .assertNormalExit("Hello AOTLinkedLambdasApp", + "hello, world"); + } +} + +class AOTLinkedLambdasApp { + static { + System.out.println("AOTLinkedLambdasApp."); + } + public static void main(String args[]) { + System.out.println("Hello AOTLinkedLambdasApp"); + + // (1) Simple tests + var words = java.util.List.of("hello", "fuzzy", "world"); + System.out.println(words.stream().filter(w->!w.contains("u")).collect(joining(", "))); + // => hello, world + + // (2) Test for order. + testClinitOrder(); + } + + + // Check that aot-linking of lambdas does not cause to be skipped or + // otherwise executed in the wrong order. + // + // A lambda is declared to implement an interface X, but it also implicitly + // implements all super interfaces of X. + // + // For any interface IN that's implemented by a lambda, if IN has declared + // a non-abstract, non-static method (JVMS 5.5. Initialization), IN must be + // initialized before the lambda can be linked. If IN:: exists, the + // initialization of IN can have side effects. + // + // AOTConstantPoolResolver::is_indy_resolution_deterministic() excludes + // any lambda if initializing its interfaces can cause side effects. This test + // checks that such exclusions are working as expected. + // + // This test also proves that is_indy_resolution_deterministic() doen't need to check + // for all other types that are mentioned by the lambda call site, as those classes + // will not be initialized as part of linking the lambda. + static void testClinitOrder() { + /* + * An indy callsite is associated with the following MethodType and MethodHandles: + * + * https://github.com/openjdk/jdk/blob/580eb62dc097efeb51c76b095c1404106859b673/src/java.base/share/classes/java/lang/invoke/LambdaMetafactory.java#L293-L309 + * + * MethodType factoryType The expected signature of the {@code CallSite}. The + * parameter types represent the types of capture variables; + * the return type is the interface to implement. When + * used with {@code invokedynamic}, this is provided by + * the {@code NameAndType} of the {@code InvokeDynamic} + * + * MethodType interfaceMethodType Signature and return type of method to be + * implemented by the function object. + * + * MethodHandle implementation A direct method handle describing the implementation + * method which should be called (with suitable adaptation + * of argument types and return types, and with captured + * arguments prepended to the invocation arguments) at + * invocation time. + * + * MethodType dynamicMethodType The signature and return type that should + * be enforced dynamically at invocation time. + * In simple use cases this is the same as + * {@code interfaceMethodType}. + */ + + // Initial condition: no used by our Foo* and Bar* types have been called. + InitTracker.assertOrder("InitTracker"); + + //============================== + // Case (i) -- Check for types used by factoryType, interfaceMethodType and dynamicMethodType + // (Note: no tests for captured variables in factoryType yet; will be tested in case (ii)) + // factoryType = "()LIntfWithNoClinit; + // interfaceMethodType = "(LFooB;)LFooA;" + // implementation = "REF_invokeStatic AOTLinkedLambdasApp.implAB:(LBarB;)LBarA;" + // dynamicMethodType = "(LBarB;)LBarA;" + IntfWithNoClinit noclinit = AOTLinkedLambdasApp::implAB; + + // None of the Foo? and Bar? types used by the lambda should have been initialized yet, even though + // the indy callsite has been resolved now. + InitTracker.assertOrder("InitTracker"); + + BarB barB = new BarB(); + InitTracker.assertOrder("InitTracker, FooB, BarB"); + BarA barA = noclinit.doit(barB); + System.out.println(barB); + InitTracker.assertOrder("InitTracker, FooB, BarB, FooA, BarA"); + + //============================== + // Case (ii) -- Check for types used by captured variables in factoryType + BarC barC = null; + IntfWithNoClinit2 noclinit2 = () -> { return barC.hashCode(); }; + try { + noclinit2.doit(); + throw new RuntimeException("NullPointerException should have been thrown"); + } catch (NullPointerException npe) { + // expected + } + // BarC shouldn't be initialized as no instances of it has been created. + InitTracker.assertOrder("InitTracker, FooB, BarB, FooA, BarA"); + + + //============================== + // (IA) No default methods -- is not initialized during lambda linking. Lambda can be archived. + IA ia = () -> {}; + ia.doit(); + InitTracker.assertOrder("InitTracker, FooB, BarB, FooA, BarA"); + System.out.println(IA._dummy); + InitTracker.assertOrder("InitTracker, FooB, BarB, FooA, BarA, IA"); + + //============================== + // (IB) Has default method but has not -- OK to initialize IB during lambda linking. Lambda can be archived. + IB ib = () -> {}; + ib.doit(); + InitTracker.assertOrder("InitTracker, FooB, BarB, FooA, BarA, IA"); + + //============================== + // (IC) Has both default method and -- cannot AOT link the lambda + IC ic = () -> {}; + InitTracker.assertOrder("InitTracker, FooB, BarB, FooA, BarA, IA, IC"); + ic.doit(); + + //============================== + // ID1 - has default method, but no + // ID2 - has , but no default method + ID2 id2 = () -> {}; + id2.doit(); + InitTracker.assertOrder("InitTracker, FooB, BarB, FooA, BarA, IA, IC"); + System.out.println(ID2._dummy); + InitTracker.assertOrder("InitTracker, FooB, BarB, FooA, BarA, IA, IC, ID2"); + + //============================== + // IE1 - has both default method and + // IE2 - has , but no default method + IE2 ie2 = () -> {}; + InitTracker.assertOrder("InitTracker, FooB, BarB, FooA, BarA, IA, IC, ID2, IE1"); + System.out.println(IE2._dummy); + InitTracker.assertOrder("InitTracker, FooB, BarB, FooA, BarA, IA, IC, ID2, IE1, IE2"); + + //============================== + // IF1 - has , but no default method + // IF2 - has both default method and + IF2 if2 = () -> {}; + InitTracker.assertOrder("InitTracker, FooB, BarB, FooA, BarA, IA, IC, ID2, IE1, IE2, IF2"); + System.out.println(IF1._dummy); + InitTracker.assertOrder("InitTracker, FooB, BarB, FooA, BarA, IA, IC, ID2, IE1, IE2, IF2, IF1"); + + //============================== + // IG1 - has both default method and + // IG2 - has both default method and + IG2 ig2 = () -> {}; + InitTracker.assertOrder("InitTracker, FooB, BarB, FooA, BarA, IA, IC, ID2, IE1, IE2, IF2, IF1, IG1, IG2"); + + //============================== + // Similar to IE1/IE2, but IH3 is one more level away from IH1 + // IH1 - has both default method and + // IH2 - has , but no default method + // IH3 - has , but no default method + IH3 ih3 = () -> {}; + InitTracker.assertOrder("InitTracker, FooB, BarB, FooA, BarA, IA, IC, ID2, IE1, IE2, IF2, IF1, IG1, IG2, IH1"); + System.out.println(IH3._dummy); + InitTracker.assertOrder("InitTracker, FooB, BarB, FooA, BarA, IA, IC, ID2, IE1, IE2, IF2, IF1, IG1, IG2, IH1, IH3"); + System.out.println(IH2._dummy); + InitTracker.assertOrder("InitTracker, FooB, BarB, FooA, BarA, IA, IC, ID2, IE1, IE2, IF2, IF1, IG1, IG2, IH1, IH3, IH2"); + } + + static BarA implAB(BarB param) { + return new BarA(param); + } +} + + +// An interface with no method. A lambda implementing this +// interface can be AOT-linked. +@FunctionalInterface +interface IntfWithNoClinit { + X doit(Y param); +} + +// Another interface with no method. A lambda implementing this +// interface can be AOT-linked. +@FunctionalInterface +interface IntfWithNoClinit2 { + int doit(); +} + + +// (IA) No default methods -- is not initialized during lambda linking. Lambda can be archived. +@FunctionalInterface interface IA { + static int _dummy = InitTracker.trackEvent("IA"); + void doit(); +} + +// (IB) Has default method but has not -- OK to initialize IB during lambda linking. Lambda can be archived. +@FunctionalInterface interface IB { + default int dummy() { return 0; } + void doit(); +} + +// (IC) Has both default method and -- cannot AOT link the lambda +@FunctionalInterface interface IC { + static int _dummy = InitTracker.trackEvent("IC"); + default int dummy() { return _dummy; } + void doit(); +} + +// (ID1/ID2) +@FunctionalInterface interface ID1 { // has default method, but no + default int dummy() { return 0; } + void doit(); +} + +@FunctionalInterface interface ID2 extends ID1 { // has , but no default method + static int _dummy = InitTracker.trackEvent("ID2"); +} + +// (IE1/IE2) +@FunctionalInterface interface IE1 { // has default method and + static int _dummy = InitTracker.trackEvent("IE1"); + default int dummy() { return _dummy; } + void doit(); +} + +@FunctionalInterface interface IE2 extends IE1 { // has , but no default method + static int _dummy = InitTracker.trackEvent("IE2"); +} + +// (IF1/IF2) +@FunctionalInterface interface IF1 { // has , but no default method + static int _dummy = InitTracker.trackEvent("IF1"); + void doit(); +} + +@FunctionalInterface interface IF2 extends IF1 { // has default method and + static int _dummy = InitTracker.trackEvent("IF2"); + default int dummy() { return 0; } +} + +// (IG1/IG2) +@FunctionalInterface interface IG1 { // has default method and + static int _dummy = InitTracker.trackEvent("IG1"); + default int dummy() { return _dummy; } + void doit(); +} + +@FunctionalInterface interface IG2 extends IG1 { // has default method and + static int _dummy = InitTracker.trackEvent("IG2"); + default int dummy() { return _dummy; } +} + +// (IH1/IH2/IH3) +@FunctionalInterface interface IH1 { // has default method and + static int _dummy = InitTracker.trackEvent("IH1"); + default int dummy() { return _dummy; } + void doit(); +} + +@FunctionalInterface interface IH2 extends IH1 { // has but no default method + static int _dummy = InitTracker.trackEvent("IH2"); +} + +@FunctionalInterface interface IH3 extends IH2 { // has but no default method + static int _dummy = InitTracker.trackEvent("IH3"); +} + + +class InitTracker { + static String actualOrder = "InitTracker"; + static int trackEvent(String event) { + actualOrder += ", " + event; + return actualOrder.lastIndexOf(','); + } + static void assertOrder(String wantOrder) { + System.out.println("wantOrder = " + wantOrder); + System.out.println("actualOrder = " + actualOrder); + if (!actualOrder.equals(wantOrder)) { + throw new RuntimeException("Want order: {" + wantOrder + "}, but got {" + actualOrder + "}"); + } + } +} + +interface FooA { + static final int _dummy = InitTracker.trackEvent("FooA"); + default int dummy() { return _dummy; } +} + +interface FooB { + static final int _dummy = InitTracker.trackEvent("FooB"); + default int dummy() { return _dummy; } +} + +class BarA implements FooA { + static {InitTracker.trackEvent("BarA");} + BarA(BarB dummy) {} +} + +class BarB implements FooB { + static {InitTracker.trackEvent("BarB");} +} + +class BarC { + static {InitTracker.trackEvent("BarC");} +} diff --git a/test/hotspot/jtreg/runtime/cds/appcds/resolvedConstants/AOTLinkedVarHandles.java b/test/hotspot/jtreg/runtime/cds/appcds/resolvedConstants/AOTLinkedVarHandles.java new file mode 100644 index 00000000000..2098ebc2c71 --- /dev/null +++ b/test/hotspot/jtreg/runtime/cds/appcds/resolvedConstants/AOTLinkedVarHandles.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * 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 AOT resolution of VarHandle invocation + * @bug 8343245 + * @requires vm.cds + * @requires vm.cds.supports.aot.class.linking + * @library /test/lib + * @build AOTLinkedVarHandles + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar app.jar + * AOTLinkedVarHandlesApp AOTLinkedVarHandlesApp$Data + * @run driver AOTLinkedVarHandles + */ + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; +import jdk.test.lib.cds.CDSOptions; +import jdk.test.lib.cds.CDSTestUtils; +import jdk.test.lib.helpers.ClassFileInstaller; +import jdk.test.lib.process.OutputAnalyzer; + +public class AOTLinkedVarHandles { + static final String classList = "AOTLinkedVarHandles.classlist"; + static final String appJar = ClassFileInstaller.getJarPath("app.jar"); + static final String mainClass = AOTLinkedVarHandlesApp.class.getName(); + + public static void main(String[] args) throws Exception { + CDSTestUtils.dumpClassList(classList, "-cp", appJar, mainClass) + .assertNormalExit(output -> { + output.shouldContain("Hello AOTLinkedVarHandlesApp"); + }); + + CDSOptions opts = (new CDSOptions()) + .addPrefix("-XX:ExtraSharedClassListFile=" + classList, + "-XX:+AOTClassLinking", + "-Xlog:cds+resolve=trace", + "-Xlog:cds+class=debug", + "-cp", appJar); + + String s = "archived method CP entry.* AOTLinkedVarHandlesApp "; + OutputAnalyzer dumpOut = CDSTestUtils.createArchiveAndCheck(opts); + dumpOut.shouldMatch(s + "java/lang/invoke/VarHandle.compareAndExchangeAcquire:\\(\\[DIDI\\)D =>"); + dumpOut.shouldMatch(s + "java/lang/invoke/VarHandle.get:\\(\\[DI\\)D => "); + + CDSOptions runOpts = (new CDSOptions()) + .setUseVersion(false) + .addPrefix("-Xlog:cds", + "-esa", + "-cp", appJar) + .addSuffix(mainClass); + + CDSTestUtils.run(runOpts) + .assertNormalExit("Hello AOTLinkedVarHandlesApp"); + } +} + +class AOTLinkedVarHandlesApp { + static final VarHandle initialized; + static final VarHandle lazy; + static long longField = 5678; + static long seed; + + static { + try { + lazy = MethodHandles.lookup().findStaticVarHandle(Data.class, "longField", long.class); + initialized = MethodHandles.lookup().findStaticVarHandle(AOTLinkedVarHandlesApp.class, "longField", long.class); + } catch (ReflectiveOperationException e) { + throw new RuntimeException(e); + } + } + + static class Data { + static long longField = seed; + } + + public static void main(String args[]) { + seed = 1234; + System.out.println("Hello AOTLinkedVarHandlesApp"); + long a = (long) lazy.get(); + long b = (long) initialized.get(); + System.out.println(a); + System.out.println(b); + if (a != 1234) { + throw new RuntimeException("Data class should not be initialized: " + a); + } + if (b != 5678) { + throw new RuntimeException("VarHandle.get() failed: " + b); + } + + VarHandle vh = MethodHandles.arrayElementVarHandle(double[].class); + double[] array = new double[] {1.0}; + int index = 0; + int v = 4; + + // JDK-8343245 -- this generates "java.lang.invoke.LambdaForm$VH/0x80????" hidden class + double r = (double) vh.compareAndExchangeAcquire(array, index, 1.0, v); + if (r != 1.0) { + throw new RuntimeException("Unexpected result: " + r); + } + r = (double) vh.get(array, index); + if (r != 4.0) { + throw new RuntimeException("Unexpected result: " + r); + } + } +} diff --git a/test/hotspot/jtreg/runtime/cds/appcds/resolvedConstants/ResolvedConstants.java b/test/hotspot/jtreg/runtime/cds/appcds/resolvedConstants/ResolvedConstants.java index 474fa65d6ea..7d3335b9db6 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/resolvedConstants/ResolvedConstants.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/resolvedConstants/ResolvedConstants.java @@ -24,26 +24,40 @@ /* * @test - * @summary Dump time resolutiom of constant pool entries. + * @summary Dump time resolution of constant pool entries. * @requires vm.cds + * @requires vm.cds.supports.aot.class.linking * @requires vm.compMode != "Xcomp" - * @library /test/lib + * @library /test/lib /test/hotspot/jtreg/runtime/cds/appcds/test-classes/ + * @build OldProvider OldClass OldConsumer StringConcatTestOld * @build ResolvedConstants - * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar app.jar ResolvedConstantsApp ResolvedConstantsFoo ResolvedConstantsBar + * @run driver jdk.test.lib.helpers.ClassFileInstaller -jar app.jar + * ResolvedConstantsApp ResolvedConstantsFoo ResolvedConstantsBar + * MyInterface InterfaceWithClinit NormalClass + * OldProvider OldClass OldConsumer SubOfOldClass + * StringConcatTest StringConcatTestOld * @run driver ResolvedConstants */ +import java.util.function.Consumer; import jdk.test.lib.cds.CDSOptions; import jdk.test.lib.cds.CDSTestUtils; import jdk.test.lib.helpers.ClassFileInstaller; +import jdk.test.lib.process.OutputAnalyzer; public class ResolvedConstants { static final String classList = "ResolvedConstants.classlist"; static final String appJar = ClassFileInstaller.getJarPath("app.jar"); static final String mainClass = ResolvedConstantsApp.class.getName(); + static boolean aotClassLinking; public static void main(String[] args) throws Exception { - // dump class list + test(false); + test(true); + } + + static void test(boolean testMode) throws Exception { + aotClassLinking = testMode; CDSTestUtils.dumpClassList(classList, "-cp", appJar, mainClass) .assertNormalExit(output -> { output.shouldContain("Hello ResolvedConstantsApp"); @@ -52,78 +66,109 @@ public static void main(String[] args) throws Exception { CDSOptions opts = (new CDSOptions()) .addPrefix("-XX:ExtraSharedClassListFile=" + classList, "-cp", appJar, - "-Xlog:cds+resolve=trace"); - CDSTestUtils.createArchiveAndCheck(opts) + "-Xlog:cds+resolve=trace", + "-Xlog:cds+class=debug"); + if (aotClassLinking) { + opts.addPrefix("-XX:+AOTClassLinking"); + } else { + opts.addPrefix("-XX:-AOTClassLinking"); + } + + OutputAnalyzer out = CDSTestUtils.createArchiveAndCheck(opts); // Class References --- // Always resolve reference when a class references itself - .shouldMatch("cds,resolve.*archived klass.* ResolvedConstantsApp app => ResolvedConstantsApp app") + out.shouldMatch(ALWAYS("klass.* ResolvedConstantsApp app => ResolvedConstantsApp app")) // Always resolve reference when a class references a super class - .shouldMatch("cds,resolve.*archived klass.* ResolvedConstantsApp app => java/lang/Object boot") - .shouldMatch("cds,resolve.*archived klass.* ResolvedConstantsBar app => ResolvedConstantsFoo app") + .shouldMatch(ALWAYS("klass.* ResolvedConstantsApp app => java/lang/Object boot")) + .shouldMatch(ALWAYS("klass.* ResolvedConstantsBar app => ResolvedConstantsFoo app")) // Always resolve reference when a class references a super interface - .shouldMatch("cds,resolve.*archived klass.* ResolvedConstantsApp app => java/lang/Runnable boot") + .shouldMatch(ALWAYS("klass.* ResolvedConstantsApp app => java/lang/Runnable boot")) - // java/lang/System is in the root loader but ResolvedConstantsApp is loaded by the app loader. - // Even though System is in the vmClasses list, when ResolvedConstantsApp looks up - // "java/lang/System" in its ConstantPool, the app loader may not have resolved the System - // class yet (i.e., there's no initiaited class entry for System in the app loader's dictionary) - .shouldMatch("cds,resolve.*reverted klass.* ResolvedConstantsApp .*java/lang/System") + // Without -XX:+AOTClassLinking: + // java/lang/System is in the boot loader but ResolvedConstantsApp is loaded by the app loader. + // Even though System is in the vmClasses list, when ResolvedConstantsApp looks up + // "java/lang/System" in its ConstantPool, the app loader may not have resolved the System + // class yet (i.e., there's no initiaited class entry for System in the app loader's dictionary) + .shouldMatch(AOTLINK_ONLY("klass.* ResolvedConstantsApp .*java/lang/System")) // Field References --- // Always resolve references to fields in the current class or super class(es) - .shouldMatch("cds,resolve.*archived field.* ResolvedConstantsBar => ResolvedConstantsBar.b:I") - .shouldMatch("cds,resolve.*archived field.* ResolvedConstantsBar => ResolvedConstantsBar.a:I") - .shouldMatch("cds,resolve.*archived field.* ResolvedConstantsBar => ResolvedConstantsFoo.a:I") + .shouldMatch(ALWAYS("field.* ResolvedConstantsBar => ResolvedConstantsBar.b:I")) + .shouldMatch(ALWAYS("field.* ResolvedConstantsBar => ResolvedConstantsBar.a:I")) + .shouldMatch(ALWAYS("field.* ResolvedConstantsBar => ResolvedConstantsFoo.a:I")) + .shouldMatch(ALWAYS("field.* ResolvedConstantsFoo => ResolvedConstantsFoo.a:I")) - // Do not resolve field references to child classes - .shouldMatch("cds,resolve.*archived field.* ResolvedConstantsFoo => ResolvedConstantsFoo.a:I") - .shouldMatch("cds,resolve.*reverted field.* ResolvedConstantsFoo ResolvedConstantsBar.a:I") - .shouldMatch("cds,resolve.*reverted field.* ResolvedConstantsFoo ResolvedConstantsBar.b:I") + // Resolve field references to child classes ONLY when using -XX:+AOTClassLinking + .shouldMatch(AOTLINK_ONLY("field.* ResolvedConstantsFoo => ResolvedConstantsBar.a:I")) + .shouldMatch(AOTLINK_ONLY("field.* ResolvedConstantsFoo => ResolvedConstantsBar.b:I")) - // Do not resolve field references to unrelated classes - .shouldMatch("cds,resolve.*reverted field.* ResolvedConstantsApp ResolvedConstantsBar.a:I") - .shouldMatch("cds,resolve.*reverted field.* ResolvedConstantsApp ResolvedConstantsBar.b:I") + // Resolve field references to unrelated classes ONLY when using -XX:+AOTClassLinking + .shouldMatch(AOTLINK_ONLY("field.* ResolvedConstantsApp => ResolvedConstantsBar.a:I")) + .shouldMatch(AOTLINK_ONLY("field.* ResolvedConstantsApp => ResolvedConstantsBar.b:I")) // Method References --- // Should resolve references to own constructor - .shouldMatch("cds,resolve.*archived method .* ResolvedConstantsApp ResolvedConstantsApp.:") + .shouldMatch(ALWAYS("method.* ResolvedConstantsApp ResolvedConstantsApp.:")) // Should resolve references to super constructor - .shouldMatch("cds,resolve.*archived method .* ResolvedConstantsApp java/lang/Object.:") + .shouldMatch(ALWAYS("method.* ResolvedConstantsApp java/lang/Object.:")) // Should resolve interface methods in VM classes - .shouldMatch("cds,resolve.*archived interface method .* ResolvedConstantsApp java/lang/Runnable.run:") + .shouldMatch(ALWAYS("interface method .* ResolvedConstantsApp java/lang/Runnable.run:")) // Should resolve references to own non-static method (private or public) - .shouldMatch("archived method.*: ResolvedConstantsBar ResolvedConstantsBar.doBar:") - .shouldMatch("archived method.*: ResolvedConstantsApp ResolvedConstantsApp.privateInstanceCall:") - .shouldMatch("archived method.*: ResolvedConstantsApp ResolvedConstantsApp.publicInstanceCall:") + .shouldMatch(ALWAYS("method.*: ResolvedConstantsBar ResolvedConstantsBar.doBar:")) + .shouldMatch(ALWAYS("method.*: ResolvedConstantsApp ResolvedConstantsApp.privateInstanceCall:")) + .shouldMatch(ALWAYS("method.*: ResolvedConstantsApp ResolvedConstantsApp.publicInstanceCall:")) // Should not resolve references to static method - .shouldNotMatch(" archived method CP entry.*: ResolvedConstantsApp ResolvedConstantsApp.staticCall:") + .shouldNotMatch(ALWAYS("method.*: ResolvedConstantsApp ResolvedConstantsApp.staticCall:")) // Should resolve references to method in super type - .shouldMatch(" archived method CP entry.*: ResolvedConstantsBar ResolvedConstantsFoo.doBar:") + .shouldMatch(ALWAYS("method.*: ResolvedConstantsBar ResolvedConstantsFoo.doBar:")) - // App class cannot resolve references to methods in boot classes: + // Without -XX:+AOTClassLinking App class cannot resolve references to methods in boot classes: // When the app class loader tries to resolve a class X that's normally loaded by // the boot loader, it's possible for the app class loader to get a different copy of // X (by using MethodHandles.Lookup.defineClass(), etc). Therefore, let's be on // the side of safety and revert all such references. - // - // This will be addressed in JDK-8315737. - .shouldMatch("reverted method.*: ResolvedConstantsApp java/io/PrintStream.println:") - .shouldMatch("reverted method.*: ResolvedConstantsBar java/lang/Class.getName:") + .shouldMatch(AOTLINK_ONLY("method.*: ResolvedConstantsApp java/io/PrintStream.println:")) + .shouldMatch(AOTLINK_ONLY("method.*: ResolvedConstantsBar java/lang/Class.getName:")) - // Should not resolve methods in unrelated classes. - .shouldMatch("reverted method.*: ResolvedConstantsApp ResolvedConstantsBar.doit:") + // Resole resolve methods in unrelated classes ONLY when using -XX:+AOTClassLinking + .shouldMatch(AOTLINK_ONLY("method.*: ResolvedConstantsApp ResolvedConstantsBar.doit:")) // End --- ; + + + // Indy References --- + if (aotClassLinking) { + out.shouldContain("Cannot aot-resolve Lambda proxy because OldConsumer is excluded") + .shouldContain("Cannot aot-resolve Lambda proxy because OldProvider is excluded") + .shouldContain("Cannot aot-resolve Lambda proxy because OldClass is excluded") + .shouldContain("Cannot aot-resolve Lambda proxy of interface type InterfaceWithClinit") + .shouldMatch("klasses.* app *NormalClass[$][$]Lambda/.* hidden aot-linked inited") + .shouldNotMatch("klasses.* app *SubOfOldClass[$][$]Lambda/") + .shouldMatch("archived indy *CP entry.*StringConcatTest .* => java/lang/invoke/StringConcatFactory.makeConcatWithConstants") + .shouldNotMatch("archived indy *CP entry.*StringConcatTestOld .* => java/lang/invoke/StringConcatFactory.makeConcatWithConstants"); + } + } + + static String ALWAYS(String s) { + return "cds,resolve.*archived " + s; + } + + static String AOTLINK_ONLY(String s) { + if (aotClassLinking) { + return ALWAYS(s); + } else { + return "cds,resolve.*reverted " + s; + } } } @@ -142,12 +187,98 @@ public static void main(String args[]) { bar.a ++; bar.b ++; bar.doit(); + + testLambda(); + StringConcatTest.test(); + StringConcatTestOld.main(null); } private static void staticCall() {} private void privateInstanceCall() {} public void publicInstanceCall() {} public void run() {} + + static void testLambda() { + // The functional type used in the Lambda is an excluded class + OldProvider op = () -> { + return null; + }; + + // A captured value is an instance of an excluded Class + OldClass c = new OldClass(); + Runnable r = () -> { + System.out.println("Test 1 " + c); + }; + r.run(); + + // The functional interface accepts an argument that's an excluded class + MyInterface i = (o) -> { + System.out.println("Test 2 " + o); + }; + i.dispatch(c); + + // Method reference to old class + OldConsumer oldConsumer = new OldConsumer(); + Consumer wrapper = oldConsumer::consumeString; + wrapper.accept("Hello"); + + // Lambda of interfaces that have are not archived. + InterfaceWithClinit i2 = () -> { + System.out.println("Test 3"); + }; + i2.dispatch(); + + // These two classes have almost identical source code, but + // only NormalClass should have its lambdas pre-resolved. + // SubOfOldClass is "old" -- it should be excluded from the AOT cache, + // so none of its lambda proxies should be cached + NormalClass.testLambda(); // Lambda proxy should be cached + SubOfOldClass.testLambda(); // Lambda proxy shouldn't be cached + } +} + +class StringConcatTest { + static void test() { + System.out.println("StringConcatTest " + new StringConcatTest()); // concat should be aot-resolved + } +} + +/* see StringConcatTestOld.jasm + +class StringConcatTestOld { + public static void main(String args[]) { + // concat should be aot-resolved => the MethodType refers to an old class + System.out.println("StringConcatTestOld " + new OldConsumer()); + } +} +*/ + +class NormalClass { + static void testLambda() { + Runnable r = () -> { + System.out.println("NormalClass testLambda"); + }; + r.run(); + } +} + +class SubOfOldClass extends OldClass { + static void testLambda() { + Runnable r = () -> { + System.out.println("SubOfOldClass testLambda"); + }; + r.run(); + } +} + +interface MyInterface { + void dispatch(OldClass c); +} + +interface InterfaceWithClinit { + static final long X = System.currentTimeMillis(); + void dispatch(); + default long dummy() { return X; } } class ResolvedConstantsFoo { diff --git a/test/hotspot/jtreg/runtime/cds/appcds/resolvedConstants/StringConcatTestOld.jasm b/test/hotspot/jtreg/runtime/cds/appcds/resolvedConstants/StringConcatTestOld.jasm new file mode 100644 index 00000000000..76460cad0a3 --- /dev/null +++ b/test/hotspot/jtreg/runtime/cds/appcds/resolvedConstants/StringConcatTestOld.jasm @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * 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. + * + */ + +/* + +decompiled from + +class OldConsumer {} + +class StringConcatTestOld { + public static void main(String args[]) { + System.out.println("StringConcatTestOld " + new OldConsumer()); + } +} + + +(1) Comment out this line + + invokestatic Method java/lang/String.valueOf:"(Ljava/lang/Object;)Ljava/lang/String;"; + +(2) Change the MethodType parameter of makeConcatWithConstants from + + "(Ljava/lang/String;)Ljava/lang/String;" + -> + + "(LOldConsumer;)Ljava/lang/String;" + +*/ + +super class StringConcatTestOld + version 67:0 +{ + Method "":"()V" + stack 1 locals 1 + { + aload_0; + invokespecial Method java/lang/Object."":"()V"; + return; + } + public static Method main:"([Ljava/lang/String;)V" + stack 3 locals 1 + { + getstatic Field java/lang/System.out:"Ljava/io/PrintStream;"; + new class OldConsumer; + dup; + invokespecial Method OldConsumer."":"()V"; + //invokestatic Method java/lang/String.valueOf:"(Ljava/lang/Object;)Ljava/lang/String;"; + invokedynamic InvokeDynamic REF_invokeStatic:Method java/lang/invoke/StringConcatFactory.makeConcatWithConstants:"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;":makeConcatWithConstants:"(LOldConsumer;)Ljava/lang/String;" { + String "StringConcatTestOld " + }; + invokevirtual Method java/io/PrintStream.println:"(Ljava/lang/String;)V"; + return; + } + + public static final InnerClass Lookup=class java/lang/invoke/MethodHandles$Lookup of class java/lang/invoke/MethodHandles; + +} // end Class StringConcatTestOld diff --git a/test/hotspot/jtreg/runtime/cds/appcds/test-classes/OldConsumer.jasm b/test/hotspot/jtreg/runtime/cds/appcds/test-classes/OldConsumer.jasm new file mode 100644 index 00000000000..bffb5a27381 --- /dev/null +++ b/test/hotspot/jtreg/runtime/cds/appcds/test-classes/OldConsumer.jasm @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * 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. + * + */ +super class OldConsumer + version 49:0 +{ + + +Method "":"()V" + stack 1 locals 1 +{ + aload_0; + invokespecial Method java/lang/Object."":"()V"; + return; +} + +public Method consumeString:"(Ljava/lang/String;)V" + stack 3 locals 2 +{ + getstatic Field java/lang/System.out:"Ljava/io/PrintStream;"; + new class java/lang/StringBuilder; + dup; + invokespecial Method java/lang/StringBuilder."":"()V"; + ldc String "Hello: "; + invokevirtual Method java/lang/StringBuilder.append:"(Ljava/lang/String;)Ljava/lang/StringBuilder;"; + aload_1; + invokevirtual Method java/lang/StringBuilder.append:"(Ljava/lang/String;)Ljava/lang/StringBuilder;"; + invokevirtual Method java/lang/StringBuilder.toString:"()Ljava/lang/String;"; + invokevirtual Method java/io/PrintStream.println:"(Ljava/lang/String;)V"; + return; +} + +} // end Class OldConsumer diff --git a/test/jdk/ProblemList-AotJdk.txt b/test/jdk/ProblemList-AotJdk.txt new file mode 100644 index 00000000000..9030ba60c78 --- /dev/null +++ b/test/jdk/ProblemList-AotJdk.txt @@ -0,0 +1,11 @@ +java/math/BigInteger/largeMemory/DivisionOverflow.java 0000000 generic-all +java/math/BigInteger/largeMemory/StringConstructorOverflow.java 0000000 generic-all + +jdk/internal/misc/CDS/ArchivedEnumTest.java 0000000 generic-all + +java/lang/module/ModuleDescriptorHashCodeTest.java 0000000 generic-all + + +# The test case is incorrect. There's no guarantee that running a JVM with the following +# parameters will always cause the class java/lang/invoke/MethodHandleStatics to be initialized +java/lang/invoke/DumpMethodHandleInternals.java 0000000 generic-all diff --git a/test/jdk/java/lang/ProcessBuilder/Basic.java b/test/jdk/java/lang/ProcessBuilder/Basic.java index 6faec0ec6bb..d0d83704318 100644 --- a/test/jdk/java/lang/ProcessBuilder/Basic.java +++ b/test/jdk/java/lang/ProcessBuilder/Basic.java @@ -38,7 +38,6 @@ * @summary Basic tests for Process and Environment Variable code * @modules java.base/java.lang:open * java.base/java.io:open - * java.base/jdk.internal.misc * @requires !vm.musl * @requires vm.flagless * @library /test/lib @@ -2693,17 +2692,6 @@ static void THROWS(Class k, Fun... fs) { else unexpected(t);}} static boolean isLocked(BufferedInputStream bis) throws Exception { - Field lockField = BufferedInputStream.class.getDeclaredField("lock"); - lockField.setAccessible(true); - var lock = (jdk.internal.misc.InternalLock) lockField.get(bis); - if (lock != null) { - if (lock.tryLock()) { - lock.unlock(); - return false; - } else { - return true; - } - } return new Thread() { volatile boolean unlocked; diff --git a/test/jdk/java/net/httpclient/DebugLoggerTest.java b/test/jdk/java/net/httpclient/DebugLoggerTest.java index ec36d62e38e..8d81e5cbe69 100644 --- a/test/jdk/java/net/httpclient/DebugLoggerTest.java +++ b/test/jdk/java/net/httpclient/DebugLoggerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -213,7 +213,7 @@ public void publish(LogRecord record) { public void flush() { } @Override - public void close() throws SecurityException { + public void close() { } } diff --git a/test/jdk/java/net/httpclient/FilePublisher/FilePublisherPermsTest.java b/test/jdk/java/net/httpclient/FilePublisher/FilePublisherPermsTest.java index 29976edec9a..bafe1496a86 100644 --- a/test/jdk/java/net/httpclient/FilePublisher/FilePublisherPermsTest.java +++ b/test/jdk/java/net/httpclient/FilePublisher/FilePublisherPermsTest.java @@ -40,7 +40,6 @@ import javax.net.ssl.SSLContext; import java.io.FileNotFoundException; -import java.io.FilePermission; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -211,9 +210,6 @@ public void handle(HttpServerAdapters.HttpTestExchange t) throws IOException { @BeforeTest public void setup() throws Exception { - policyFile = System.getProperty("java.security.policy"); - out.println(policyFile); - sslContext = new SimpleSSLContext().get(); if (sslContext == null) throw new AssertionError("Unexpected null sslContext"); diff --git a/test/jdk/java/net/httpclient/FilePublisher/SecureZipFSProvider.java b/test/jdk/java/net/httpclient/FilePublisher/SecureZipFSProvider.java index 333996496cd..00f532ba47c 100644 --- a/test/jdk/java/net/httpclient/FilePublisher/SecureZipFSProvider.java +++ b/test/jdk/java/net/httpclient/FilePublisher/SecureZipFSProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. * 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,13 +92,6 @@ public Path getPath(URI uri) { public InputStream newInputStream(Path path, OpenOption... options) throws IOException { Path p = toTestPath(path).unwrap(); - - // Added permission checks before opening the file - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(new RuntimePermission("customPermission")); - sm.checkRead(p.toString()); - } return defaultProvider.newInputStream(p, options); } diff --git a/test/jdk/java/net/httpclient/PlainProxyConnectionTest.java b/test/jdk/java/net/httpclient/PlainProxyConnectionTest.java index a3157b0ac37..f8671103ec4 100644 --- a/test/jdk/java/net/httpclient/PlainProxyConnectionTest.java +++ b/test/jdk/java/net/httpclient/PlainProxyConnectionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,8 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; +import jdk.httpclient.test.lib.common.HttpServerAdapters; + import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; @@ -54,15 +56,28 @@ * @bug 8230526 * @summary Verifies that PlainProxyConnections are cached and reused properly. We do this by * verifying that the remote address of the HTTP exchange (on the fake proxy server) - * is always the same InetSocketAddress. - * @modules jdk.httpserver - * @run main/othervm -Djdk.tracePinnedThreads=full PlainProxyConnectionTest - * @author danielfuchs + * is always the same InetSocketAddress. Logging verbosity is increased to aid in + * diagnosis of intermittent failures. + * @library /test/lib + * /test/jdk/java/net/httpclient/lib + * @run main/othervm -Djdk.tracePinnedThreads=full + * -Djdk.httpclient.HttpClient.log=headers,requests,trace + * -Djdk.internal.httpclient.debug=true + * PlainProxyConnectionTest */ public class PlainProxyConnectionTest { + // Increase logging verbosity to troubleshoot intermittent failures + static { + HttpServerAdapters.enableServerLogging(); + } + static final String RESPONSE = "

Hello World!"; - static final String PATH = "/foo/"; + + // Adding some salt to the path to avoid other parallel running tests mistakenly connect to our test server + private static final String PATH = String.format( + "/%s-%d", PlainProxyConnectionTest.class.getSimpleName(), PlainProxyConnectionTest.class.hashCode()); + static final ConcurrentLinkedQueue connections = new ConcurrentLinkedQueue<>(); private static final AtomicInteger IDS = new AtomicInteger(); diff --git a/test/jdk/java/net/httpclient/ProxyServer.java b/test/jdk/java/net/httpclient/ProxyServer.java index 7de14a79225..747a20772d1 100644 --- a/test/jdk/java/net/httpclient/ProxyServer.java +++ b/test/jdk/java/net/httpclient/ProxyServer.java @@ -27,10 +27,8 @@ import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.*; -import java.security.*; import java.util.concurrent.CopyOnWriteArrayList; -import static java.nio.charset.StandardCharsets.US_ASCII; import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.ISO_8859_1; import static java.util.Arrays.asList; @@ -49,9 +47,9 @@ public class ProxyServer extends Thread implements Closeable { // build it. Let's keep it simple. static final boolean IS_WINDOWS; static { - PrivilegedAction action = - () -> System.getProperty("os.name", "unknown"); - String osName = AccessController.doPrivileged(action); + // Parses os.name directly in order to avoid depending on test + // libraries in an auxiliary test class + String osName = System.getProperty("os.name", "unknown"); IS_WINDOWS = osName.toLowerCase(Locale.ROOT).startsWith("win"); } @@ -151,20 +149,6 @@ public void close() throws IOException { volatile boolean done; public void run() { - if (System.getSecurityManager() == null) { - execute(); - } else { - // so calling domain does not need to have socket permission - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - execute(); - return null; - } - }); - } - } - - public void execute() { int id = 0; try { while (!done) { diff --git a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/TestServerConfigurator.java b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/TestServerConfigurator.java index 5d16ac24155..a471f3ce07f 100644 --- a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/TestServerConfigurator.java +++ b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/TestServerConfigurator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved. * 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,8 +23,6 @@ package jdk.httpclient.test.lib.common; import java.net.InetAddress; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.List; import javax.net.ssl.SNIMatcher; @@ -59,14 +57,8 @@ public TestServerConfigurator(final InetAddress serverAddr, final SSLContext con @Override public void configure(final HttpsParameters params) { final SSLParameters sslParams = getSSLContext().getDefaultSSLParameters(); - @SuppressWarnings("removal") final SecurityManager sm = System.getSecurityManager(); - final String hostname; - if (sm == null) { - hostname = serverAddr.getHostName(); - } else { - final PrivilegedAction action = () -> serverAddr.getHostName(); - hostname = AccessController.doPrivileged(action); - } + final String hostname = serverAddr.getHostName(); + final List sniMatchers = List.of(new ServerNameMatcher(hostname)); sslParams.setSNIMatchers(sniMatchers); // configure the server with these custom SSLParameters diff --git a/test/jdk/java/net/httpclient/security/filePerms/FileProcessorPermissionTest.java b/test/jdk/java/net/httpclient/security/filePerms/FileProcessorPermissionTest.java index 3c857ba1b48..c8920771727 100644 --- a/test/jdk/java/net/httpclient/security/filePerms/FileProcessorPermissionTest.java +++ b/test/jdk/java/net/httpclient/security/filePerms/FileProcessorPermissionTest.java @@ -29,7 +29,6 @@ import java.nio.file.Path; import java.nio.file.Paths; -import java.security.PrivilegedExceptionAction; import java.util.List; import java.net.http.HttpRequest; import java.net.http.HttpResponse.BodyHandlers; @@ -43,11 +42,14 @@ public class FileProcessorPermissionTest { static final Path fromFilePath = Paths.get(testSrc, "FileProcessorPermissionTest.java"); static final Path asFilePath = Paths.get(testSrc, "asFile.txt"); static final Path CWD = Paths.get("."); - static final Class SE = SecurityException.class; + + interface ExceptionAction { + T run() throws Exception; + } @Test public void test() throws Exception { - List> list = List.of( + List> list = List.of( () -> HttpRequest.BodyPublishers.ofFile(fromFilePath), () -> BodyHandlers.ofFile(asFilePath), @@ -59,7 +61,7 @@ public void test() throws Exception { () -> BodyHandlers.ofFileDownload(CWD, CREATE, WRITE) ); - for (PrivilegedExceptionAction pa : list) { + for (ExceptionAction pa : list) { pa.run(); } diff --git a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/AuthenticationFilterTest.java b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/AuthenticationFilterTest.java index 7a960892aec..415caeb1196 100644 --- a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/AuthenticationFilterTest.java +++ b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/AuthenticationFilterTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,7 +38,6 @@ import java.net.http.HttpHeaders; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; -import java.security.AccessController; import java.util.Arrays; import java.util.Base64; import java.util.Collections; @@ -196,8 +195,7 @@ private void doTestAuthentication(String uri, Version v, String proxy) throws Ex HttpRequestImpl origReq = new HttpRequestImpl(reqBuilder); HttpRequestImpl req = new HttpRequestImpl(origReq, ps); MultiExchange multi = new MultiExchange(origReq, req, client, - BodyHandlers.replacing(null), - null, AccessController.getContext()); + BodyHandlers.replacing(null), null); Exchange exchange = new Exchange<>(req, multi); out.println("\nSimulating unauthenticated request to " + uri); filter.request(req, multi); @@ -266,8 +264,7 @@ private void doTestAuthentication(String uri, Version v, String proxy) throws Ex HttpRequestImpl origReq2 = new HttpRequestImpl(reqBuilder2); HttpRequestImpl req2 = new HttpRequestImpl(origReq2, ps); MultiExchange multi2 = new MultiExchange(origReq2, req2, client, - HttpResponse.BodyHandlers.replacing(null), - null, AccessController.getContext()); + HttpResponse.BodyHandlers.replacing(null), null); filter.request(req2, multi2); out.println("Check that filter has added credentials from cache for " + reqURI2 + " with proxy " + req2.proxy()); @@ -298,8 +295,7 @@ && isNullOrEmpty(reqURI.getFragment()) HttpRequestImpl origReq3 = new HttpRequestImpl(reqBuilder3); HttpRequestImpl req3 = new HttpRequestImpl(origReq3, ps); MultiExchange multi3 = new MultiExchange(origReq3, req3, client, - HttpResponse.BodyHandlers.replacing(null), - null, AccessController.getContext()); + HttpResponse.BodyHandlers.replacing(null), null); filter.request(req3, multi3); HttpHeaders h3 = req3.getSystemHeadersBuilder().build(); if (proxy == null) { @@ -342,8 +338,7 @@ && isNullOrEmpty(reqURI.getFragment()) HttpRequestImpl origReq4 = new HttpRequestImpl(reqBuilder4); HttpRequestImpl req4 = new HttpRequestImpl(origReq4, fakeProxy); MultiExchange multi4 = new MultiExchange(origReq4, req4, client, - HttpResponse.BodyHandlers.replacing(null), null, - AccessController.getContext()); + HttpResponse.BodyHandlers.replacing(null), null); out.println("Simulating new request to " + reqURI4 + " with a proxy " + req4.proxy()); assertTrue((req4.proxy() == null) == (proxy != null), "(req4.proxy() == null) == (proxy != null) should be true"); @@ -383,8 +378,7 @@ && isNullOrEmpty(reqURI.getFragment()) HttpRequestImpl origReq5 = new HttpRequestImpl(reqBuilder5); HttpRequestImpl req5 = new HttpRequestImpl(origReq5, NO_PROXY); MultiExchange multi5 = new MultiExchange(origReq5, req5, client, - HttpResponse.BodyHandlers.replacing(null), null, - AccessController.getContext()); + HttpResponse.BodyHandlers.replacing(null), null); out.println("Simulating new request to " + reqURI + " with a proxy " + req5.proxy()); assertTrue(req5.proxy() == null, "req5.proxy() should be null"); Exchange exchange5 = new Exchange<>(req5, multi5); @@ -437,8 +431,7 @@ && isNullOrEmpty(reqURI.getFragment()) HttpRequestImpl origReq6 = new HttpRequestImpl(reqBuilder6); HttpRequestImpl req6 = new HttpRequestImpl(origReq6, ps); MultiExchange multi6 = new MultiExchange(origReq6, req6, client, - HttpResponse.BodyHandlers.replacing(null), null, - AccessController.getContext()); + HttpResponse.BodyHandlers.replacing(null), null); out.println("Simulating new request to " + reqURI + " with a proxy " + req6.proxy()); assertTrue(req6.proxy() != null, "req6.proxy() should not be null"); Exchange exchange6 = new Exchange<>(req6, multi6); @@ -461,8 +454,7 @@ && isNullOrEmpty(reqURI.getFragment()) HttpRequestImpl origReq7 = new HttpRequestImpl(reqBuilder7); HttpRequestImpl req7 = new HttpRequestImpl(origReq7, ps); MultiExchange multi7 = new MultiExchange(origReq7, req7, client, - HttpResponse.BodyHandlers.replacing(null), null, - AccessController.getContext()); + HttpResponse.BodyHandlers.replacing(null), null); out.println("Simulating new request to " + reqURI7 + " with a proxy " + req7.proxy()); assertTrue(req7.proxy() == null, "req7.proxy() should be null"); Exchange exchange7 = new Exchange<>(req7, multi7); diff --git a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/RawChannelTest.java b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/RawChannelTest.java index 6619eff008a..9b5764735b2 100644 --- a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/RawChannelTest.java +++ b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/RawChannelTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -221,7 +221,6 @@ private static RawChannel channelOf(int port) throws Exception { requestImpl, clientImpl, discarding(), - null, null); HttpResponse r = mex.responseAsync(clientImpl.theExecutor()) .get(30, SECONDS); diff --git a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SimpleSSLContext.java b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SimpleSSLContext.java index 5277eed3ac0..e6897a83de4 100644 --- a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SimpleSSLContext.java +++ b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SimpleSSLContext.java @@ -42,13 +42,6 @@ /** * Creates a simple usable SSLContext for SSLSocketFactory * or a HttpsServer using a default keystore in the test tree. - *

- * Using this class with a security manager requires the following - * permissions to be granted: - *

- * permission "java.util.PropertyPermission" "test.src.path", "read"; - * permission java.io.FilePermission "/path/to/test/lib/jdk/test/lib/testkeys", "read"; - * The exact path above depends on the location of the test. */ public class SimpleSSLContext { @@ -60,27 +53,17 @@ public class SimpleSSLContext { public SimpleSSLContext() throws IOException { String paths = System.getProperty("test.src.path"); StringTokenizer st = new StringTokenizer(paths, File.pathSeparator); - boolean securityExceptions = false; SSLContext sslContext = null; while (st.hasMoreTokens()) { String path = st.nextToken(); - try { - File f = new File(path, "../../../../../lib/jdk/test/lib/net/testkeys"); - if (f.exists()) { - try (FileInputStream fis = new FileInputStream(f)) { - sslContext = init(fis); - break; - } + File f = new File(path, "../../../../../lib/jdk/test/lib/net/testkeys"); + if (f.exists()) { + try (FileInputStream fis = new FileInputStream(f)) { + sslContext = init(fis); + break; } - } catch (SecurityException e) { - // catch and ignore because permission only required - // for one entry on path (at most) - securityExceptions = true; } } - if (securityExceptions) { - System.out.println("SecurityExceptions thrown on loading testkeys"); - } ssl = sslContext; } diff --git a/test/jdk/jdk/classfile/BoundAttributeTest.java b/test/jdk/jdk/classfile/BoundAttributeTest.java index 6a164bec2f9..e8f12356128 100644 --- a/test/jdk/jdk/classfile/BoundAttributeTest.java +++ b/test/jdk/jdk/classfile/BoundAttributeTest.java @@ -41,6 +41,7 @@ import java.lang.classfile.attribute.MethodParameterInfo; import java.lang.classfile.attribute.MethodParametersAttribute; import java.lang.classfile.constantpool.ConstantPoolException; +import java.lang.classfile.constantpool.Utf8Entry; import java.lang.constant.ClassDesc; import java.lang.constant.ConstantDescs; import java.lang.constant.MethodTypeDesc; @@ -89,6 +90,11 @@ public void writeBody(BufWriterImpl b) { b.writeIndex(oneClass); b.writeIndex(oneClassString); } + + @Override + public Utf8Entry attributeName() { + return cp.utf8Entry(Attributes.NAME_NEST_MEMBERS); + } }); }); diff --git a/test/jdk/jdk/classfile/CorpusTest.java b/test/jdk/jdk/classfile/CorpusTest.java index 631e2f8afaa..513005370e7 100644 --- a/test/jdk/jdk/classfile/CorpusTest.java +++ b/test/jdk/jdk/classfile/CorpusTest.java @@ -93,6 +93,11 @@ public void writeBody(BufWriterImpl b) { b.writeU2(curPc); b.writeU2(ln.line()); } + + @Override + public Utf8Entry attributeName() { + return cob.constantPool().utf8Entry(Attributes.NAME_LINE_NUMBER_TABLE); + } }); case LocalVariable lv -> dcob.writeAttribute(new UnboundAttribute.AdHocAttribute<>(Attributes.localVariableTable()) { @Override @@ -100,6 +105,11 @@ public void writeBody(BufWriterImpl b) { b.writeU2(1); Util.writeLocalVariable(b, lv); } + + @Override + public Utf8Entry attributeName() { + return cob.constantPool().utf8Entry(Attributes.NAME_LOCAL_VARIABLE_TABLE); + } }); case LocalVariableType lvt -> dcob.writeAttribute(new UnboundAttribute.AdHocAttribute<>(Attributes.localVariableTypeTable()) { @Override @@ -107,6 +117,11 @@ public void writeBody(BufWriterImpl b) { b.writeU2(1); Util.writeLocalVariable(b, lvt); } + + @Override + public Utf8Entry attributeName() { + return cob.constantPool().utf8Entry(Attributes.NAME_LOCAL_VARIABLE_TYPE_TABLE); + } }); default -> cob.with(coe); } diff --git a/test/jdk/jdk/classfile/LimitsTest.java b/test/jdk/jdk/classfile/LimitsTest.java index a1899ac1c84..6f3dc04c665 100644 --- a/test/jdk/jdk/classfile/LimitsTest.java +++ b/test/jdk/jdk/classfile/LimitsTest.java @@ -41,6 +41,7 @@ import java.lang.classfile.constantpool.ConstantPoolBuilder; import java.lang.classfile.constantpool.ConstantPoolException; import java.lang.classfile.constantpool.IntegerEntry; +import java.lang.classfile.constantpool.Utf8Entry; import java.util.List; import jdk.internal.classfile.impl.BufWriterImpl; @@ -49,6 +50,7 @@ import jdk.internal.classfile.impl.LabelContext; import jdk.internal.classfile.impl.UnboundAttribute; import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.*; class LimitsTest { @@ -145,7 +147,13 @@ public void writeBody(BufWriterImpl b) { b.writeInt(-2); //npairs to jump back and cause OOME if not checked b.writeU2(0);//exception handlers b.writeU2(0);//attributes - }})))).methods().get(0).code().get().elementList()); + } + + @Override + public Utf8Entry attributeName() { + return mb.constantPool().utf8Entry(Attributes.NAME_CODE); + } + })))).methods().get(0).code().get().elementList()); } @Test @@ -167,7 +175,13 @@ public void writeBody(BufWriterImpl b) { b.writeInt(-5); //high to jump back and cause OOME if not checked b.writeU2(0);//exception handlers b.writeU2(0);//attributes - }})))).methods().get(0).code().get().elementList()); + } + + @Override + public Utf8Entry attributeName() { + return mb.constantPool().utf8Entry(Attributes.NAME_CODE); + } + })))).methods().get(0).code().get().elementList()); assertThrows(IllegalArgumentException.class, () -> ClassFile.of().parse(ClassFile.of().build(ClassDesc.of("TableSwitchClass"), cb -> cb.withMethod( "tableSwitchMethod", MethodTypeDesc.of(ConstantDescs.CD_void), 0, mb -> @@ -189,7 +203,13 @@ public void writeBody(BufWriterImpl b) { b.writeInt(Integer.MAX_VALUE - 4); //high to jump back and cause infinite loop b.writeU2(0);//exception handlers b.writeU2(0);//attributes - }})))).methods().get(0).code().get().elementList()); + } + + @Override + public Utf8Entry attributeName() { + return mb.constantPool().utf8Entry(Attributes.NAME_CODE); + } + })))).methods().get(0).code().get().elementList()); } @Test diff --git a/test/jdk/jdk/classfile/LowJCovAttributeTest.java b/test/jdk/jdk/classfile/LowJCovAttributeTest.java index 858b9c90416..ed29a057357 100644 --- a/test/jdk/jdk/classfile/LowJCovAttributeTest.java +++ b/test/jdk/jdk/classfile/LowJCovAttributeTest.java @@ -76,7 +76,7 @@ void testRead() { private void testRead0() { int[] mask = new int[1]; for (Attribute attr : classLow.attributes()) { - switch (attr.attributeName()) { + switch (attr.attributeName().stringValue()) { case Attributes.NAME_COMPILATION_ID: { CompilationIDAttribute cid = (CompilationIDAttribute) attr; Utf8Entry v = cid.compilationId(); diff --git a/test/jdk/jdk/classfile/LowModuleTest.java b/test/jdk/jdk/classfile/LowModuleTest.java index e78eff74d1d..b017fe84756 100644 --- a/test/jdk/jdk/classfile/LowModuleTest.java +++ b/test/jdk/jdk/classfile/LowModuleTest.java @@ -77,7 +77,7 @@ void testRead(Path path, TestInfo test) throws Exception { private void testRead0(ClassModel classLow) { for (Attribute attr : classLow.attributes()) { - switch (attr.attributeName()) { + switch (attr.attributeName().stringValue()) { case Attributes.NAME_SOURCE_FILE: { SourceFileAttribute sfa = (SourceFileAttribute) attr; Utf8Entry sf = sfa.sourceFile(); diff --git a/test/jdk/jdk/classfile/VerifierSelfTest.java b/test/jdk/jdk/classfile/VerifierSelfTest.java index b6a2f08c9ec..1f9f199a33b 100644 --- a/test/jdk/jdk/classfile/VerifierSelfTest.java +++ b/test/jdk/jdk/classfile/VerifierSelfTest.java @@ -31,7 +31,9 @@ import java.io.IOException; import java.lang.classfile.constantpool.PoolEntry; import java.lang.constant.ClassDesc; + import static java.lang.constant.ConstantDescs.*; + import java.lang.invoke.MethodHandleInfo; import java.net.URI; import java.nio.file.FileSystem; @@ -47,12 +49,14 @@ import java.lang.classfile.*; import java.lang.classfile.attribute.*; import java.lang.classfile.components.ClassPrinter; +import java.lang.classfile.constantpool.Utf8Entry; import java.lang.constant.ModuleDesc; import jdk.internal.classfile.impl.BufWriterImpl; import jdk.internal.classfile.impl.DirectClassBuilder; import jdk.internal.classfile.impl.UnboundAttribute; import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.*; class VerifierSelfTest { @@ -109,6 +113,11 @@ void testInvalidAttrLocation() { public void writeBody(BufWriterImpl b) { b.writeU2(0); } + + @Override + public Utf8Entry attributeName() { + return cb.constantPool().utf8Entry(Attributes.NAME_LOCAL_VARIABLE_TABLE); + } })); assertTrue(cc.verify(bytes).stream().anyMatch(e -> e.getMessage().contains("Invalid LocalVariableTable attribute location"))); } @@ -366,7 +375,7 @@ private static class CloneAttribute extends CustomAttribute { super(new AttributeMapper(){ @Override public String name() { - return a.attributeName(); + return a.attributeName().stringValue(); } @Override diff --git a/test/jdk/jdk/classfile/helpers/ClassRecord.java b/test/jdk/jdk/classfile/helpers/ClassRecord.java index e7a239015f6..c663721ec9f 100644 --- a/test/jdk/jdk/classfile/helpers/ClassRecord.java +++ b/test/jdk/jdk/classfile/helpers/ClassRecord.java @@ -234,7 +234,7 @@ public record AttributesRecord( public static AttributesRecord ofStreamingElements(Supplier> elements, ConstantPool cp, CompatibilityFilter... cf) { Map> attrs = elements.get().filter(e -> e instanceof Attribute) .map(e -> (Attribute) e) - .collect(toMap(Attribute::attributeName, e -> e)); + .collect(toMap(a -> a.attributeName().stringValue(), e -> e)); return new AttributesRecord( mapAttr(attrs, annotationDefault(), a -> ElementValueRecord.ofElementValue(a.defaultValue())), cp == null ? null : IntStream.range(0, cp.bootstrapMethodCount()).mapToObj(i -> BootstrapMethodRecord.ofBootstrapMethodEntry(cp.bootstrapMethodEntry(i))).collect(toSetOrNull()), diff --git a/test/jdk/jdk/classfile/helpers/RebuildingTransformation.java b/test/jdk/jdk/classfile/helpers/RebuildingTransformation.java index a5de6cb2fa1..6ddc42528e8 100644 --- a/test/jdk/jdk/classfile/helpers/RebuildingTransformation.java +++ b/test/jdk/jdk/classfile/helpers/RebuildingTransformation.java @@ -59,8 +59,8 @@ static byte[] transform(ClassModel clm) { case RuntimeVisibleTypeAnnotationsAttribute a -> fb.with(RuntimeVisibleTypeAnnotationsAttribute.of(transformTypeAnnotations(a.annotations(), null, null))); case SignatureAttribute a -> fb.with(SignatureAttribute.of(Signature.parseFrom(a.asTypeSignature().signatureString()))); case SyntheticAttribute a -> fb.with(SyntheticAttribute.of()); - case CustomAttribute a -> throw new AssertionError("Unexpected custom attribute: " + a.attributeName()); - case UnknownAttribute a -> throw new AssertionError("Unexpected unknown attribute: " + a.attributeName()); + case CustomAttribute a -> throw new AssertionError("Unexpected custom attribute: " + a.attributeName().stringValue()); + case UnknownAttribute a -> throw new AssertionError("Unexpected unknown attribute: " + a.attributeName().stringValue()); } } }); @@ -91,8 +91,8 @@ static byte[] transform(ClassModel clm) { case RuntimeVisibleTypeAnnotationsAttribute a -> mb.with(RuntimeVisibleTypeAnnotationsAttribute.of(transformTypeAnnotations(a.annotations(), null, null))); case SignatureAttribute a -> mb.with(SignatureAttribute.of(MethodSignature.parseFrom(a.asMethodSignature().signatureString()))); case SyntheticAttribute a -> mb.with(SyntheticAttribute.of()); - case CustomAttribute a -> throw new AssertionError("Unexpected custom attribute: " + a.attributeName()); - case UnknownAttribute a -> throw new AssertionError("Unexpected unknown attribute: " + a.attributeName()); + case CustomAttribute a -> throw new AssertionError("Unexpected custom attribute: " + a.attributeName().stringValue()); + case UnknownAttribute a -> throw new AssertionError("Unexpected unknown attribute: " + a.attributeName().stringValue()); } } }); @@ -132,7 +132,7 @@ static byte[] transform(ClassModel clm) { case RuntimeVisibleAnnotationsAttribute rvaa -> rcac.accept(RuntimeVisibleAnnotationsAttribute.of(transformAnnotations(rvaa.annotations()))); case RuntimeVisibleTypeAnnotationsAttribute rvtaa -> rcac.accept(RuntimeVisibleTypeAnnotationsAttribute.of(transformTypeAnnotations(rvtaa.annotations(), null, null))); case SignatureAttribute sa -> rcac.accept(SignatureAttribute.of(Signature.parseFrom(sa.asTypeSignature().signatureString()))); - default -> throw new AssertionError("Unexpected record component attribute: " + rca.attributeName()); + default -> throw new AssertionError("Unexpected record component attribute: " + rca.attributeName().stringValue()); }}).toArray(Attribute[]::new))).toArray(RecordComponentInfo[]::new))); case RuntimeInvisibleAnnotationsAttribute a -> clb.with(RuntimeInvisibleAnnotationsAttribute.of(transformAnnotations(a.annotations()))); case RuntimeInvisibleTypeAnnotationsAttribute a -> clb.with(RuntimeInvisibleTypeAnnotationsAttribute.of(transformTypeAnnotations(a.annotations(), null, null))); @@ -143,8 +143,8 @@ static byte[] transform(ClassModel clm) { case SourceFileAttribute a -> clb.with(SourceFileAttribute.of(a.sourceFile().stringValue())); case SourceIDAttribute a -> clb.with(SourceIDAttribute.of(a.sourceId().stringValue())); case SyntheticAttribute a -> clb.with(SyntheticAttribute.of()); - case CustomAttribute a -> throw new AssertionError("Unexpected custom attribute: " + a.attributeName()); - case UnknownAttribute a -> throw new AssertionError("Unexpected unknown attribute: " + a.attributeName()); + case CustomAttribute a -> throw new AssertionError("Unexpected custom attribute: " + a.attributeName().stringValue()); + case UnknownAttribute a -> throw new AssertionError("Unexpected unknown attribute: " + a.attributeName().stringValue()); } } }); @@ -596,7 +596,7 @@ else switch (i.constantValue()) { transformFrameTypeInfos(fr.locals(), cob, labels), transformFrameTypeInfos(fr.stack(), cob, labels))).toList())); case CustomAttribute a -> - throw new AssertionError("Unexpected custom attribute: " + a.attributeName()); + throw new AssertionError("Unexpected custom attribute: " + a.attributeName().stringValue()); } } } diff --git a/test/jdk/jdk/internal/misc/CDS/ArchivedEnumTest.java b/test/jdk/jdk/internal/misc/CDS/ArchivedEnumTest.java index ec1bd213834..3a2d0f9539f 100644 --- a/test/jdk/jdk/internal/misc/CDS/ArchivedEnumTest.java +++ b/test/jdk/jdk/internal/misc/CDS/ArchivedEnumTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,6 +35,7 @@ * @run driver ArchivedEnumTest */ +import jdk.test.lib.cds.CDSTestUtils; import jdk.test.lib.helpers.ClassFileInstaller; import jdk.test.lib.process.OutputAnalyzer; @@ -46,7 +47,7 @@ public static void main(String[] args) throws Exception { TestCommon.list("ArchivedEnumApp")); // Note: You can get the following line to fail by commenting out // the ADD_EXCL(...) lines in cdsHeapVerifier.cpp - out.shouldNotContain("object points to a static field that may be reinitialized at runtime"); + out.shouldNotContain(CDSTestUtils.MSG_STATIC_FIELD_MAY_HOLD_DIFFERENT_VALUE); TestCommon.run("-cp", appJar, "-Xlog:cds=debug", diff --git a/test/jdk/jdk/nio/zipfs/TestPosix.java b/test/jdk/jdk/nio/zipfs/TestPosix.java index f63f091c32e..420c1618e12 100644 --- a/test/jdk/jdk/nio/zipfs/TestPosix.java +++ b/test/jdk/jdk/nio/zipfs/TestPosix.java @@ -29,10 +29,6 @@ import java.nio.ByteOrder; import java.nio.file.*; import java.nio.file.attribute.*; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.time.Instant; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; @@ -219,35 +215,28 @@ static interface Executor { private static String expectedDefaultOwner(Path zf) { try { - try { - PrivilegedExceptionAction pa = ()->Files.getOwner(zf).getName(); - return AccessController.doPrivileged(pa); - } catch (UnsupportedOperationException e) { - // if we can't get the owner of the file, we fall back to system property user.name - PrivilegedAction pa = ()->System.getProperty("user.name"); - return AccessController.doPrivileged(pa); - } - } catch (PrivilegedActionException | SecurityException e) { + return Files.getOwner(zf).getName(); + } catch (UnsupportedOperationException e) { + // if we can't get the owner of the file, we fall back to system property user.name + return System.getProperty("user.name"); + } catch (IOException e) { System.out.println("Caught " + e.getClass().getName() + "(" + e.getMessage() + - ") when running a privileged operation to get the default owner."); + ") when getting the default owner."); return null; } } private static String expectedDefaultGroup(Path zf, String defaultOwner) { try { - try { - PosixFileAttributeView zfpv = Files.getFileAttributeView(zf, PosixFileAttributeView.class); - if (zfpv == null) { - return defaultOwner; - } - PrivilegedExceptionAction pa = ()->zfpv.readAttributes().group().getName(); - return AccessController.doPrivileged(pa); - } catch (UnsupportedOperationException e) { + PosixFileAttributeView zfpv = Files.getFileAttributeView(zf, PosixFileAttributeView.class); + if (zfpv == null) { return defaultOwner; } - } catch (PrivilegedActionException | SecurityException e) { - System.out.println("Caught an exception when running a privileged operation to get the default group."); + return zfpv.readAttributes().group().getName(); + } catch (UnsupportedOperationException e) { + return defaultOwner; + } catch (IOException e) { + System.out.println("Caught an exception when getting the default group."); e.printStackTrace(); return null; } diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java index 338ff7a767b..1976a5cf72c 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java @@ -64,22 +64,6 @@ private static Path getInstallationSubDirectory(JPackageCommand cmd) { return Path.of(cmd.getArgumentValue("--install-dir", cmd::name)); } - // Tests have problems on windows where path in the temp dir are too long - // for the wix tools. We can't use a tempDir outside the TKit's WorkDir, so - // we minimize both the tempRoot directory name (above) and the tempDir name - // (below) to the extension part (which is necessary to differenciate between - // the multiple PackageTypes that will be run for one JPackageCommand). - // It might be beter if the whole work dir name was shortened from: - // jtreg_open_test_jdk_tools_jpackage_share_jdk_jpackage_tests_BasicTest_java. - public static Path getTempDirectory(JPackageCommand cmd, Path tempRoot) { - String ext = cmd.outputBundle().getFileName().toString(); - int i = ext.lastIndexOf("."); - if (i > 0 && i < (ext.length() - 1)) { - ext = ext.substring(i+1); - } - return tempRoot.resolve(ext); - } - private static void runMsiexecWithRetries(Executor misexec) { Executor.Result result = null; for (int attempt = 0; attempt < 8; ++attempt) { diff --git a/test/jdk/tools/jpackage/linux/jdk/jpackage/tests/UsrTreeTest.java b/test/jdk/tools/jpackage/linux/UsrTreeTest.java similarity index 100% rename from test/jdk/tools/jpackage/linux/jdk/jpackage/tests/UsrTreeTest.java rename to test/jdk/tools/jpackage/linux/UsrTreeTest.java diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/AppVersionTest.java b/test/jdk/tools/jpackage/share/AppVersionTest.java similarity index 98% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/AppVersionTest.java rename to test/jdk/tools/jpackage/share/AppVersionTest.java index d4f28ec17be..efd025590d2 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/AppVersionTest.java +++ b/test/jdk/tools/jpackage/share/AppVersionTest.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import java.io.IOException; import java.util.Collection; @@ -46,7 +45,7 @@ * @build jdk.jpackage.test.* * @compile AppVersionTest.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.AppVersionTest + * --jpt-run=AppVersionTest */ public final class AppVersionTest { diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/BasicTest.java b/test/jdk/tools/jpackage/share/BasicTest.java similarity index 95% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/BasicTest.java rename to test/jdk/tools/jpackage/share/BasicTest.java index 1222fa95949..61668b9e878 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/BasicTest.java +++ b/test/jdk/tools/jpackage/share/BasicTest.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import java.io.IOException; import java.nio.file.Files; @@ -45,8 +44,6 @@ import jdk.jpackage.test.Functional.ThrowingConsumer; import static jdk.jpackage.test.RunnablePackageTest.Action.CREATE_AND_UNPACK; -import static jdk.jpackage.test.WindowsHelper.getTempDirectory; - /* * @test * @summary jpackage basic testing @@ -54,7 +51,7 @@ * @build jdk.jpackage.test.* * @compile BasicTest.java * @run main/othervm/timeout=720 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.BasicTest + * --jpt-run=BasicTest */ public final class BasicTest { @@ -345,7 +342,7 @@ public void testTemp(TestTempType type) throws IOException { // Force save of package bundle in test work directory. .addInitializer(JPackageCommand::setDefaultInputOutput) .addInitializer(cmd -> { - Path tempDir = getTempDirectory(cmd, tempRoot); + Path tempDir = tempRoot.resolve(cmd.packageType().name()); switch (type) { case TEMPDIR_EMPTY -> Files.createDirectories(tempDir); case TEMPDIR_NOT_EXIST -> Files.createDirectories(tempDir.getParent()); @@ -362,20 +359,16 @@ public void testTemp(TestTempType type) throws IOException { if (TestTempType.TEMPDIR_NOT_EMPTY.equals(type)) { pkgTest.setExpectedExitCode(1).addBundleVerifier(cmd -> { // Check jpackage didn't use the supplied directory. - Path tempDir = getTempDirectory(cmd, tempRoot); - String[] tempDirContents = tempDir.toFile().list(); - TKit.assertStringListEquals(List.of("foo.txt"), List.of( - tempDirContents), String.format( - "Check the contents of the supplied temporary directory [%s]", - tempDir)); + Path tempDir = Path.of(cmd.getArgumentValue("--temp")); + TKit.assertDirectoryContent(tempDir).match(Path.of("foo.txt")); TKit.assertStringListEquals(List.of("Hello Duke!"), - Files.readAllLines(tempDir.resolve(tempDirContents[0])), + Files.readAllLines(tempDir.resolve("foo.txt")), "Check the contents of the file in the supplied temporary directory"); }); } else { pkgTest.addBundleVerifier(cmd -> { // Check jpackage used the supplied directory. - Path tempDir = getTempDirectory(cmd, tempRoot); + Path tempDir = Path.of(cmd.getArgumentValue("--temp")); TKit.assertDirectoryNotEmpty(tempDir); }); } diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/CookedRuntimeTest.java b/test/jdk/tools/jpackage/share/CookedRuntimeTest.java similarity index 98% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/CookedRuntimeTest.java rename to test/jdk/tools/jpackage/share/CookedRuntimeTest.java index cfb6ec13ccf..e8bd034bfb4 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/CookedRuntimeTest.java +++ b/test/jdk/tools/jpackage/share/CookedRuntimeTest.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import java.io.IOException; import java.nio.file.Files; @@ -46,7 +45,7 @@ * @build jdk.jpackage.test.* * @compile CookedRuntimeTest.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.CookedRuntimeTest + * --jpt-run=CookedRuntimeTest */ public final class CookedRuntimeTest { diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/DotInNameTest.java b/test/jdk/tools/jpackage/share/DotInNameTest.java similarity index 96% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/DotInNameTest.java rename to test/jdk/tools/jpackage/share/DotInNameTest.java index 73be2c2e47a..2617db26183 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/DotInNameTest.java +++ b/test/jdk/tools/jpackage/share/DotInNameTest.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import jdk.jpackage.test.JPackageCommand; import jdk.jpackage.test.HelloApp; @@ -37,7 +36,7 @@ * @build jdk.jpackage.test.* * @compile DotInNameTest.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.DotInNameTest + * --jpt-run=DotInNameTest * --jpt-before-run=jdk.jpackage.test.JPackageCommand.useToolProviderByDefault */ diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/ErrorTest.java b/test/jdk/tools/jpackage/share/ErrorTest.java similarity index 97% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/ErrorTest.java rename to test/jdk/tools/jpackage/share/ErrorTest.java index 57603809607..f012eac1ced 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/ErrorTest.java +++ b/test/jdk/tools/jpackage/share/ErrorTest.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import java.util.Collection; import java.util.List; @@ -37,7 +36,7 @@ * @build jdk.jpackage.test.* * @compile ErrorTest.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.ErrorTest + * --jpt-run=ErrorTest * --jpt-before-run=jdk.jpackage.test.JPackageCommand.useExecutableByDefault */ @@ -48,7 +47,7 @@ * @build jdk.jpackage.test.* * @compile ErrorTest.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.ErrorTest + * --jpt-run=ErrorTest * --jpt-before-run=jdk.jpackage.test.JPackageCommand.useToolProviderByDefault */ diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/JLinkOptionsTest.java b/test/jdk/tools/jpackage/share/JLinkOptionsTest.java similarity index 98% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/JLinkOptionsTest.java rename to test/jdk/tools/jpackage/share/JLinkOptionsTest.java index dce60890aba..d4f7bca2ae4 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/JLinkOptionsTest.java +++ b/test/jdk/tools/jpackage/share/JLinkOptionsTest.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import java.util.Collection; import java.util.List; @@ -37,7 +36,7 @@ * @build jdk.jpackage.test.* * @compile JLinkOptionsTest.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.JLinkOptionsTest + * --jpt-run=JLinkOptionsTest */ public final class JLinkOptionsTest { diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/JavaOptionsEqualsTest.java b/test/jdk/tools/jpackage/share/JavaOptionsEqualsTest.java similarity index 96% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/JavaOptionsEqualsTest.java rename to test/jdk/tools/jpackage/share/JavaOptionsEqualsTest.java index e1c809dadd3..b1f69c6395f 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/JavaOptionsEqualsTest.java +++ b/test/jdk/tools/jpackage/share/JavaOptionsEqualsTest.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import java.util.Collection; import java.util.List; @@ -39,7 +38,7 @@ * @build jdk.jpackage.test.* * @compile JavaOptionsEqualsTest.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.JavaOptionsEqualsTest + * --jpt-run=JavaOptionsEqualsTest * --jpt-before-run=jdk.jpackage.test.JPackageCommand.useExecutableByDefault */ @@ -50,7 +49,7 @@ * @build jdk.jpackage.test.* * @compile JavaOptionsEqualsTest.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.JavaOptionsEqualsTest + * --jpt-run=JavaOptionsEqualsTest * --jpt-before-run=jdk.jpackage.test.JPackageCommand.useToolProviderByDefault */ diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/JavaOptionsTest.java b/test/jdk/tools/jpackage/share/JavaOptionsTest.java similarity index 98% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/JavaOptionsTest.java rename to test/jdk/tools/jpackage/share/JavaOptionsTest.java index cee455271aa..befc90accea 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/JavaOptionsTest.java +++ b/test/jdk/tools/jpackage/share/JavaOptionsTest.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import java.util.Collection; import java.util.List; @@ -39,7 +38,7 @@ * @build jdk.jpackage.test.* * @compile JavaOptionsTest.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.JavaOptionsTest + * --jpt-run=JavaOptionsTest * --jpt-before-run=jdk.jpackage.test.JPackageCommand.useToolProviderByDefault */ diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/MainClassTest.java b/test/jdk/tools/jpackage/share/MainClassTest.java similarity index 96% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/MainClassTest.java rename to test/jdk/tools/jpackage/share/MainClassTest.java index 641d0fd00bb..d9188e8f18f 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/MainClassTest.java +++ b/test/jdk/tools/jpackage/share/MainClassTest.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import java.io.IOException; import java.nio.file.Files; @@ -46,7 +45,7 @@ import jdk.jpackage.test.Annotations.Test; import jdk.jpackage.test.CfgFile; import jdk.jpackage.test.Functional.ThrowingConsumer; -import static jdk.jpackage.tests.MainClassTest.Script.MainClassType.*; + /* @@ -56,7 +55,7 @@ * @build jdk.jpackage.test.* * @compile MainClassTest.java * @run main/othervm/timeout=720 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.MainClassTest + * --jpt-run=MainClassTest */ public final class MainClassTest { @@ -82,7 +81,7 @@ Script withMainClass(MainClassType v) { } Script withJarMainClass(MainClassType v) { - appDesc.setWithMainClass(v != NotSet); + appDesc.setWithMainClass(v != MainClassType.NotSet); jarMainClass = v; return this; } @@ -172,7 +171,8 @@ public MainClassTest(Script script) { @Parameters public static Collection scripts() { - final var withMainClass = Set.of(SetWrong, SetRight); + final var withMainClass = Set.of(Script.MainClassType.SetWrong, + Script.MainClassType.SetRight); List scripts = new ArrayList<>(); for (var withJLink : List.of(true, false)) { @@ -205,7 +205,7 @@ public static Collection scripts() { @Test public void test() throws IOException { - if (script.jarMainClass == SetWrong) { + if (script.jarMainClass == Script.MainClassType.SetWrong) { initJarWithWrongMainClass(); } @@ -224,11 +224,11 @@ public void test() throws IOException { boolean appShouldSucceed = false; // Should succeed if valid main class is set on the command line. - appShouldSucceed |= (script.mainClass == SetRight); + appShouldSucceed |= (script.mainClass == Script.MainClassType.SetRight); // Should succeed if main class is not set on the command line but set // to valid value in the jar. - appShouldSucceed |= (script.mainClass == NotSet && script.jarMainClass == SetRight); + appShouldSucceed |= (script.mainClass == Script.MainClassType.NotSet && script.jarMainClass == Script.MainClassType.SetRight); if (appShouldSucceed) { cmd.executeAndAssertHelloAppImageCreated(); diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/ModulePathTest.java b/test/jdk/tools/jpackage/share/ModulePathTest.java similarity index 98% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/ModulePathTest.java rename to test/jdk/tools/jpackage/share/ModulePathTest.java index c42a24ec310..7d1e86f8ae2 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/ModulePathTest.java +++ b/test/jdk/tools/jpackage/share/ModulePathTest.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import java.io.File; import java.io.IOException; @@ -48,7 +47,7 @@ * @build jdk.jpackage.test.* * @compile ModulePathTest.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.ModulePathTest + * --jpt-run=ModulePathTest */ public final class ModulePathTest { diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/ModulePathTest2.java b/test/jdk/tools/jpackage/share/ModulePathTest2.java similarity index 97% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/ModulePathTest2.java rename to test/jdk/tools/jpackage/share/ModulePathTest2.java index 7b1ec2f5b63..34144907bdb 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/ModulePathTest2.java +++ b/test/jdk/tools/jpackage/share/ModulePathTest2.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import java.io.IOException; import java.nio.file.Path; @@ -40,7 +39,7 @@ * @build jdk.jpackage.test.* * @compile ModulePathTest2.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.ModulePathTest2 + * --jpt-run=ModulePathTest2 */ public final class ModulePathTest2 { diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/ModulePathTest3.java b/test/jdk/tools/jpackage/share/ModulePathTest3.java similarity index 98% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/ModulePathTest3.java rename to test/jdk/tools/jpackage/share/ModulePathTest3.java index d6fca043920..b4b51e1adfc 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/ModulePathTest3.java +++ b/test/jdk/tools/jpackage/share/ModulePathTest3.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import java.io.IOException; import java.nio.file.Files; @@ -53,7 +52,7 @@ * @build jdk.jpackage.test.* * @compile ModulePathTest3.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.ModulePathTest3 + * --jpt-run=ModulePathTest3 */ public final class ModulePathTest3 { diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/MultipleJarAppTest.java b/test/jdk/tools/jpackage/share/MultipleJarAppTest.java similarity index 96% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/MultipleJarAppTest.java rename to test/jdk/tools/jpackage/share/MultipleJarAppTest.java index 38878929006..0726b131d69 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/MultipleJarAppTest.java +++ b/test/jdk/tools/jpackage/share/MultipleJarAppTest.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import java.nio.file.Path; import jdk.jpackage.test.Annotations.Test; @@ -37,7 +36,7 @@ * @build jdk.jpackage.test.* * @compile MultipleJarAppTest.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.MultipleJarAppTest + * --jpt-run=MultipleJarAppTest */ public final class MultipleJarAppTest { diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/NoMPathRuntimeTest.java b/test/jdk/tools/jpackage/share/NoMPathRuntimeTest.java similarity index 98% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/NoMPathRuntimeTest.java rename to test/jdk/tools/jpackage/share/NoMPathRuntimeTest.java index 4a9aef7860d..37319971183 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/NoMPathRuntimeTest.java +++ b/test/jdk/tools/jpackage/share/NoMPathRuntimeTest.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import java.io.IOException; import java.nio.file.Files; @@ -47,7 +46,7 @@ * @build jdk.jpackage.test.* * @compile NoMPathRuntimeTest.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.NoMPathRuntimeTest + * --jpt-run=NoMPathRuntimeTest */ public final class NoMPathRuntimeTest { diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/NonExistentTest.java b/test/jdk/tools/jpackage/share/NonExistentTest.java similarity index 97% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/NonExistentTest.java rename to test/jdk/tools/jpackage/share/NonExistentTest.java index 8ca18af356c..4d50f2a5850 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/NonExistentTest.java +++ b/test/jdk/tools/jpackage/share/NonExistentTest.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import java.util.Collection; import java.util.List; @@ -37,7 +36,7 @@ * @build jdk.jpackage.test.* * @compile NonExistentTest.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.NonExistentTest + * --jpt-run=NonExistentTest */ public final class NonExistentTest { diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/PredefinedAppImageErrorTest.java b/test/jdk/tools/jpackage/share/PredefinedAppImageErrorTest.java similarity index 96% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/PredefinedAppImageErrorTest.java rename to test/jdk/tools/jpackage/share/PredefinedAppImageErrorTest.java index b01a78120db..bdb4f6bfbd7 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/PredefinedAppImageErrorTest.java +++ b/test/jdk/tools/jpackage/share/PredefinedAppImageErrorTest.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import java.io.IOException; import java.nio.file.Path; @@ -42,11 +41,11 @@ * @compile PredefinedAppImageErrorTest.java * * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.PredefinedAppImageErrorTest + * --jpt-run=PredefinedAppImageErrorTest * --jpt-before-run=jdk.jpackage.test.JPackageCommand.useExecutableByDefault * * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.PredefinedAppImageErrorTest + * --jpt-run=PredefinedAppImageErrorTest * --jpt-before-run=jdk.jpackage.test.JPackageCommand.useToolProviderByDefault */ diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/UnicodeArgsTest.java b/test/jdk/tools/jpackage/share/UnicodeArgsTest.java similarity index 97% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/UnicodeArgsTest.java rename to test/jdk/tools/jpackage/share/UnicodeArgsTest.java index 29722086eec..6fa2717d15e 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/UnicodeArgsTest.java +++ b/test/jdk/tools/jpackage/share/UnicodeArgsTest.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import java.util.stream.Collectors; import jdk.jpackage.test.TKit; @@ -38,7 +37,7 @@ * @compile UnicodeArgsTest.java * @requires (os.family == "windows") * @run main/othervm/timeout=720 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.UnicodeArgsTest + * --jpt-run=UnicodeArgsTest */ public final class UnicodeArgsTest { diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/VendorTest.java b/test/jdk/tools/jpackage/share/VendorTest.java similarity index 96% rename from test/jdk/tools/jpackage/share/jdk/jpackage/tests/VendorTest.java rename to test/jdk/tools/jpackage/share/VendorTest.java index b6e8f44dbf8..4c3a0ffcee2 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/VendorTest.java +++ b/test/jdk/tools/jpackage/share/VendorTest.java @@ -21,7 +21,6 @@ * questions. */ -package jdk.jpackage.tests; import jdk.jpackage.test.PackageTest; import jdk.jpackage.test.PackageType; @@ -61,7 +60,7 @@ * @build jdk.jpackage.test.* * @compile VendorTest.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.VendorTest + * --jpt-run=VendorTest */ /* @@ -74,7 +73,7 @@ * @build jdk.jpackage.test.* * @compile VendorTest.java * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=jdk.jpackage.tests.VendorTest + * --jpt-run=VendorTest */ public class VendorTest { diff --git a/test/jdk/tools/jpackage/windows/WinL10nTest.java b/test/jdk/tools/jpackage/windows/WinL10nTest.java index d951b6f8832..814b6401f47 100644 --- a/test/jdk/tools/jpackage/windows/WinL10nTest.java +++ b/test/jdk/tools/jpackage/windows/WinL10nTest.java @@ -22,7 +22,6 @@ */ import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import jdk.jpackage.test.TKit; import jdk.jpackage.test.PackageTest; @@ -37,8 +36,6 @@ import java.util.stream.Stream; import jdk.jpackage.test.Executor; -import static jdk.jpackage.test.WindowsHelper.getTempDirectory; - /* * @test * @summary Custom l10n of msi installers in jpackage @@ -182,9 +179,8 @@ public void test() throws IOException { } // Preserve config dir to check the set of copied l10n files. - Path tempDir = getTempDirectory(cmd, tempRoot); - Files.createDirectories(tempDir.getParent()); - cmd.addArguments("--temp", tempDir.toString()); + Path tempDir = tempRoot.resolve(cmd.packageType().name()); + cmd.addArguments("--temp", tempDir); }) .addBundleVerifier((cmd, result) -> { if (expectedCultures != null) { @@ -213,7 +209,7 @@ public void test() throws IOException { v.createCmdOutputVerifier(wixSrcDir).apply(getBuildCommandLine(result)); } } - Path tempDir = getTempDirectory(cmd, tempRoot).toAbsolutePath(); + var tempDir = Path.of(cmd.getArgumentValue("--temp")).toAbsolutePath(); for (var v : createDefaultL10nFilesLocVerifiers(tempDir)) { v.apply(getBuildCommandLine(result)); } diff --git a/test/jtreg-ext/requires/VMProps.java b/test/jtreg-ext/requires/VMProps.java index 58aebfd4be4..0c2da686903 100644 --- a/test/jtreg-ext/requires/VMProps.java +++ b/test/jtreg-ext/requires/VMProps.java @@ -122,6 +122,7 @@ public Map call() { // vm.cds is true if the VM is compiled with cds support. map.put("vm.cds", this::vmCDS); map.put("vm.cds.custom.loaders", this::vmCDSForCustomLoaders); + map.put("vm.cds.supports.aot.class.linking", this::vmCDSSupportsAOTClassLinking); map.put("vm.cds.write.archived.java.heap", this::vmCDSCanWriteArchivedJavaHeap); map.put("vm.continuations", this::vmContinuations); // vm.graal.enabled is true if Graal is used as JIT @@ -458,6 +459,14 @@ protected String vmCDSCanWriteArchivedJavaHeap() { && isCDSRuntimeOptionsCompatible()); } + /** + * @return true if this VM can support the -XX:AOTClassLinking option + */ + protected String vmCDSSupportsAOTClassLinking() { + // Currently, the VM supports AOTClassLinking as long as it's able to write archived java heap. + return vmCDSCanWriteArchivedJavaHeap(); + } + /** * @return true if the VM options specified via the "test.cds.runtime.options" * property is compatible with writing Java heap objects into the CDS archive diff --git a/test/langtools/tools/javac/LocalFreeVarStaticInstantiate.java b/test/langtools/tools/javac/LocalFreeVarStaticInstantiate.java new file mode 100644 index 00000000000..39b419c694a --- /dev/null +++ b/test/langtools/tools/javac/LocalFreeVarStaticInstantiate.java @@ -0,0 +1,44 @@ +/* + * @test /nodynamiccopyright/ + * @bug 8322882 + * @summary Disallow attempts to access a free variable proxy field from a static method + * @compile/fail/ref=LocalFreeVarStaticInstantiate.out -XDrawDiagnostics LocalFreeVarStaticInstantiate.java + */ + +class LocalFreeVarStaticInstantiate { + + // local class in method + static void foo(Object there) { + class Local { + { + there.hashCode(); + } + + static { + new Local(); // can't get there from here + } + + static Runnable r = () -> { + new Local(); // can't get there from here + }; + } + } + + // local class in lambda + static Runnable foo = () -> { + Object there = ""; + class Local { + { + there.hashCode(); + } + + static { + new Local(); // can't get there from here + } + + static Runnable r = () -> { + new Local(); // can't get there from here + }; + } + }; +} diff --git a/test/langtools/tools/javac/LocalFreeVarStaticInstantiate.out b/test/langtools/tools/javac/LocalFreeVarStaticInstantiate.out new file mode 100644 index 00000000000..50e913083b0 --- /dev/null +++ b/test/langtools/tools/javac/LocalFreeVarStaticInstantiate.out @@ -0,0 +1,5 @@ +LocalFreeVarStaticInstantiate.java:18:17: compiler.err.local.cant.be.inst.static: kindname.class, Local +LocalFreeVarStaticInstantiate.java:22:17: compiler.err.local.cant.be.inst.static: kindname.class, Local +LocalFreeVarStaticInstantiate.java:36:17: compiler.err.local.cant.be.inst.static: kindname.class, Local +LocalFreeVarStaticInstantiate.java:40:17: compiler.err.local.cant.be.inst.static: kindname.class, Local +4 errors diff --git a/test/langtools/tools/javac/QualifiedAccess/QualifiedAccess_2.java b/test/langtools/tools/javac/QualifiedAccess/QualifiedAccess_2.java index de36f070766..d16c8194a53 100644 --- a/test/langtools/tools/javac/QualifiedAccess/QualifiedAccess_2.java +++ b/test/langtools/tools/javac/QualifiedAccess/QualifiedAccess_2.java @@ -7,7 +7,7 @@ * * @compile pack1/P1.java * @compile pack1/P2.java - * @compile/fail/ref=QualifiedAccess_2.out -XDrawDiagnostics QualifiedAccess_2.java + * @compile/fail/ref=QualifiedAccess_2.out -XDdev -XDrawDiagnostics QualifiedAccess_2.java */ import pack1.P1; diff --git a/test/langtools/tools/javac/SuperInit/EarlyIndirectOuterCapture.java b/test/langtools/tools/javac/SuperInit/EarlyIndirectOuterCapture.java new file mode 100644 index 00000000000..9336c4dc183 --- /dev/null +++ b/test/langtools/tools/javac/SuperInit/EarlyIndirectOuterCapture.java @@ -0,0 +1,29 @@ +/* + * @test /nodynamiccopyright/ + * @bug 8334248 + * @summary Invalid error for early construction local class constructor method reference + * @compile/fail/ref=EarlyIndirectOuterCapture.out -XDrawDiagnostics EarlyIndirectOuterCapture.java + */ + +public class EarlyIndirectOuterCapture { + + EarlyIndirectOuterCapture() { + this(null); + } + + EarlyIndirectOuterCapture(InnerSuperclass inner) { } + + class InnerSuperclass { } + + static class InnerOuter extends EarlyIndirectOuterCapture { // accessible + class InnerInnerOuter extends EarlyIndirectOuterCapture { // not accessible + InnerInnerOuter() { + super(/* which enclosing instance here ? */new InnerSuperclass() { }); + } + + InnerInnerOuter(boolean b) { + super(InnerOuter.this.new InnerSuperclass() { }); // ok, explicit + } + } + } +} diff --git a/test/langtools/tools/javac/SuperInit/EarlyIndirectOuterCapture.out b/test/langtools/tools/javac/SuperInit/EarlyIndirectOuterCapture.out new file mode 100644 index 00000000000..7b96671a2bd --- /dev/null +++ b/test/langtools/tools/javac/SuperInit/EarlyIndirectOuterCapture.out @@ -0,0 +1,2 @@ +EarlyIndirectOuterCapture.java:21:60: compiler.err.cant.ref.before.ctor.called: this +1 error diff --git a/test/langtools/tools/javac/SuperInit/EarlyLocalCtorRef.java b/test/langtools/tools/javac/SuperInit/EarlyLocalCtorRef.java new file mode 100644 index 00000000000..3346d6ff4f7 --- /dev/null +++ b/test/langtools/tools/javac/SuperInit/EarlyLocalCtorRef.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * 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 8334248 + * @summary Allow early construction local class constructor method references + * @enablePreview + */ + +import java.util.function.Supplier; + +public class EarlyLocalCtorRef { + + public EarlyLocalCtorRef() { + class InnerLocal { } + this(InnerLocal::new); + } + + public EarlyLocalCtorRef(Supplier s) { + } + + public static void main(String[] args) { + new EarlyLocalCtorRef(); + } +} diff --git a/src/java.base/share/classes/jdk/internal/access/JavaIOPrintWriterAccess.java b/test/langtools/tools/javac/SuperInit/EarlyLocalTest2.java similarity index 62% rename from src/java.base/share/classes/jdk/internal/access/JavaIOPrintWriterAccess.java rename to test/langtools/tools/javac/SuperInit/EarlyLocalTest2.java index 8be54a76b0a..ba90f06dc5e 100644 --- a/src/java.base/share/classes/jdk/internal/access/JavaIOPrintWriterAccess.java +++ b/test/langtools/tools/javac/SuperInit/EarlyLocalTest2.java @@ -1,12 +1,10 @@ /* - * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. * 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. + * 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 @@ -22,10 +20,24 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -package jdk.internal.access; +/* + * @test + * @bug 8333313 + * @summary Verify references to local classes declared in early construction contexts + * @enablePreview + */ +public class EarlyLocalTest2 { -import java.io.PrintWriter; + class Test { + Test() { + class InnerLocal { } + Runnable r = () -> new InnerLocal() { }; + r.run(); + super(); + } + } -public interface JavaIOPrintWriterAccess { - Object lock(PrintWriter pw); + public static void main(String[] args) { + new EarlyLocalTest2().new Test(); + } } diff --git a/src/java.base/share/classes/jdk/internal/access/JavaIOPrintStreamAccess.java b/test/langtools/tools/javac/SuperInit/EarlyLocalTest3.java similarity index 63% rename from src/java.base/share/classes/jdk/internal/access/JavaIOPrintStreamAccess.java rename to test/langtools/tools/javac/SuperInit/EarlyLocalTest3.java index ec205e27dca..bf8d6faa099 100644 --- a/src/java.base/share/classes/jdk/internal/access/JavaIOPrintStreamAccess.java +++ b/test/langtools/tools/javac/SuperInit/EarlyLocalTest3.java @@ -1,12 +1,10 @@ /* - * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. * 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. + * 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 @@ -22,10 +20,24 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -package jdk.internal.access; +/* + * @test + * @bug 8333313 + * @summary Verify references to local classes declared in early construction contexts + * @enablePreview + */ +public class EarlyLocalTest3 { -import java.io.PrintStream; + class Test { + Test() { + class InnerLocal { } + Runnable r = InnerLocal::new; + r.run(); + super(); + } + } -public interface JavaIOPrintStreamAccess { - Object lock(PrintStream ps); + public static void main(String[] args) { + new EarlyLocalTest3().new Test(); + } } diff --git a/test/langtools/tools/javac/SuperInit/EarlyLocalTest8.java b/test/langtools/tools/javac/SuperInit/EarlyLocalTest8.java new file mode 100644 index 00000000000..806903e9017 --- /dev/null +++ b/test/langtools/tools/javac/SuperInit/EarlyLocalTest8.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * 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 8333313 + * @summary Verify references to local classes declared in early construction contexts + * @enablePreview + */ +import java.util.concurrent.atomic.AtomicReference; + +public class EarlyLocalTest8 { + + class Test extends AtomicReference { + Test(int x) { + super( + switch (x) { + case 0 -> null; + default -> { + class InnerLocal { } + yield () -> new InnerLocal() { { System.out.println(EarlyLocalTest8.this); } }; + } + }); + } + } + + public static void main(String[] args) { + new EarlyLocalTest8().new Test(42); + } +} diff --git a/test/langtools/tools/javac/classfiles/attributes/AnnotationDefault/AnnotationDefaultTest.java b/test/langtools/tools/javac/classfiles/attributes/AnnotationDefault/AnnotationDefaultTest.java index d9a3320ecc2..2911e58820f 100644 --- a/test/langtools/tools/javac/classfiles/attributes/AnnotationDefault/AnnotationDefaultTest.java +++ b/test/langtools/tools/javac/classfiles/attributes/AnnotationDefault/AnnotationDefaultTest.java @@ -88,7 +88,7 @@ private void test(String template, Map replacements, boolean has checkEquals(countNumberOfAttributes(method.attributes()), 1L, "Number of AnnotationDefault attribute"); - checkEquals(attr.attributeName(), + checkEquals(attr.attributeName().stringValue(), "AnnotationDefault", "attribute_name_index"); ExpectedValues expectedValue = expectedValues.get(methodName); diff --git a/test/langtools/tools/javac/classfiles/attributes/EnclosingMethod/EnclosingMethodTest.java b/test/langtools/tools/javac/classfiles/attributes/EnclosingMethod/EnclosingMethodTest.java index f15771840f5..924916f5cbd 100644 --- a/test/langtools/tools/javac/classfiles/attributes/EnclosingMethod/EnclosingMethodTest.java +++ b/test/langtools/tools/javac/classfiles/attributes/EnclosingMethod/EnclosingMethodTest.java @@ -169,7 +169,7 @@ private void testEnclosingMethodAttribute() { // stop checking, attr is null. test case failed return; } - checkEquals(attr.attributeName(), + checkEquals(attr.attributeName().stringValue(), "EnclosingMethod", "attribute_name_index of EnclosingMethod attribute in the class : " + className); checkEquals(((BoundAttribute)attr).payloadLen(), 4, diff --git a/test/langtools/tools/javac/classfiles/attributes/LineNumberTable/LineNumberTestBase.java b/test/langtools/tools/javac/classfiles/attributes/LineNumberTable/LineNumberTestBase.java index be4a5aaea91..531d5e617d0 100644 --- a/test/langtools/tools/javac/classfiles/attributes/LineNumberTable/LineNumberTestBase.java +++ b/test/langtools/tools/javac/classfiles/attributes/LineNumberTable/LineNumberTestBase.java @@ -138,7 +138,7 @@ private void verifyCoveredLines(Set actualCoveredLines, TestCase.Method private > int countAttributes(AttributeMapper attr, AttributedElement attributedElement) { int i = 0; for (Attribute attribute : attributedElement.attributes()) { - if (attribute.attributeName().equals(attr.name())) { + if (attribute.attributeName().equalsString(attr.name())) { i++; } } diff --git a/test/langtools/tools/javac/classfiles/attributes/Signature/Driver.java b/test/langtools/tools/javac/classfiles/attributes/Signature/Driver.java index 72f7d2a6b9b..7b75ffa5f9c 100644 --- a/test/langtools/tools/javac/classfiles/attributes/Signature/Driver.java +++ b/test/langtools/tools/javac/classfiles/attributes/Signature/Driver.java @@ -219,7 +219,7 @@ private void testAttribute( SignatureAttribute attribute = sup.get(); if (expectedSignature != null && checkNotNull(attribute, memberName + " must have attribute")) { - checkEquals(attribute.attributeName(), + checkEquals(attribute.attributeName().stringValue(), "Signature", "Attribute's name : " + memberName); checkEquals(((BoundAttribute)attribute).payloadLen(), 2, "Attribute's length : " + memberName); checkEquals(attribute.signature().stringValue(), diff --git a/test/langtools/tools/javac/classfiles/attributes/SourceFile/SourceFileTestBase.java b/test/langtools/tools/javac/classfiles/attributes/SourceFile/SourceFileTestBase.java index 52d53f9dce4..0d81fc2c282 100644 --- a/test/langtools/tools/javac/classfiles/attributes/SourceFile/SourceFileTestBase.java +++ b/test/langtools/tools/javac/classfiles/attributes/SourceFile/SourceFileTestBase.java @@ -108,7 +108,7 @@ private void assertAttributePresent(ClassModel classFile, String fileName) throw SourceFileAttribute attribute = sourceFileAttributes.get(0); - assertEquals(attribute.attributeName(), Attributes.sourceFile().name(), "Incorrect attribute name"); + assertEquals(attribute.attributeName().stringValue(), Attributes.sourceFile().name(), "Incorrect attribute name"); assertEquals(attribute.sourceFile().stringValue(), fileName, "Incorrect source file name"); assertEquals(((BoundAttribute)attribute).payloadLen(), 2, "Incorrect attribute length"); diff --git a/test/langtools/tools/javac/classfiles/attributes/deprecated/DeprecatedTest.java b/test/langtools/tools/javac/classfiles/attributes/deprecated/DeprecatedTest.java index 425760ea137..6467f3d8027 100644 --- a/test/langtools/tools/javac/classfiles/attributes/deprecated/DeprecatedTest.java +++ b/test/langtools/tools/javac/classfiles/attributes/deprecated/DeprecatedTest.java @@ -302,7 +302,7 @@ private void testDeprecatedAttribute(String name, DeprecatedAttribute attr, Clas if (checkNotNull(attr, name + " must have deprecated attribute")) { checkEquals(0, ((BoundAttribute)attr).payloadLen(), "attribute_length should equal to 0"); - checkEquals("Deprecated", attr.attributeName(), + checkEquals("Deprecated", attr.attributeName().stringValue(), name + " attribute_name_index"); } } diff --git a/test/langtools/tools/javac/classfiles/attributes/innerclasses/InnerClassesTestBase.java b/test/langtools/tools/javac/classfiles/attributes/innerclasses/InnerClassesTestBase.java index 6410b162e38..d49b9f15983 100644 --- a/test/langtools/tools/javac/classfiles/attributes/innerclasses/InnerClassesTestBase.java +++ b/test/langtools/tools/javac/classfiles/attributes/innerclasses/InnerClassesTestBase.java @@ -206,7 +206,7 @@ private void test(String classToTest, TestCase test, String...skipClasses) { if (!checkNotNull(innerClasses, "InnerClasses attribute should not be null")) { return; } - checkEquals(innerClasses.attributeName(), "InnerClasses", + checkEquals(innerClasses.attributeName().stringValue(), "InnerClasses", "innerClasses.attribute_name_index"); // Inner Classes attribute consists of length (2 bytes) // and 8 bytes for each inner class's entry. diff --git a/test/langtools/tools/javac/danglingDocComments/JBangException1.java b/test/langtools/tools/javac/danglingDocComments/JBangException1.java new file mode 100644 index 00000000000..123451aff7c --- /dev/null +++ b/test/langtools/tools/javac/danglingDocComments/JBangException1.java @@ -0,0 +1,19 @@ +///usr/bin/env jbang "$0" "$@" ; exit $? +// /nodynamiccopyright/ + +/** A class comment */ +public class JBangException1 { + + /** + * A method comment + * + * @param args a parameter comment + */ + public static void main(String[] args) { + if (args.length == 0) { + System.out.println("Hello World!"); + } else { + System.out.println("Hello " + args[0]); + } + } +} \ No newline at end of file diff --git a/test/langtools/tools/javac/danglingDocComments/JBangException2.enabled.out b/test/langtools/tools/javac/danglingDocComments/JBangException2.enabled.out new file mode 100644 index 00000000000..8934c449e3b --- /dev/null +++ b/test/langtools/tools/javac/danglingDocComments/JBangException2.enabled.out @@ -0,0 +1,2 @@ +JBangException2.java:1:1: compiler.warn.dangling.doc.comment +1 warning diff --git a/test/langtools/tools/javac/danglingDocComments/JBangException2.java b/test/langtools/tools/javac/danglingDocComments/JBangException2.java new file mode 100644 index 00000000000..1514542f3fc --- /dev/null +++ b/test/langtools/tools/javac/danglingDocComments/JBangException2.java @@ -0,0 +1,19 @@ +/** /usr/bin/env jbang "$0" "$@" ; exit $? */ +// /nodynamiccopyright/ + +/** A class comment */ +public class JBangException2 { + + /** + * A method comment + * + * @param args a parameter comment + */ + public static void main(String[] args) { + if (args.length == 0) { + System.out.println("Hello World!"); + } else { + System.out.println("Hello " + args[0]); + } + } +} \ No newline at end of file diff --git a/test/langtools/tools/javac/danglingDocComments/JBangException3.enabled.out b/test/langtools/tools/javac/danglingDocComments/JBangException3.enabled.out new file mode 100644 index 00000000000..9b08300a7c0 --- /dev/null +++ b/test/langtools/tools/javac/danglingDocComments/JBangException3.enabled.out @@ -0,0 +1,2 @@ +JBangException3.java:1:1: compiler.warn.dangling.doc.comment +1 warning diff --git a/test/langtools/tools/javac/danglingDocComments/JBangException3.java b/test/langtools/tools/javac/danglingDocComments/JBangException3.java new file mode 100644 index 00000000000..9e14dfc0b55 --- /dev/null +++ b/test/langtools/tools/javac/danglingDocComments/JBangException3.java @@ -0,0 +1,22 @@ +/// A +/// multiline +/// dangling +/// comment +// /nodynamiccopyright/ + +/** A class comment */ +public class JBangException3 { + + /** + * A method comment + * + * @param args a parameter comment + */ + public static void main(String[] args) { + if (args.length == 0) { + System.out.println("Hello World!"); + } else { + System.out.println("Hello " + args[0]); + } + } +} \ No newline at end of file diff --git a/test/langtools/tools/javac/danglingDocComments/JBangExceptionTest.java b/test/langtools/tools/javac/danglingDocComments/JBangExceptionTest.java new file mode 100644 index 00000000000..4308335f4c5 --- /dev/null +++ b/test/langtools/tools/javac/danglingDocComments/JBangExceptionTest.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * 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 + * + * @compile/ref=empty.out -XDrawDiagnostics JBangException1.java + * @compile/ref=empty.out -XDrawDiagnostics -Xlint:dangling-doc-comments JBangException1.java + * + * @compile/ref=empty.out -XDrawDiagnostics JBangException2.java + * @compile/ref=JBangException2.enabled.out -XDrawDiagnostics -Xlint:dangling-doc-comments JBangException2.java + * + * @compile/ref=empty.out -XDrawDiagnostics JBangException3.java + * @compile/ref=JBangException3.enabled.out -XDrawDiagnostics -Xlint:dangling-doc-comments JBangException3.java + */ + +// The classes being tested reside in files separate from this one because +// the classes need to provide the initial dangling comment, which would +// otherwise interfere with the JTReg test comment. For similar reasons, +// the files with test classes do __NOT__ have a copyright header. diff --git a/test/langtools/tools/javac/diags/examples/CantAccessInnerClsConstr.java b/test/langtools/tools/javac/diags/examples/LocalClassCantBeInstStatic.java similarity index 72% rename from test/langtools/tools/javac/diags/examples/CantAccessInnerClsConstr.java rename to test/langtools/tools/javac/diags/examples/LocalClassCantBeInstStatic.java index 112862cd2ef..80301cbbb77 100644 --- a/test/langtools/tools/javac/diags/examples/CantAccessInnerClsConstr.java +++ b/test/langtools/tools/javac/diags/examples/LocalClassCantBeInstStatic.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. * 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,18 +21,18 @@ * questions. */ -// key: compiler.misc.cant.access.inner.cls.constr -// key: compiler.err.invalid.mref +// key: compiler.err.local.cant.be.inst.static -class CantAccessInnerClsConstructor { +class LocalClassCantBeInstStatic { + static void foo(Object there) { + class Local { + { + there.hashCode(); + } - interface SAM { - Outer m(); - } - - class Outer { } - - static void test() { - SAM s = Outer::new; + static { + new Local(); // can't get there from here + } + } } } diff --git a/test/langtools/tools/javac/lambda/MethodReference23.out b/test/langtools/tools/javac/lambda/MethodReference23.out index 456a002bd99..6f7e1c5c909 100644 --- a/test/langtools/tools/javac/lambda/MethodReference23.out +++ b/test/langtools/tools/javac/lambda/MethodReference23.out @@ -1,6 +1,6 @@ -MethodReference23.java:52:19: compiler.err.invalid.mref: kindname.constructor, (compiler.misc.cant.access.inner.cls.constr: Inner1, MethodReference23, MethodReference23) -MethodReference23.java:53:16: compiler.err.invalid.mref: kindname.constructor, (compiler.misc.cant.access.inner.cls.constr: Inner1, MethodReference23, MethodReference23) -MethodReference23.java:57:19: compiler.err.invalid.mref: kindname.constructor, (compiler.misc.cant.access.inner.cls.constr: Inner1, , MethodReference23) -MethodReference23.java:58:16: compiler.err.invalid.mref: kindname.constructor, (compiler.misc.cant.access.inner.cls.constr: Inner1, , MethodReference23) +MethodReference23.java:52:19: compiler.err.non-static.cant.be.ref: kindname.variable, this +MethodReference23.java:53:16: compiler.err.non-static.cant.be.ref: kindname.variable, this +MethodReference23.java:57:19: compiler.err.non-static.cant.be.ref: kindname.variable, this +MethodReference23.java:58:16: compiler.err.non-static.cant.be.ref: kindname.variable, this MethodReference23.java:72:9: compiler.err.ref.ambiguous: call3, kindname.method, call3(MethodReference23.SAM21), MethodReference23, kindname.method, call3(MethodReference23.SAM22), MethodReference23 5 errors diff --git a/test/langtools/tools/javac/lambda/MethodReference37.out b/test/langtools/tools/javac/lambda/MethodReference37.out index 8db8e456daf..09dc966bd4a 100644 --- a/test/langtools/tools/javac/lambda/MethodReference37.out +++ b/test/langtools/tools/javac/lambda/MethodReference37.out @@ -1,5 +1,5 @@ MethodReference37.java:24:38: compiler.err.prob.found.req: (compiler.misc.invalid.mref: kindname.constructor, (compiler.misc.cant.apply.symbol: kindname.constructor, Inner, compiler.misc.no.args, MethodReference37.Outer, kindname.class, MethodReference37.Outer.Inner, (compiler.misc.arg.length.mismatch))) MethodReference37.java:29:39: compiler.err.prob.found.req: (compiler.misc.invalid.mref: kindname.constructor, (compiler.misc.cant.apply.symbol: kindname.constructor, Inner, compiler.misc.no.args, MethodReference37.Outer, kindname.class, MethodReference37.Outer.Inner, (compiler.misc.arg.length.mismatch))) -MethodReference37.java:34:40: compiler.err.invalid.mref: kindname.constructor, (compiler.misc.cant.access.inner.cls.constr: Inner, MethodReference37.Outer, MethodReference37.Outer) -MethodReference37.java:38:41: compiler.err.invalid.mref: kindname.constructor, (compiler.misc.cant.access.inner.cls.constr: Inner, MethodReference37.Outer, MethodReference37.Outer) +MethodReference37.java:34:40: compiler.err.prob.found.req: (compiler.misc.invalid.mref: kindname.constructor, (compiler.misc.cant.apply.symbol: kindname.constructor, Inner, compiler.misc.no.args, MethodReference37.Outer, kindname.class, MethodReference37.Outer.Inner, (compiler.misc.arg.length.mismatch))) +MethodReference37.java:38:41: compiler.err.prob.found.req: (compiler.misc.invalid.mref: kindname.constructor, (compiler.misc.cant.apply.symbol: kindname.constructor, Inner, compiler.misc.no.args, MethodReference37.Outer, kindname.class, MethodReference37.Outer.Inner, (compiler.misc.arg.length.mismatch))) 4 errors diff --git a/test/langtools/tools/javac/lambda/MethodReferenceNoThisTest.out b/test/langtools/tools/javac/lambda/MethodReferenceNoThisTest.out index 2dff751f68d..a411c340484 100644 --- a/test/langtools/tools/javac/lambda/MethodReferenceNoThisTest.out +++ b/test/langtools/tools/javac/lambda/MethodReferenceNoThisTest.out @@ -1,2 +1,2 @@ MethodReferenceNoThisTest.java:22:15: compiler.err.cant.ref.before.ctor.called: this -1 error \ No newline at end of file +1 error diff --git a/test/langtools/tools/javac/lambda/methodReference/MethodRefToInnerWithoutOuter.out b/test/langtools/tools/javac/lambda/methodReference/MethodRefToInnerWithoutOuter.out index 03b3d338369..66c50ed315b 100644 --- a/test/langtools/tools/javac/lambda/methodReference/MethodRefToInnerWithoutOuter.out +++ b/test/langtools/tools/javac/lambda/methodReference/MethodRefToInnerWithoutOuter.out @@ -1,2 +1,2 @@ -MethodRefToInnerWithoutOuter.java:22:31: compiler.err.invalid.mref: kindname.constructor, (compiler.misc.cant.access.inner.cls.constr: TestString, java.lang.String, MethodRefToInnerBase) +MethodRefToInnerWithoutOuter.java:22:31: compiler.err.non-static.cant.be.ref: kindname.variable, this 1 error diff --git a/test/langtools/tools/javac/sealed/CheckSubtypesOfSealedTest.java b/test/langtools/tools/javac/sealed/CheckSubtypesOfSealedTest.java index 0366d4982ca..0f9634423ec 100644 --- a/test/langtools/tools/javac/sealed/CheckSubtypesOfSealedTest.java +++ b/test/langtools/tools/javac/sealed/CheckSubtypesOfSealedTest.java @@ -76,7 +76,7 @@ enum CheckFor { void check(ClassModel classFile) throws Exception { boolean found = false; for (Attribute attr: classFile.attributes()) { - if (attr.attributeName().equals("PermittedSubclasses")) { + if (attr.attributeName().equalsString("PermittedSubclasses")) { PermittedSubclassesAttribute permittedSubclasses = (PermittedSubclassesAttribute)attr; found = true; if (permittedSubclasses.permittedSubclasses().isEmpty()) { @@ -99,7 +99,7 @@ void check(ClassModel classFile) throws Exception { NOT_SEALED { void check(ClassModel classFile) throws Exception { for (Attribute attr: classFile.attributes()) { - if (attr.attributeName().equals("PermittedSubclasses")) { + if (attr.attributeName().equalsString("PermittedSubclasses")) { throw new AssertionError(classFile.thisClass().name() + " should not be sealed"); } } diff --git a/test/langtools/tools/javap/T6716452.java b/test/langtools/tools/javap/T6716452.java index 63ccead52e7..20c382918c3 100644 --- a/test/langtools/tools/javap/T6716452.java +++ b/test/langtools/tools/javap/T6716452.java @@ -70,7 +70,7 @@ > void test(MethodModel mm, AttributeMapper attr, Clas if (!c.isAssignableFrom(mm.attributes().get(index).getClass())) { error(mm + ": unexpected attribute found," + " expected " + c.getName() - + " found " + mm.attributes().get(index).attributeName()); + + " found " + mm.attributes().get(index).attributeName().stringValue()); } } else { error(mm + ": expected attribute " + attr.name() + " not found"); diff --git a/test/lib/jdk/test/lib/cds/CDSAppTester.java b/test/lib/jdk/test/lib/cds/CDSAppTester.java index c39e6bb8e94..d83c3c36e41 100644 --- a/test/lib/jdk/test/lib/cds/CDSAppTester.java +++ b/test/lib/jdk/test/lib/cds/CDSAppTester.java @@ -28,6 +28,7 @@ import jdk.test.lib.process.ProcessTools; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.StringArrayUtils; +import jtreg.SkippedException; /* * This is a base class used for testing CDS functionalities with complex applications. @@ -42,9 +43,13 @@ abstract public class CDSAppTester { private final String staticArchiveFileLog; private final String dynamicArchiveFile; private final String dynamicArchiveFileLog; - private final String productionRunLog; + private int numProductionRuns = 0; public CDSAppTester(String name) { + if (CDSTestUtils.DYNAMIC_DUMP) { + throw new SkippedException("Tests based on CDSAppTester should be excluded when -Dtest.dynamic.cds.archive is specified"); + } + // Old workflow this.name = name; classListFile = name() + ".classlist"; @@ -53,7 +58,14 @@ public CDSAppTester(String name) { staticArchiveFileLog = staticArchiveFile + ".log"; dynamicArchiveFile = name() + ".dynamic.jsa"; dynamicArchiveFileLog = dynamicArchiveFile + ".log"; - productionRunLog = name() + ".production.log"; + } + + private String productionRunLog() { + if (numProductionRuns == 0) { + return name() + ".production.log"; + } else { + return name() + ".production." + numProductionRuns + ".log"; + } } private enum Workflow { @@ -97,6 +109,11 @@ public String classpath(RunMode runMode) { public void checkExecution(OutputAnalyzer out, RunMode runMode) throws Exception {} private Workflow workflow; + private boolean checkExitValue = true; + + public final void setCheckExitValue(boolean b) { + checkExitValue = b; + } public final boolean isStaticWorkflow() { return workflow == Workflow.STATIC; @@ -134,7 +151,10 @@ private OutputAnalyzer executeAndCheck(String[] cmdLine, RunMode runMode, String for (String logFile : logFiles) { listOutputFile(logFile); } - output.shouldHaveExitValue(0); + if (checkExitValue) { + output.shouldHaveExitValue(0); + } + output.shouldNotContain(CDSTestUtils.MSG_STATIC_FIELD_MAY_HOLD_DIFFERENT_VALUE); CDSTestUtils.checkCommonExecExceptions(output); checkExecution(output, runMode); return output; @@ -189,10 +209,22 @@ private OutputAnalyzer dumpDynamicArchive() throws Exception { } private OutputAnalyzer productionRun() throws Exception { + return productionRun(null, null); + } + + public OutputAnalyzer productionRun(String[] extraVmArgs) throws Exception { + return productionRun(extraVmArgs, null); + } + + // After calling run(String[]), you can call this method to run the app again, with the AOTCache + // using different args to the VM and application. + public OutputAnalyzer productionRun(String[] extraVmArgs, String[] extraAppArgs) throws Exception { RunMode runMode = RunMode.PRODUCTION; String[] cmdLine = StringArrayUtils.concat(vmArgs(runMode), + "-XX:+UnlockDiagnosticVMOptions", + "-XX:VerifyArchivedFields=2", // make sure archived heap objects are good. "-cp", classpath(runMode), - logToFile(productionRunLog, "cds")); + logToFile(productionRunLog(), "cds")); if (isStaticWorkflow()) { cmdLine = StringArrayUtils.concat(cmdLine, "-XX:SharedArchiveFile=" + staticArchiveFile); @@ -200,8 +232,19 @@ private OutputAnalyzer productionRun() throws Exception { cmdLine = StringArrayUtils.concat(cmdLine, "-XX:SharedArchiveFile=" + dynamicArchiveFile); } + if (extraVmArgs != null) { + cmdLine = StringArrayUtils.concat(cmdLine, extraVmArgs); + } + cmdLine = StringArrayUtils.concat(cmdLine, appCommandLine(runMode)); - return executeAndCheck(cmdLine, runMode, productionRunLog); + + if (extraAppArgs != null) { + cmdLine = StringArrayUtils.concat(cmdLine, extraAppArgs); + } + + OutputAnalyzer out = executeAndCheck(cmdLine, runMode, productionRunLog()); + numProductionRuns ++; + return out; } public void run(String args[]) throws Exception { diff --git a/test/lib/jdk/test/lib/cds/CDSTestUtils.java b/test/lib/jdk/test/lib/cds/CDSTestUtils.java index 7115912380a..a913f2f9fa2 100644 --- a/test/lib/jdk/test/lib/cds/CDSTestUtils.java +++ b/test/lib/jdk/test/lib/cds/CDSTestUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,6 +51,8 @@ public class CDSTestUtils { "Unable to allocate region, java heap range is already in use."; public static final String MSG_DYNAMIC_NOT_SUPPORTED = "-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded"; + public static final String MSG_STATIC_FIELD_MAY_HOLD_DIFFERENT_VALUE = + "an object points to a static field that may hold a different value at runtime"; public static final boolean DYNAMIC_DUMP = Boolean.getBoolean("test.dynamic.cds.archive"); public interface Checker { @@ -284,6 +286,7 @@ public static OutputAnalyzer checkDump(OutputAnalyzer output, String... extraMat output.shouldContain("Written dynamic archive 0x"); } output.shouldHaveExitValue(0); + output.shouldNotContain(MSG_STATIC_FIELD_MAY_HOLD_DIFFERENT_VALUE); for (String match : extraMatches) { output.shouldContain(match); @@ -296,6 +299,7 @@ public static OutputAnalyzer checkDump(OutputAnalyzer output, String... extraMat public static OutputAnalyzer checkBaseDump(OutputAnalyzer output) throws Exception { output.shouldContain("Loading classes to share"); output.shouldHaveExitValue(0); + output.shouldNotContain(MSG_STATIC_FIELD_MAY_HOLD_DIFFERENT_VALUE); return output; } @@ -859,4 +863,24 @@ public static Path copyFile(String srcFile, String destDir) throws Exception { Files.copy(srcPath, destPath, REPLACE_EXISTING, COPY_ATTRIBUTES); return destPath; } + + // Some tests were initially written without the knowledge of -XX:+AOTClassLinking. These tests need to + // be adjusted if -XX:+AOTClassLinking is specified in jtreg -vmoptions or -javaoptions: + public static boolean isAOTClassLinkingEnabled() { + return isBooleanVMOptionEnabledInCommandLine("AOTClassLinking"); + } + + public static boolean isBooleanVMOptionEnabledInCommandLine(String optionName) { + String lastMatch = null; + String pattern = "^-XX:." + optionName + "$"; + for (String s : Utils.getTestJavaOpts()) { + if (s.matches(pattern)) { + lastMatch = s; + } + } + if (lastMatch != null && lastMatch.equals("-XX:+" + optionName)) { + return true; + } + return false; + } }