1 // Copyright 2022 Code Intelligence GmbH 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package com.code_intelligence.jazzer.runtime; 16 17 import java.lang.reflect.Field; 18 import sun.misc.Unsafe; 19 20 public final class UnsafeProvider { 21 private static final Unsafe UNSAFE = getUnsafeInternal(); 22 getUnsafe()23 public static Unsafe getUnsafe() { 24 return UNSAFE; 25 } 26 getUnsafeInternal()27 private static Unsafe getUnsafeInternal() { 28 try { 29 // The Java agent is loaded by the bootstrap class loader and should thus 30 // pass the security checks in getUnsafe. 31 return Unsafe.getUnsafe(); 32 } catch (Throwable unused) { 33 // If not running as an agent, use the classical reflection trick to get an Unsafe instance, 34 // taking into account that the private field may have a name other than "theUnsafe": 35 // https://android.googlesource.com/platform/libcore/+/gingerbread/luni/src/main/java/sun/misc/Unsafe.java#32 36 try { 37 for (Field f : Unsafe.class.getDeclaredFields()) { 38 if (f.getType() == Unsafe.class) { 39 f.setAccessible(true); 40 return (Unsafe) f.get(null); 41 } 42 } 43 return null; 44 } catch (Throwable t) { 45 t.printStackTrace(); 46 return null; 47 } 48 } 49 } 50 } 51