Home | History | Annotate | Download | only in src
      1 /*
      2  * Copyright (C) 2015 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 sun.misc.Unsafe;
     18 import java.lang.reflect.Field;
     19 
     20 public class Main {
     21 
     22   long instanceField;
     23   static long myLongField1;
     24   static long myLongField2;
     25 
     26   public static void main(String[] args) throws Exception {
     27     Unsafe unsafe = getUnsafe();
     28     Main f = new Main();
     29     long offset = unsafe.objectFieldOffset(Main.class.getDeclaredField("instanceField"));
     30     getUnsafe(); // spill offset
     31     long a = myLongField1;
     32     // We used the hinted register for the low part of b, which is EBX, as requested
     33     // by the intrinsic below. Allocating EBX for the low part, would put ESP as the high
     34     // part, and we did not check that ESP was blocked.
     35     long b = myLongField2;
     36     unsafe.compareAndSwapLong(f, offset, a, b);
     37   }
     38 
     39 
     40   private static Unsafe getUnsafe() throws Exception {
     41     Field f = Unsafe.class.getDeclaredField("theUnsafe");
     42     f.setAccessible(true);
     43     return (Unsafe) f.get(null);
     44   }
     45 }
     46