Skip to content

Commit

Permalink
Use Unsafe API in more correct way
Browse files Browse the repository at this point in the history
 * pass result of Unsafe.staticFieldBase() instead of Lookup.class
to conform with specification for Unsafe.getObject() requirements.
The specification requires the arguments for Unsafe.getObject()
to be obtained from Unsafe.staticFieldBase() and Unsafe.staticFieldOffset().
 * avoid calling Unsafe.getObject() via reflection, because passing
result of Unsafe.staticFieldBase() via reflection might cause problems
if it is not real java object.

Fixes #1672
  • Loading branch information
alsemenov committed May 3, 2023
1 parent a99b87a commit eae57e3
Showing 1 changed file with 5 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@
final class HiddenClassDefiner implements ClassDefiner {

private static final Object THE_UNSAFE;
private static final Object TRUSTED_LOOKUP_BASE;
private static final Object TRUSTED_LOOKUP_OFFSET;
private static final Method GET_OBJECT_METHOD;
private static final Object HIDDEN_CLASS_OPTIONS;
private static final Method HIDDEN_DEFINE_METHOD;

Expand All @@ -41,9 +41,10 @@ final class HiddenClassDefiner implements ClassDefiner {
theUnsafeField.setAccessible(true);
THE_UNSAFE = theUnsafeField.get(null);
Field trustedLookupField = Lookup.class.getDeclaredField("IMPL_LOOKUP");
Method baseMethod = unsafeType.getMethod("staticFieldBase", Field.class);
TRUSTED_LOOKUP_BASE = baseMethod.invoke(THE_UNSAFE, trustedLookupField);
Method offsetMethod = unsafeType.getMethod("staticFieldOffset", Field.class);
TRUSTED_LOOKUP_OFFSET = offsetMethod.invoke(THE_UNSAFE, trustedLookupField);
GET_OBJECT_METHOD = unsafeType.getMethod("getObject", Object.class, long.class);
HIDDEN_CLASS_OPTIONS = classOptions("NESTMATE");
HIDDEN_DEFINE_METHOD =
Lookup.class.getMethod(
Expand All @@ -56,7 +57,8 @@ final class HiddenClassDefiner implements ClassDefiner {
@Override
public Class<?> define(Class<?> hostClass, byte[] bytecode) throws Exception {
Lookup trustedLookup =
(Lookup) GET_OBJECT_METHOD.invoke(THE_UNSAFE, Lookup.class, TRUSTED_LOOKUP_OFFSET);
(Lookup) ((sun.misc.Unsafe)THE_UNSAFE)
.getObject(TRUSTED_LOOKUP_BASE, ((Number)TRUSTED_LOOKUP_OFFSET).longValue());
Lookup definedLookup =
(Lookup)
HIDDEN_DEFINE_METHOD.invoke(
Expand Down

0 comments on commit eae57e3

Please sign in to comment.