Skip to content

Commit

Permalink
Merge pull request #1712 from rhernandez35/master
Browse files Browse the repository at this point in the history
Fix fallback behavior of UnsafeReflectionAllocator when AccessibleObject isn't so accessible
  • Loading branch information
eamonnmcmanus committed Aug 4, 2021
2 parents a14f161 + b39494d commit 63e747f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
Expand Up @@ -79,7 +79,7 @@ private static Object getUnsafeInstance() {
private static Field getOverrideField() {
try {
return AccessibleObject.class.getDeclaredField("override");
} catch (NoSuchFieldException e) {
} catch (Exception e) {
return null;
}
}
Expand Down
Expand Up @@ -15,10 +15,12 @@
*/
package com.google.gson.internal.reflect;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.lang.reflect.Field;
import java.security.Permission;

import org.junit.Test;

Expand All @@ -41,6 +43,30 @@ public void testMakeAccessibleWithUnsafe() throws Exception {
}
}

@Test
public void testMakeAccessibleWithRestrictiveSecurityManager() throws Exception {
final Permission accessDeclaredMembers = new RuntimePermission("accessDeclaredMembers");
final SecurityManager original = System.getSecurityManager();
SecurityManager restrictiveManager = new SecurityManager() {
@Override
public void checkPermission(Permission perm) {
if (accessDeclaredMembers.equals(perm)) {
throw new SecurityException("nope");
}
}
};
System.setSecurityManager(restrictiveManager);

try {
UnsafeReflectionAccessor accessor = new UnsafeReflectionAccessor();
Field field = ClassWithPrivateFinalFields.class.getDeclaredField("a");
assertFalse("override field should have been inaccessible", accessor.makeAccessibleWithUnsafe(field));
accessor.makeAccessible(field);
} finally {
System.setSecurityManager(original);
}
}

@SuppressWarnings("unused")
private static final class ClassWithPrivateFinalFields {
private final String a;
Expand Down

0 comments on commit 63e747f

Please sign in to comment.