From b39494dbe68f91045850778cac4b661b38beb615 Mon Sep 17 00:00:00 2001 From: Richard Hernandez Date: Tue, 26 May 2020 20:12:06 -0700 Subject: [PATCH] Fix fallback behavior of UnsafeReflectionAllocator when AccessibleObject isn't so accessible --- .../reflect/UnsafeReflectionAccessor.java | 2 +- .../reflect/UnsafeReflectionAccessorTest.java | 26 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/gson/src/main/java/com/google/gson/internal/reflect/UnsafeReflectionAccessor.java b/gson/src/main/java/com/google/gson/internal/reflect/UnsafeReflectionAccessor.java index 749335b7..b23d7bab 100644 --- a/gson/src/main/java/com/google/gson/internal/reflect/UnsafeReflectionAccessor.java +++ b/gson/src/main/java/com/google/gson/internal/reflect/UnsafeReflectionAccessor.java @@ -79,7 +79,7 @@ final class UnsafeReflectionAccessor extends ReflectionAccessor { private static Field getOverrideField() { try { return AccessibleObject.class.getDeclaredField("override"); - } catch (NoSuchFieldException e) { + } catch (Exception e) { return null; } } diff --git a/gson/src/test/java/com/google/gson/internal/reflect/UnsafeReflectionAccessorTest.java b/gson/src/test/java/com/google/gson/internal/reflect/UnsafeReflectionAccessorTest.java index d5caaf53..b330e662 100644 --- a/gson/src/test/java/com/google/gson/internal/reflect/UnsafeReflectionAccessorTest.java +++ b/gson/src/test/java/com/google/gson/internal/reflect/UnsafeReflectionAccessorTest.java @@ -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; @@ -41,6 +43,30 @@ public class UnsafeReflectionAccessorTest { } } + @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;