Skip to content

Commit

Permalink
Add access bridge
Browse files Browse the repository at this point in the history
  • Loading branch information
Karlatemp committed Mar 16, 2021
1 parent da2dbfd commit 1459d4e
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package io.github.karlatemp.unsafeaccessor;

class ProtectedObject {
boolean trusted;

void checkTrusted() {
if (!trusted) throw new SecurityException();
}

public ProtectedObject(boolean t) {
this.trusted = t;
}

public ProtectedObject() {
this(true);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,12 @@
*
* @since 1.3.0
*/
public final class SecurityCheck {
private final boolean trusted;
public final class SecurityCheck extends ProtectedObject {

SecurityCheck() {
trusted = true;
}

SecurityCheck(boolean trusted) {
this.trusted = trusted;
}

static final SecurityCheck INSTANCE = new SecurityCheck();
static Permission PERMISSION_GET_UNSAFE;
Expand All @@ -33,11 +29,6 @@ public static SecurityCheck getInstance() {
return INSTANCE;
}

private void checkTrusted() {
if (!trusted)
throw new IllegalStateException();
}

public Permission getPermission() {
checkTrusted();
return PERMISSION_GET_UNSAFE;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package io.github.karlatemp.unsafeaccessor;

import java.lang.invoke.MethodHandles;
import java.lang.reflect.AccessibleObject;

/**
* Direct unsafe access
* <p>
* A bridge object to access unsafe.
* <p>
* Unlike other methods, using this bridge will not trigger any permission checks.
* The permission check will only happen in {@link #getInstance()}
*
* @since 1.4.0
*/
public final class UnsafeAccess extends ProtectedObject {
static final UnsafeAccess INSTANCE = new UnsafeAccess();

public static UnsafeAccess getInstance() {
SecurityCheck.getInstance();
return INSTANCE;
}

public SecurityCheck getSecuritySettings() {
checkTrusted();
return SecurityCheck.INSTANCE;
}

public Unsafe getUnsafe() {
checkTrusted();
return Unsafe.getUnsafe0();
}

/**
* Use {@link #getTrustedIn(Class)}
*
* @return MethodHandles.Lookup.IMPL_LOOKUP
*/
@Deprecated
public MethodHandles.Lookup getTrusted() {
checkTrusted();
return Root.RootLookupHolder.ROOT;
}

public MethodHandles.Lookup getTrustedIn(Class<?> target) {
checkTrusted();
return Root.RootLookupHolder.trustedIn(target);
}

public <T extends AccessibleObject> T openAccess(T object) {
checkTrusted();
Root.OpenAccess.openAccess0(object, true);
return object;
}

public <T extends AccessibleObject> T setAccessible(T object, boolean accessible) {
checkTrusted();
Root.OpenAccess.openAccess0(object, accessible);
return object;
}
}

0 comments on commit 1459d4e

Please sign in to comment.