Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow AnonymousClassDefiner class initializer complete normally if running on JDK >=17 with Unsafe.defineAnonymousClass removed. #1821

Merged
1 commit merged into from
May 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions core/src/com/google/inject/internal/aop/AnonymousClassDefiner.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,36 @@ final class AnonymousClassDefiner implements ClassDefiner {
private static final sun.misc.Unsafe THE_UNSAFE;
private static final Method ANONYMOUS_DEFINE_METHOD;

/** True if this class err'd during initialization and should not be used. */
static final boolean HAS_ERROR;

static {
sun.misc.Unsafe theUnsafe;
Method anonymousDefineMethod;
try {
THE_UNSAFE = UnsafeGetter.getUnsafe();
theUnsafe = UnsafeGetter.getUnsafe();
// defineAnonymousClass was removed in JDK17, so we must refer to it reflectively.
ANONYMOUS_DEFINE_METHOD =
anonymousDefineMethod =
sun.misc.Unsafe.class.getMethod(
"defineAnonymousClass", Class.class, byte[].class, Object[].class);
} catch (ReflectiveOperationException e) {
throw new ExceptionInInitializerError(e);
theUnsafe = null;
anonymousDefineMethod = null;
}

THE_UNSAFE = theUnsafe;
ANONYMOUS_DEFINE_METHOD = anonymousDefineMethod;
HAS_ERROR = theUnsafe == null;
}

@Override
public Class<?> define(Class<?> hostClass, byte[] bytecode) throws Exception {
if (HAS_ERROR) {
throw new IllegalStateException(
"Should not be called. An earlier error occurred during AnonymousClassDefiner static"
+ " initialization.");
}

return (Class<?>) ANONYMOUS_DEFINE_METHOD.invoke(THE_UNSAFE, hostClass, bytecode, null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ final class UnsafeClassDefiner implements ClassDefiner {
static {
ClassDefiner unsafeDefiner =
tryPrivileged(AnonymousClassDefiner::new, "Cannot bind Unsafe.defineAnonymousClass");
if (unsafeDefiner == null) {

if (AnonymousClassDefiner.HAS_ERROR || unsafeDefiner == null) {
unsafeDefiner =
tryPrivileged(
HiddenClassDefiner::new, "Cannot bind MethodHandles.Lookup.defineHiddenClass");
Expand Down
Loading