1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 import java.lang.reflect.Field; 18 import java.lang.reflect.Method; 19 import jdk.internal.misc.Unsafe; 20 21 class UnsafeMicroBenchmark extends MicroBenchmark { 22 protected Unsafe theUnsafe; 23 UnsafeMicroBenchmark()24 UnsafeMicroBenchmark() throws Throwable { 25 Field f = Unsafe.class.getDeclaredField("theUnsafe"); 26 f.setAccessible(true); 27 theUnsafe = (Unsafe) f.get(null); 28 } 29 getFieldOffset(Field field)30 protected long getFieldOffset(Field field) throws Throwable { 31 return theUnsafe.objectFieldOffset(field); 32 } 33 getStaticFieldOffset(Field staticField)34 protected long getStaticFieldOffset(Field staticField) throws Throwable { 35 if (System.getProperty("java.vm.name").equals("Dalvik")) { 36 // field.getOffset(); ()J 37 Method m = Field.class.getDeclaredMethod("getOffset"); 38 return (Integer) m.invoke(staticField); 39 } else { 40 // theUnsafe.staticFieldOffset(field) (Ljava/lang/Field;)J 41 Method m = Unsafe.class.getDeclaredMethod("staticFieldOffset", Field.class); 42 return (Long) m.invoke(theUnsafe, staticField); 43 } 44 } 45 }