Home | History | Annotate | Download | only in shadows
      1 package org.robolectric.shadows;
      2 
      3 import static android.os.Build.VERSION_CODES.LOLLIPOP;
      4 
      5 import android.annotation.TargetApi;
      6 import dalvik.system.VMRuntime;
      7 import java.lang.reflect.Array;
      8 import javax.annotation.Nullable;
      9 import org.robolectric.annotation.Implementation;
     10 import org.robolectric.annotation.Implements;
     11 import org.robolectric.annotation.Resetter;
     12 import org.robolectric.res.android.NativeObjRegistry;
     13 
     14 @Implements(value = VMRuntime.class, isInAndroidSdk = false)
     15 public class ShadowVMRuntime {
     16 
     17   private final NativeObjRegistry<Object> nativeObjRegistry =
     18       new NativeObjRegistry<>("VRRuntime.nativeObjectRegistry");
     19   // There actually isn't any android JNI code to call through to in Robolectric due to
     20   // cross-platform compatibility issues. We default to a reasonable value that reflects the devices
     21   // that would commonly run this code.
     22   private static boolean is64Bit = true;
     23 
     24   @Implementation(minSdk = LOLLIPOP)
     25   public Object newUnpaddedArray(Class<?> klass, int size) {
     26     return Array.newInstance(klass, size);
     27   }
     28 
     29   @Implementation
     30   public Object newNonMovableArray(Class<?> type, int size) {
     31     if (type.equals(int.class)) {
     32       return new int[size];
     33     }
     34     return null;
     35   }
     36 
     37   /**
     38    * Returns a unique identifier of the object instead of a 'native' address.
     39    */
     40   @Implementation
     41   public long addressOf(Object obj) {
     42     return nativeObjRegistry.register(obj);
     43   }
     44 
     45   /**
     46    * Returns the object previously registered with {@link #addressOf(Object)}.
     47    */
     48   public @Nullable
     49   Object getObjectForAddress(long address) {
     50     return nativeObjRegistry.getNativeObject(address);
     51   }
     52 
     53   /**
     54    * Returns whether the VM is running in 64-bit mode. Available in Android L+. Defaults to true.
     55    */
     56   @Implementation(minSdk = LOLLIPOP)
     57   protected boolean is64Bit() {
     58     return ShadowVMRuntime.is64Bit;
     59   }
     60 
     61   /** Sets whether the VM is running in 64-bit mode. */
     62   @TargetApi(LOLLIPOP)
     63   public static void setIs64Bit(boolean is64Bit) {
     64     ShadowVMRuntime.is64Bit = is64Bit;
     65   }
     66 
     67   @Resetter
     68   public static void reset() {
     69     ShadowVMRuntime.is64Bit = true;
     70   }
     71 }
     72