1/* 2 * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23package org.graalvm.compiler.jtt.jdk; 24 25import java.lang.reflect.Field; 26 27import org.junit.Test; 28 29import sun.misc.Unsafe; 30 31import org.graalvm.compiler.jtt.JTTTest; 32 33/* 34 */ 35public class UnsafeAccess01 extends JTTTest { 36 37 private static int randomValue = 100; 38 private static final Unsafe unsafe; 39 private static final long offset; 40 private static Object staticObject = new TestClass(); 41 42 static { 43 unsafe = getUnsafe(); 44 Field field = null; 45 try { 46 field = TestClass.class.getDeclaredField("field"); 47 } catch (NoSuchFieldException e) { 48 } catch (SecurityException e) { 49 } 50 offset = unsafe.objectFieldOffset(field); 51 } 52 53 private static class TestClass { 54 private int field = 42; 55 } 56 57 public static int test() { 58 final TestClass object = new TestClass(); 59 final int value = unsafe.getInt(object, offset); 60 return value; 61 } 62 63 static Unsafe getUnsafe() { 64 try { 65 final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe"); 66 unsafeField.setAccessible(true); 67 return (Unsafe) unsafeField.get(null); 68 } catch (Exception e) { 69 throw new Error(e); 70 } 71 } 72 73 @Test 74 public void run0() throws Throwable { 75 runTest("test"); 76 } 77 78 @Test 79 public void runDiamond() throws Throwable { 80 runTest("testDiamond"); 81 } 82 83 public static int testDiamond() { 84 85 final Object object = staticObject; 86 final int oldValue = ((TestClass) object).field; 87 88 if (randomValue == 100) { 89 unsafe.putInt(object, offset, 41); 90 } else { 91 unsafe.putInt(object, offset, 40); 92 } 93 unsafe.putInt(object, offset, 42); 94 return oldValue; 95 } 96} 97