Java Examples for sun.misc.Unsafe

The following java examples will help you to understand the usage of sun.misc.Unsafe. These source code samples are taken from different open source projects.

Example 1
Project: sef4j-master  File: InstrumenterHelper.java View source code
public sun.misc.Unsafe run() {
    try {
        java.lang.reflect.Field singleoneInstanceField = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
        boolean prev = singleoneInstanceField.isAccessible();
        singleoneInstanceField.setAccessible(true);
        sun.misc.Unsafe ret = (sun.misc.Unsafe) singleoneInstanceField.get(null);
        singleoneInstanceField.setAccessible(prev);
        return ret;
    } catch (Throwable e) {
        LOG.error("Could not instanciate sun.miscUnsafe. should use java.nio DirectByteBuffer ?", e);
        return null;
    }
}
Example 2
Project: jdeps-maven-plugin-master  File: ViolationTest.java View source code
@Test
public void compareTo_sameDependents_differentDependencies_orderedByDependencies() throws Exception {
    Violation smaller = Violation.buildForDependent(DEPENDENT).addDependencies(InternalType.of("sun.misc", "BASE64Decoder", "", ""), InternalType.of("sun.misc", "Unsafe", "", "")).build();
    Violation greater = Violation.buildForDependent(DEPENDENT).addDependencies(InternalType.of("sun.misc", "BASE64Encoder", "", ""), InternalType.of("sun.misc", "Unsafe", "", "")).build();
    assertThat(smaller.compareTo(greater)).isNegative();
    assertThat(greater.compareTo(smaller)).isPositive();
}
Example 3
Project: TridentCommons-master  File: UnsafeTool.java View source code
/**
     * Obtains the instance of unsafe
     *
     * <p>May not exist on certain platforms</p>
     *
     * @return the unsafe instance, if it exists
     */
private static Unsafe hackUnsafe() {
    try {
        Class<?> c = Class.forName("sun.misc.Unsafe");
        Field field = c.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        return (Unsafe) field.get(null);
    } catch (ClassNotFoundExceptionNoSuchFieldException |  e) {
        TridentLogger.error("Your platform does not support sun.misc.Unsafe");
        Handler.forPlugins().disable(TridentPlugin.instance());
    } catch (IllegalAccessException e) {
        e.printStackTrace();
        Handler.forPlugins().disable(TridentPlugin.instance());
    }
    return null;
}
Example 4
Project: flink-master  File: CommonTestUtils.java View source code
@SuppressWarnings("restriction")
private static sun.misc.Unsafe getUnsafe() {
    try {
        Field unsafeField = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
        unsafeField.setAccessible(true);
        return (sun.misc.Unsafe) unsafeField.get(null);
    } catch (SecurityException e) {
        throw new RuntimeException("Could not access the sun.misc.Unsafe handle, permission denied by security manager.", e);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException("The static handle field in sun.misc.Unsafe was not found.");
    } catch (IllegalArgumentException e) {
        throw new RuntimeException("Bug: Illegal argument reflection access for static field.", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Access to sun.misc.Unsafe is forbidden by the runtime.", e);
    } catch (Throwable t) {
        throw new RuntimeException("Unclassified error while trying to access the sun.misc.Unsafe handle.", t);
    }
}
Example 5
Project: Multiverse-master  File: ToolUnsafe.java View source code
/**
     * Fetch the Unsafe.  Use With Caution.
     *
     * @return an Unsafe instance.
     */
public static Unsafe getUnsafe() {
    // Not on bootclasspath
    if (ToolUnsafe.class.getClassLoader() == null) {
        return Unsafe.getUnsafe();
    }
    try {
        final Field field = Unsafe.class.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        return (Unsafe) field.get(ToolUnsafe.class);
    } catch (Exception e) {
        throw new RuntimeException("Could not access sun.misc.Unsafe", e);
    }
}
Example 6
Project: extended-stacktrace-master  File: UtilUnsafe.java View source code
public static Unsafe getUnsafe1() {
    // Not on bootclasspath
    if (UtilUnsafe.class.getClassLoader() == null)
        return Unsafe.getUnsafe();
    try {
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        return (Unsafe) f.get(UtilUnsafe.class);
    } catch (Exception e) {
        throw new RuntimeException("Could not obtain access to sun.misc.Unsafe", e);
    }
}
Example 7
Project: voltdb-master  File: UnsignedBytes.java View source code
@Override
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x)) {
            return k.cast(x);
        }
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 8
Project: forbidden-apis-master  File: AsmUtilsTest.java View source code
@Test
public void testGlob() {
    Pattern pat = glob2Pattern("a.b.c.*");
    assertTrue(pat.matcher("a.b.c.d").matches());
    assertTrue(pat.matcher("a.b.c.def").matches());
    assertFalse(pat.matcher("a.b.c").matches());
    assertFalse(pat.matcher("a.b.c.d.e").matches());
    pat = glob2Pattern("a.b.c.**");
    assertTrue(pat.matcher("a.b.c.d").matches());
    assertTrue(pat.matcher("a.b.c.def").matches());
    assertTrue(pat.matcher("a.b.c.d.e").matches());
    assertTrue(pat.matcher("a.b.c.d.e.f").matches());
    pat = glob2Pattern("sun.*.*");
    assertTrue(pat.matcher("sun.misc.Unsafe").matches());
    assertTrue(pat.matcher("sun.misc.Unsafe$1").matches());
    assertFalse(pat.matcher("sun.misc.Unsafe.xy").matches());
    pat = glob2Pattern("java.**.Array?");
    assertTrue(pat.matcher("java.util.Arrays").matches());
    assertFalse(pat.matcher("java.util.ArrayList").matches());
    assertFalse(pat.matcher("java.util.Array").matches());
    assertTrue(pat.matcher("java.lang.reflect.Arrays").matches());
}
Example 9
Project: tomee-master  File: PojoSerialization.java View source code
public Class<?> run() {
    try {
        return Thread.currentThread().getContextClassLoader().loadClass("sun.misc.Unsafe");
    } catch (final Exception e) {
        try {
            return ClassLoader.getSystemClassLoader().loadClass("sun.misc.Unsafe");
        } catch (final ClassNotFoundException e1) {
            throw new IllegalStateException("Cannot get sun.misc.Unsafe", e);
        }
    }
}
Example 10
Project: h2o-2-master  File: CountedCompleter.java View source code
/**
     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
     * Replace with a simple call to Unsafe.getUnsafe when integrating
     * into a jdk.
     *
     * @return a sun.misc.Unsafe
     */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

                public sun.misc.Unsafe run() throws Exception {
                    java.lang.reflect.Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
                    f.setAccessible(true);
                    return (sun.misc.Unsafe) f.get(null);
                }
            });
        } catch (java.security.PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics", e.getCause());
        }
    }
}
Example 11
Project: h2o-3-master  File: CountedCompleter.java View source code
/**
     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
     * Replace with a simple call to Unsafe.getUnsafe when integrating
     * into a jdk.
     *
     * @return a sun.misc.Unsafe
     */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

                public sun.misc.Unsafe run() throws Exception {
                    java.lang.reflect.Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
                    f.setAccessible(true);
                    return (sun.misc.Unsafe) f.get(null);
                }
            });
        } catch (java.security.PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics", e.getCause());
        }
    }
}
Example 12
Project: high-scale-lib-master  File: UnsafeCounter.java View source code
public static Unsafe getUnsafe() {
    // Not on bootclasspath
    if (UtilUnsafe.class.getClassLoader() == null)
        return Unsafe.getUnsafe();
    try {
        final Field fld = Unsafe.class.getDeclaredField("theUnsafe");
        fld.setAccessible(true);
        return (Unsafe) fld.get(UtilUnsafe.class);
    } catch (Exception e) {
        throw new RuntimeException("Could not obtain access to sun.misc.Unsafe", e);
    }
}
Example 13
Project: JCTools-master  File: UnsafeCounter.java View source code
public static Unsafe getUnsafe() {
    // Not on bootclasspath
    if (UtilUnsafe.class.getClassLoader() == null)
        return Unsafe.getUnsafe();
    try {
        final Field fld = Unsafe.class.getDeclaredField("theUnsafe");
        fld.setAccessible(true);
        return (Unsafe) fld.get(UtilUnsafe.class);
    } catch (Exception e) {
        throw new RuntimeException("Could not obtain access to sun.misc.Unsafe", e);
    }
}
Example 14
Project: synchrobench-master  File: Field.java View source code
public static Object getValue(Object reference, long field, Type type) {
    Unsafe unsafe = UnsafeHolder.getUnsafe();
    switch(type) {
        case BYTE:
            return unsafe.getByte(reference, field);
        case BOOLEAN:
            return unsafe.getBoolean(reference, field);
        case CHAR:
            return unsafe.getChar(reference, field);
        case SHORT:
            return unsafe.getShort(reference, field);
        case INT:
            return unsafe.getInt(reference, field);
        case LONG:
            return unsafe.getLong(reference, field);
        case FLOAT:
            return unsafe.getFloat(reference, field);
        case DOUBLE:
            return unsafe.getDouble(reference, field);
        case OBJECT:
            return unsafe.getObject(reference, field);
    }
    return null;
}
Example 15
Project: texai-master  File: UtilUnsafe.java View source code
// dummy private constructor
/** Fetch the Unsafe.  Use With Caution. */
public static Unsafe getUnsafe() {
    // Not on bootclasspath
    if (UtilUnsafe.class.getClassLoader() == null) {
        return Unsafe.getUnsafe();
    }
    try {
        final Field fld = Unsafe.class.getDeclaredField("theUnsafe");
        fld.setAccessible(true);
        return (Unsafe) fld.get(UtilUnsafe.class);
    } catch (Exception e) {
        throw new RuntimeException("Could not obtain access to sun.misc.Unsafe", e);
    }
}
Example 16
Project: galaxy-master  File: UtilUnsafe.java View source code
public static Unsafe getUnsafe1() {
    // Not on bootclasspath
    if (UtilUnsafe.class.getClassLoader() == null)
        return Unsafe.getUnsafe();
    try {
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        return (Unsafe) f.get(UtilUnsafe.class);
    } catch (Exception e) {
        throw new RuntimeException("Could not obtain access to sun.misc.Unsafe", e);
    }
}
Example 17
Project: quasar-master  File: UtilUnsafe.java View source code
public static Unsafe getUnsafe1() {
    // Not on bootclasspath
    if (UtilUnsafe.class.getClassLoader() == null)
        return Unsafe.getUnsafe();
    try {
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        return (Unsafe) f.get(UtilUnsafe.class);
    } catch (Exception e) {
        throw new RuntimeException("Could not obtain access to sun.misc.Unsafe", e);
    }
}
Example 18
Project: stratosphere-master  File: MemoryUtils.java View source code
@SuppressWarnings("restriction")
private static sun.misc.Unsafe getUnsafe() {
    try {
        Field unsafeField = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
        unsafeField.setAccessible(true);
        return (sun.misc.Unsafe) unsafeField.get(null);
    } catch (SecurityException e) {
        throw new RuntimeException("Could not access the unsafe handle.", e);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException("The static unsafe handle field was not be found.");
    } catch (IllegalArgumentException e) {
        throw new RuntimeException("Bug: Illegal argument reflection access for static field.");
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Access to the unsafe handle is forbidden by the runtime.", e);
    }
}
Example 19
Project: Voovan-master  File: TUnsafe.java View source code
public static Unsafe getUnsafe() {
    if (unsafe == null) {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe) field.get(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return unsafe;
}
Example 20
Project: beanpath-master  File: StolenUnsafe.java View source code
private static Unsafe steal() {
    try {
        final Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafeField.setAccessible(true);
        try {
            return (Unsafe) theUnsafeField.get(null);
        } finally {
            theUnsafeField.setAccessible(false);
        }
    } catch (Exception x) {
        throw new RuntimeException("Failed to steal sun.misc.Unsafe via reflection", x);
    }
}
Example 21
Project: ef-orm-master  File: UnsafeUtils.java View source code
/**
	 * 用指定的ClassLoader加载二进制数�为class
	 * @param className
	 * @param data
	 * @param i
	 * @param length
	 * @param classLoader
	 * @return
	 */
public static final Class<?> defineClass(String className, byte[] data, int i, int length, ClassLoader classLoader) {
    if (data == null || data.length == 0) {
        throw new IllegalArgumentException("the input class data is empty!");
    }
    if (length < 1 || i + length < data.length) {
        throw new IllegalArgumentException("the input length is invalid!");
    }
    if (className == null || className.length() == 0) {
        throw new IllegalArgumentException("the class name is invalid!" + className);
    }
    Assert.notNull(classLoader);
    //		LogUtil.debug("Unsafe load class ["+className+"] to "+classLoader);
    return unsafe.defineClass(className, data, i, length, classLoader, null);
}
Example 22
Project: jvstm-master  File: UtilUnsafe.java View source code
@SuppressWarnings("unchecked")
private static <UNSAFE> UNSAFE getUnsafe() {
    Object theUnsafe = null;
    Exception exception = null;
    try {
        Class<?> uc = Class.forName("sun.misc.Unsafe");
        Field f = uc.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        theUnsafe = f.get(uc);
    } catch (Exception e) {
        exception = e;
    }
    if (theUnsafe == null)
        throw new Error("Could not obtain access to sun.misc.Unsafe", exception);
    return (UNSAFE) theUnsafe;
}
Example 23
Project: infinispan-master  File: UnsafeHolder.java View source code
@SuppressWarnings("restriction")
private static Unsafe getUnsafe() {
    // attempt to access field Unsafe#theUnsafe
    final Object maybeUnsafe = AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
        try {
            final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
            unsafeField.setAccessible(true);
            return unsafeField.get(null);
        } catch (NoSuchFieldExceptionSecurityException | IllegalAccessException |  e) {
            return e;
        }
    });
    if (maybeUnsafe instanceof Exception) {
        throw new CacheException((Exception) maybeUnsafe);
    } else {
        return (Unsafe) maybeUnsafe;
    }
}
Example 24
Project: jersey-master  File: UnsafeAccessor.java View source code
static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException tryReflectionInstead) {
    }
    try {
        return java.security.AccessController.doPrivileged((PrivilegedExceptionAction<Unsafe>) () -> {
            Class<Unsafe> k = Unsafe.class;
            for (Field f : k.getDeclaredFields()) {
                f.setAccessible(true);
                Object x = f.get(null);
                if (k.isInstance(x)) {
                    return k.cast(x);
                }
            }
            throw new NoSuchFieldError("the Unsafe");
        });
    } catch (java.security.PrivilegedActionException e) {
        throw new RuntimeException("Could not initialize intrinsics", e.getCause());
    }
}
Example 25
Project: hbase-master  File: UnsafeAvailChecker.java View source code
@Override
public Boolean run() {
    try {
        Class<?> clazz = Class.forName(CLASS_NAME);
        Field f = clazz.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        return f.get(null) != null;
    } catch (Throwable e) {
        LOG.warn("sun.misc.Unsafe is not available/accessible", e);
    }
    return false;
}
Example 26
Project: ehcache3-master  File: JSR166Helper.java View source code
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 27
Project: rubah-master  File: UnsafeRewritter.java View source code
@Override
protected void setTranslations() {
    Type rubahType = Type.getType(Rubah.class);
    Type objectType = Type.getType(Object.class);
    Type unsafeType = Type.getType(Unsafe.class);
    this.translations.put(new MethodInvocation(unsafeType, "getObject", objectType, objectType, Type.LONG_TYPE), new MethodInvocation(rubahType, "getObject", objectType, unsafeType, objectType, Type.LONG_TYPE).setOpcode(INVOKESTATIC));
    this.translations.put(new MethodInvocation(unsafeType, "getObjectVolatile", objectType, objectType, Type.LONG_TYPE), new MethodInvocation(rubahType, "getObjectVolatile", objectType, unsafeType, objectType, Type.LONG_TYPE).setOpcode(INVOKESTATIC));
}
Example 28
Project: Tank-master  File: SummaryReportObserverTest.java View source code
/**
     * Run the void observerJobEvents(JobEvent) method test.
     *
     * @throws Exception
     *
     * @generatedBy CodePro at 12/15/14 3:52 PM
     */
@Test
public void testObserverJobEvents_1() throws Exception {
    SummaryReportObserver fixture = new SummaryReportObserver();
    JobEvent jobEvent = new JobEvent("", "", JobLifecycleEvent.AGENT_EXCESSIVE_CPU);
    fixture.observerJobEvents(jobEvent);
// An unexpected exception was thrown in user code while executing this test:
//    java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
//       at com.intuit.tank.api.enumerated.JobLifecycleEvent.<init>(JobLifecycleEvent.java:43)
//       at com.intuit.tank.api.enumerated.JobLifecycleEvent.<clinit>(JobLifecycleEvent.java:14)
//       at sun.misc.Unsafe.ensureClassInitialized(Native Method)
}
Example 29
Project: arquillian-extension-drone-master  File: TestAugmentingEnhancer.java View source code
@Test
public void testCanEnhance() throws Exception {
    Unsafe unsafe = new Unsafe();
    RemoteWebDriver remoteDriver = unsafe.createInstanceWithoutInvokingConstructor(RemoteWebDriver.class);
    RemoteWebDriver reusableRemoteDriver = mock(ReusableRemoteWebDriver.class);
    DroneAugmented augmentedDriver = mock(DroneAugmented.class);
    InstanceOrCallableInstance instance1 = mock(InstanceOrCallableInstance.class);
    InstanceOrCallableInstance instance2 = mock(InstanceOrCallableInstance.class);
    InstanceOrCallableInstance instance3 = mock(InstanceOrCallableInstance.class);
    InstanceOrCallableInstance instance4 = mock(InstanceOrCallableInstance.class);
    doReturn(remoteDriver).when(instance1).asInstance(RemoteWebDriver.class);
    doReturn(remoteDriver).when(instance1).asInstance(WebDriver.class);
    doReturn(augmentedDriver).when(instance1).asInstance(ReusableRemoteWebDriver.class);
    doReturn(unsafe.createInstanceWithoutInvokingConstructor(FirefoxDriver.class)).when(instance2).asInstance(WebDriver.class);
    doReturn(reusableRemoteDriver).when(instance3).asInstance(WebDriver.class);
    doReturn(augmentedDriver).when(instance4).asInstance(WebDriver.class);
    assertTrue("AugmentingEnhancer should enhance when droneType == RemoteWebDriver.class", enhancer.canEnhance(instance1, RemoteWebDriver.class, Default.class));
    assertTrue("AugmentingEnhancer should enhance when droneType == ReusableRemoteWebDriver.class", enhancer.canEnhance(instance1, ReusableRemoteWebDriver.class, Default.class));
    assertTrue("AugmentingEnhancer should enhance when real instance is RemoteWebDriver", enhancer.canEnhance(instance1, WebDriver.class, Default.class));
    assertTrue("AugmentingEnhancer should enhance when real instance already augmented!", enhancer.canEnhance(instance4, WebDriver.class, Default.class));
    assertFalse("AugmentingEnhancer should not enhance when real instance is not RemoteWebDriver || ReusableRemoteWebDriver", enhancer.canEnhance(instance2, WebDriver.class, Default.class));
    assertFalse("AugmentingEnhancer should not enhance extensions of supported classes!", enhancer.canEnhance(instance3, WebDriver.class, Default.class));
}
Example 30
Project: guava-master  File: UnsignedBytes.java View source code
@Override
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x)) {
            return k.cast(x);
        }
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 31
Project: netty-learning-master  File: DetectionUtil.java View source code
private static boolean hasUnsafe(ClassLoader loader) {
    boolean noUnsafe = SystemPropertyUtil.getBoolean("io.netty.noUnsafe", false);
    if (noUnsafe) {
        return false;
    }
    // Legacy properties
    boolean tryUnsafe;
    if (SystemPropertyUtil.contains("io.netty.tryUnsafe")) {
        tryUnsafe = SystemPropertyUtil.getBoolean("io.netty.tryUnsafe", true);
    } else {
        tryUnsafe = SystemPropertyUtil.getBoolean("org.jboss.netty.tryUnsafe", true);
    }
    if (!tryUnsafe) {
        return false;
    }
    try {
        Class<?> unsafeClazz = Class.forName("sun.misc.Unsafe", true, loader);
        return hasUnsafeField(unsafeClazz);
    } catch (Exception e) {
    }
    return false;
}
Example 32
Project: netty3.9-note-master  File: DetectionUtil.java View source code
private static boolean hasUnsafe(ClassLoader loader) {
    boolean noUnsafe = SystemPropertyUtil.getBoolean("io.netty.noUnsafe", false);
    if (noUnsafe) {
        return false;
    }
    // Legacy properties
    boolean tryUnsafe;
    if (SystemPropertyUtil.contains("io.netty.tryUnsafe")) {
        tryUnsafe = SystemPropertyUtil.getBoolean("io.netty.tryUnsafe", true);
    } else {
        tryUnsafe = SystemPropertyUtil.getBoolean("org.jboss.netty.tryUnsafe", true);
    }
    if (!tryUnsafe) {
        return false;
    }
    try {
        Class<?> unsafeClazz = Class.forName("sun.misc.Unsafe", true, loader);
        return hasUnsafeField(unsafeClazz);
    } catch (Exception e) {
    }
    return false;
}
Example 33
Project: simple-netty-source-master  File: DetectionUtil.java View source code
private static boolean hasUnsafe(ClassLoader loader) {
    boolean noUnsafe = SystemPropertyUtil.getBoolean("io.netty.noUnsafe", false);
    if (noUnsafe) {
        return false;
    }
    // Legacy properties
    boolean tryUnsafe;
    if (SystemPropertyUtil.contains("io.netty.tryUnsafe")) {
        tryUnsafe = SystemPropertyUtil.getBoolean("io.netty.tryUnsafe", true);
    } else {
        tryUnsafe = SystemPropertyUtil.getBoolean("org.jboss.netty.tryUnsafe", true);
    }
    if (!tryUnsafe) {
        return false;
    }
    try {
        Class<?> unsafeClazz = Class.forName("sun.misc.Unsafe", true, loader);
        return hasUnsafeField(unsafeClazz);
    } catch (Exception e) {
    }
    return false;
}
Example 34
Project: streamline-master  File: DetectionUtil.java View source code
private static boolean hasUnsafe(ClassLoader loader) {
    boolean useUnsafe = Boolean.valueOf(SystemPropertyUtil.get("org.jboss.netty.tryUnsafe", "true"));
    if (!useUnsafe) {
        return false;
    }
    try {
        Class<?> unsafeClazz = Class.forName("sun.misc.Unsafe", true, loader);
        return hasUnsafeField(unsafeClazz);
    } catch (Exception e) {
    }
    return false;
}
Example 35
Project: haze-master  File: UnsafeHelper.java View source code
static Unsafe findUnsafeIfAllowed() {
    if (isUnsafeExplicitlyDisabled()) {
        Logger.getLogger(UnsafeHelper.class).warning(UNSAFE_WARNING_WHEN_EXPLICTLY_DISABLED);
        return null;
    }
    if (!isUnalignedAccessAllowed()) {
        if (isUnsafeExplicitlyEnforced()) {
            Logger.getLogger(UnsafeHelper.class).warning(UNSAFE_WARNING_WHEN_ENFORCED_ON_PLATFORM_WHERE_NOT_SUPPORTED);
        } else {
            Logger.getLogger(UnsafeHelper.class).warning(UNSAFE_WARNING_WHEN_UNALIGNED_ACCESS_NOT_ALLOWED);
            return null;
        }
    }
    Unsafe unsafe = findUnsafe();
    if (unsafe == null) {
        Logger.getLogger(UnsafeHelper.class).warning(UNSAFE_WARNING_WHEN_NOT_FOUND);
    }
    return unsafe;
}
Example 36
Project: hazelcast-master  File: UnsafeHelper.java View source code
static Unsafe findUnsafeIfAllowed() {
    if (isUnsafeExplicitlyDisabled()) {
        Logger.getLogger(UnsafeHelper.class).warning(UNSAFE_WARNING_WHEN_EXPLICTLY_DISABLED);
        return null;
    }
    if (!isUnalignedAccessAllowed()) {
        if (isUnsafeExplicitlyEnforced()) {
            Logger.getLogger(UnsafeHelper.class).warning(UNSAFE_WARNING_WHEN_ENFORCED_ON_PLATFORM_WHERE_NOT_SUPPORTED);
        } else {
            Logger.getLogger(UnsafeHelper.class).warning(UNSAFE_WARNING_WHEN_UNALIGNED_ACCESS_NOT_ALLOWED);
            return null;
        }
    }
    Unsafe unsafe = findUnsafe();
    if (unsafe == null) {
        Logger.getLogger(UnsafeHelper.class).warning(UNSAFE_WARNING_WHEN_NOT_FOUND);
    }
    return unsafe;
}
Example 37
Project: java-sizeof-master  File: BlackMagic.java View source code
/**
   * Returns Unsafe if available or throw a RuntimeException.
   */
public static sun.misc.Unsafe getUnsafe() {
    try {
        final Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
        final Field unsafeField = unsafeClass.getDeclaredField("theUnsafe");
        unsafeField.setAccessible(true);
        return (sun.misc.Unsafe) unsafeField.get(null);
    } catch (Throwable t) {
        throw new RuntimeException("Unsafe not available.", t);
    }
}
Example 38
Project: guava-libraries-master  File: Striped64.java View source code
/**
     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
     * Replace with a simple call to Unsafe.getUnsafe when integrating
     * into a jdk.
     *
     * @return a sun.misc.Unsafe
     */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

                public sun.misc.Unsafe run() throws Exception {
                    java.lang.reflect.Field f;
                    try {
                        f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
                    } catch (NoSuchFieldException e) {
                        f = sun.misc.Unsafe.class.getDeclaredField("THE_ONE");
                    }
                    f.setAccessible(true);
                    return (sun.misc.Unsafe) f.get(null);
                }
            });
        } catch (java.security.PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics", e.getCause());
        }
    }
}
Example 39
Project: caffeine-master  File: UnsafeAccess.java View source code
static Unsafe load(String openJdk, String android) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    Field field;
    try {
        // try OpenJDK field name
        field = Unsafe.class.getDeclaredField(openJdk);
    } catch (NoSuchFieldException e) {
        try {
            field = Unsafe.class.getDeclaredField(android);
        } catch (NoSuchFieldException e2) {
            Constructor<Unsafe> unsafeConstructor = Unsafe.class.getDeclaredConstructor();
            unsafeConstructor.setAccessible(true);
            return unsafeConstructor.newInstance();
        }
    }
    field.setAccessible(true);
    return (Unsafe) field.get(null);
}
Example 40
Project: ceylon-compiler-master  File: T6873845.java View source code
public void run() throws Exception {
    String out = compile(Arrays.asList("-XDrawDiagnostics", "-X"));
    if (out.contains("sunapi"))
        throw new Exception("unexpected output for -X");
    String warn1 = "T6873845.java:72:9: compiler.warn.sun.proprietary: sun.misc.Unsafe" + newline;
    String warn2 = "T6873845.java:77:9: compiler.warn.sun.proprietary: sun.misc.Unsafe" + newline;
    String note1 = "- compiler.note.sunapi.filename: T6873845.java" + newline;
    String note2 = "- compiler.note.sunapi.recompile" + newline;
    test(opts(), warn1 + warn2 + "2 warnings" + newline);
    test(opts("-XDenableSunApiLintControl"), note1 + note2);
    test(opts("-XDenableSunApiLintControl", "-XDsuppressNotes"), "");
    test(opts("-XDenableSunApiLintControl", "-Xlint:sunapi"), warn1 + "1 warning" + newline);
    test(opts("-XDenableSunApiLintControl", "-Xlint:all"), warn1 + "1 warning" + newline);
    test(opts("-XDenableSunApiLintControl", "-Xlint:all,-sunapi"), note1 + note2);
}
Example 41
Project: Funcheck-master  File: T6873845.java View source code
public void run() throws Exception {
    String out = compile(Arrays.asList("-XDrawDiagnostics", "-X"));
    if (out.contains("sunapi"))
        throw new Exception("unexpected output for -X");
    String warn1 = "T6873845.java:72:9: compiler.warn.sun.proprietary: sun.misc.Unsafe" + newline;
    String warn2 = "T6873845.java:77:9: compiler.warn.sun.proprietary: sun.misc.Unsafe" + newline;
    String note1 = "- compiler.note.sunapi.filename: T6873845.java" + newline;
    String note2 = "- compiler.note.sunapi.recompile" + newline;
    test(opts(), warn1 + warn2 + "2 warnings" + newline);
    test(opts("-XDenableSunApiLintControl"), note1 + note2);
    test(opts("-XDenableSunApiLintControl", "-XDsuppressNotes"), "");
    test(opts("-XDenableSunApiLintControl", "-Xlint:sunapi"), warn1 + "1 warning" + newline);
    test(opts("-XDenableSunApiLintControl", "-Xlint:all"), warn1 + "1 warning" + newline);
    test(opts("-XDenableSunApiLintControl", "-Xlint:all,-sunapi"), note1 + note2);
}
Example 42
Project: javappp-master  File: T6873845.java View source code
public void run() throws Exception {
    String out = compile(Arrays.asList("-XDrawDiagnostics", "-X"));
    if (out.contains("sunapi"))
        throw new Exception("unexpected output for -X");
    String warn1 = "T6873845.java:72:9: compiler.warn.sun.proprietary: sun.misc.Unsafe" + newline;
    String warn2 = "T6873845.java:77:9: compiler.warn.sun.proprietary: sun.misc.Unsafe" + newline;
    String note1 = "- compiler.note.sunapi.filename: T6873845.java" + newline;
    String note2 = "- compiler.note.sunapi.recompile" + newline;
    test(opts(), warn1 + warn2 + "2 warnings" + newline);
    test(opts("-XDenableSunApiLintControl"), note1 + note2);
    test(opts("-XDenableSunApiLintControl", "-XDsuppressNotes"), "");
    test(opts("-XDenableSunApiLintControl", "-Xlint:sunapi"), warn1 + "1 warning" + newline);
    test(opts("-XDenableSunApiLintControl", "-Xlint:all"), warn1 + "1 warning" + newline);
    test(opts("-XDenableSunApiLintControl", "-Xlint:all,-sunapi"), note1 + note2);
}
Example 43
Project: jdk7u-langtools-master  File: T6873845.java View source code
public void run() throws Exception {
    String out = compile(Arrays.asList("-XDrawDiagnostics", "-X"));
    if (out.contains("sunapi"))
        throw new Exception("unexpected output for -X");
    String warn1 = "T6873845.java:72:9: compiler.warn.sun.proprietary: sun.misc.Unsafe" + newline;
    String warn2 = "T6873845.java:77:9: compiler.warn.sun.proprietary: sun.misc.Unsafe" + newline;
    String note1 = "- compiler.note.sunapi.filename: T6873845.java" + newline;
    String note2 = "- compiler.note.sunapi.recompile" + newline;
    test(opts(), warn1 + warn2 + "2 warnings" + newline);
    test(opts("-XDenableSunApiLintControl"), note1 + note2);
    test(opts("-XDenableSunApiLintControl", "-XDsuppressNotes"), "");
    test(opts("-XDenableSunApiLintControl", "-Xlint:sunapi"), warn1 + "1 warning" + newline);
    test(opts("-XDenableSunApiLintControl", "-Xlint:all"), warn1 + "1 warning" + newline);
    test(opts("-XDenableSunApiLintControl", "-Xlint:all,-sunapi"), note1 + note2);
}
Example 44
Project: jsr308-langtools-master  File: T6873845.java View source code
public void run() throws Exception {
    String out = compile(Arrays.asList("-XDrawDiagnostics", "-X"));
    if (out.contains("sunapi"))
        throw new Exception("unexpected output for -X");
    String warn1 = "T6873845.java:73:9: compiler.warn.sun.proprietary: sun.misc.Unsafe" + newline;
    String warn2 = "T6873845.java:78:9: compiler.warn.sun.proprietary: sun.misc.Unsafe" + newline;
    String note1 = "- compiler.note.sunapi.filename: T6873845.java" + newline;
    String note2 = "- compiler.note.sunapi.recompile" + newline;
    test(opts(), warn1 + warn2 + "2 warnings" + newline);
    test(opts("-XDenableSunApiLintControl"), note1 + note2);
    test(opts("-XDenableSunApiLintControl", "-XDsuppressNotes"), "");
    test(opts("-XDenableSunApiLintControl", "-Xlint:sunapi"), warn1 + "1 warning" + newline);
    test(opts("-XDenableSunApiLintControl", "-Xlint:all"), warn1 + "1 warning" + newline);
    test(opts("-XDenableSunApiLintControl", "-Xlint:all,-sunapi"), note1 + note2);
}
Example 45
Project: OpenJML-master  File: T6873845.java View source code
public void run() throws Exception {
    String out = compile(Arrays.asList("-XDrawDiagnostics", "-X"));
    if (out.contains("sunapi"))
        throw new Exception("unexpected output for -X");
    String warn1 = "T6873845.java:72:9: compiler.warn.sun.proprietary: sun.misc.Unsafe" + newline;
    String warn2 = "T6873845.java:77:9: compiler.warn.sun.proprietary: sun.misc.Unsafe" + newline;
    String note1 = "- compiler.note.sunapi.filename: T6873845.java" + newline;
    String note2 = "- compiler.note.sunapi.recompile" + newline;
    test(opts(), warn1 + warn2 + "2 warnings" + newline);
    test(opts("-XDenableSunApiLintControl"), note1 + note2);
    test(opts("-XDenableSunApiLintControl", "-XDsuppressNotes"), "");
    test(opts("-XDenableSunApiLintControl", "-Xlint:sunapi"), warn1 + "1 warning" + newline);
    test(opts("-XDenableSunApiLintControl", "-Xlint:all"), warn1 + "1 warning" + newline);
    test(opts("-XDenableSunApiLintControl", "-Xlint:all,-sunapi"), note1 + note2);
}
Example 46
Project: tengi-master  File: UnsafeUtil.java View source code
@Override
public Unsafe run() {
    try {
        Class<Unsafe> type = Unsafe.class;
        try {
            Field field = type.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            return type.cast(field.get(type));
        } catch (Exception e) {
            for (Field field : type.getDeclaredFields()) {
                if (type.isAssignableFrom(field.getType())) {
                    field.setAccessible(true);
                    return type.cast(field.get(type));
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Unsafe unavailable", e);
    }
    throw new RuntimeException("Unsafe unavailable");
}
Example 47
Project: hugecast-master  File: PlatformDependent.java View source code
private static boolean hasUnsafe0() {
    boolean noUnsafe = SystemPropertyUtil.getBoolean("io.netty.noUnsafe", false);
    if (logger.isFinestEnabled()) {
        logger.finest("-Dio.netty.noUnsafe: " + noUnsafe);
    }
    if (noUnsafe) {
        logger.finest("sun.misc.Unsafe: unavailable (io.netty.noUnsafe)");
        return false;
    }
    // Legacy properties
    boolean tryUnsafe;
    if (SystemPropertyUtil.contains("io.netty.tryUnsafe")) {
        tryUnsafe = SystemPropertyUtil.getBoolean("io.netty.tryUnsafe", true);
    } else {
        tryUnsafe = SystemPropertyUtil.getBoolean("org.jboss.netty.tryUnsafe", true);
    }
    if (!tryUnsafe) {
        logger.finest("sun.misc.Unsafe: unavailable (io.netty.tryUnsafe/org.jboss.netty.tryUnsafe)");
        return false;
    }
    try {
        boolean hasUnsafe = PlatformDependent0.hasUnsafe();
        if (logger.isFinestEnabled()) {
            logger.finest("sun.misc.Unsafe: " + (hasUnsafe ? "available" : "unavailable"));
        }
        return hasUnsafe;
    } catch (Throwable t) {
        return false;
    }
}
Example 48
Project: asynchbase-master  File: Striped64.java View source code
/**
     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
     * Replace with a simple call to Unsafe.getUnsafe when integrating
     * into a jdk.
     *
     * @return a sun.misc.Unsafe
     */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

                public sun.misc.Unsafe run() throws Exception {
                    java.lang.reflect.Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
                    f.setAccessible(true);
                    return (sun.misc.Unsafe) f.get(null);
                }
            });
        } catch (java.security.PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics", e.getCause());
        }
    }
}
Example 49
Project: cloudtm-data-platform-master  File: Striped64.java View source code
/**
    * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
    * Replace with a simple call to Unsafe.getUnsafe when integrating
    * into a jdk.
    *
    * @return a sun.misc.Unsafe
    */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

                @Override
                public sun.misc.Unsafe run() throws Exception {
                    java.lang.reflect.Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
                    f.setAccessible(true);
                    return (sun.misc.Unsafe) f.get(null);
                }
            });
        } catch (java.security.PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics", e.getCause());
        }
    }
}
Example 50
Project: gocd-master  File: Striped64.java View source code
/**
     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
     * Replace with a simple call to Unsafe.getUnsafe when integrating
     * into a jdk.
     *
     * @return a sun.misc.Unsafe
     */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

                public sun.misc.Unsafe run() throws Exception {
                    java.lang.reflect.Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
                    f.setAccessible(true);
                    return (sun.misc.Unsafe) f.get(null);
                }
            });
        } catch (java.security.PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics", e.getCause());
        }
    }
}
Example 51
Project: guava-experimental-master  File: Striped64.java View source code
/**
     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
     * Replace with a simple call to Unsafe.getUnsafe when integrating
     * into a jdk.
     *
     * @return a sun.misc.Unsafe
     */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

                public sun.misc.Unsafe run() throws Exception {
                    java.lang.reflect.Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
                    f.setAccessible(true);
                    return (sun.misc.Unsafe) f.get(null);
                }
            });
        } catch (java.security.PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics", e.getCause());
        }
    }
}
Example 52
Project: Hystrix-master  File: Striped64.java View source code
/**
     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
     * Replace with a simple call to Unsafe.getUnsafe when integrating
     * into a jdk.
     *
     * @return a sun.misc.Unsafe
     */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

                public sun.misc.Unsafe run() throws Exception {
                    java.lang.reflect.Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
                    f.setAccessible(true);
                    return (sun.misc.Unsafe) f.get(null);
                }
            });
        } catch (java.security.PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics", e.getCause());
        }
    }
}
Example 53
Project: ignite-master  File: Striped64_8.java View source code
/**
     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
     * Replace with a simple call to Unsafe.getUnsafe when integrating
     * into a jdk.
     *
     * @return a sun.misc.Unsafe
     */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

                public sun.misc.Unsafe run() throws Exception {
                    java.lang.reflect.Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
                    f.setAccessible(true);
                    return (sun.misc.Unsafe) f.get(null);
                }
            });
        } catch (java.security.PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics", e.getCause());
        }
    }
}
Example 54
Project: instrumentation-master  File: Striped64.java View source code
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 55
Project: janusproject-master  File: UnsignedBytes.java View source code
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 56
Project: jnlp-master  File: UnsignedBytes.java View source code
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 57
Project: jst-master  File: Striped64.java View source code
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 58
Project: jstorm-master  File: Striped64.java View source code
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 59
Project: light-4j-master  File: UnsafeStriped64.java View source code
@Override
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 60
Project: mango-master  File: Striped64.java View source code
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 61
Project: metr-master  File: UnsafeStriped64.java View source code
@Override
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 62
Project: metric-master  File: UnsafeStriped64.java View source code
@Override
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 63
Project: metrics-master  File: UnsafeStriped64.java View source code
@Override
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 64
Project: monitoring-master  File: Striped64.java View source code
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 65
Project: netty4study-master  File: Striped64.java View source code
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 66
Project: org.openntf.domino-master  File: UnsignedBytes.java View source code
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 67
Project: pinpoint-master  File: Striped64.java View source code
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 68
Project: reactive-audit-master  File: Striped64.java View source code
@Override
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 69
Project: seeds-libraries-master  File: UnsignedBytes.java View source code
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 70
Project: Springs-master  File: Striped64.java View source code
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 71
Project: springside4-master  File: Striped64.java View source code
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x))
            return k.cast(x);
    }
    throw new NoSuchFieldError("the Unsafe");
}
Example 72
Project: thread_safe-master  File: Striped64.java View source code
/**
     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
     * Replace with a simple call to Unsafe.getUnsafe when integrating
     * into a jdk.
     *
     * @return a sun.misc.Unsafe
     */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

                public sun.misc.Unsafe run() throws Exception {
                    java.lang.reflect.Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
                    f.setAccessible(true);
                    return (sun.misc.Unsafe) f.get(null);
                }
            });
        } catch (java.security.PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics", e.getCause());
        }
    }
}
Example 73
Project: bazel-master  File: UnsafeUtil.java View source code
@Override
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x)) {
            return k.cast(x);
        }
    }
    // The sun.misc.Unsafe field does not exist.
    return null;
}
Example 74
Project: Correct-master  File: UnsafeUtil.java View source code
@Override
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x)) {
            return k.cast(x);
        }
    }
    // The sun.misc.Unsafe field does not exist.
    return null;
}
Example 75
Project: test-master  File: UnsafeUtil.java View source code
@Override
public sun.misc.Unsafe run() throws Exception {
    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
    for (Field f : k.getDeclaredFields()) {
        f.setAccessible(true);
        Object x = f.get(null);
        if (k.isInstance(x)) {
            return k.cast(x);
        }
    }
    // The sun.misc.Unsafe field does not exist.
    return null;
}
Example 76
Project: mapdb-master  File: UnsafeVolume.java View source code
@SuppressWarnings("restriction")
private static sun.misc.Unsafe getUnsafe() {
    if (ByteOrder.nativeOrder() != ByteOrder.LITTLE_ENDIAN) {
        LOG.log(Level.WARNING, "This is not Little Endian platform. Unsafe optimizations are disabled.");
        return null;
    }
    try {
        java.lang.reflect.Field singleoneInstanceField = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
        singleoneInstanceField.setAccessible(true);
        sun.misc.Unsafe ret = (sun.misc.Unsafe) singleoneInstanceField.get(null);
        return ret;
    } catch (Throwable e) {
        LOG.log(Level.WARNING, "Could not instantiate sun.misc.Unsafe. Fall back to DirectByteBuffer and other alternatives.", e);
        return null;
    }
}
Example 77
Project: amza-master  File: KeyUtil.java View source code
/**
             * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
             * Replace with a simple call to Unsafe.getUnsafe when integrating
             * into a jdk.
             *
             * @return a sun.misc.Unsafe
             */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException tryReflectionInstead) {
    }
    try {
        return java.security.AccessController.doPrivileged((java.security.PrivilegedExceptionAction<Unsafe>) () -> {
            Class<Unsafe> k = Unsafe.class;
            for (java.lang.reflect.Field f : k.getDeclaredFields()) {
                f.setAccessible(true);
                Object x = f.get(null);
                if (k.isInstance(x)) {
                    return k.cast(x);
                }
            }
            throw new NoSuchFieldError("the Unsafe");
        });
    } catch (java.security.PrivilegedActionException e) {
        throw new RuntimeException("Could not initialize intrinsics", e.getCause());
    }
}
Example 78
Project: hasor-master  File: Accessors.java View source code
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (Exception e) {
    }
    try {
        Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
        for (Field f : k.getDeclaredFields()) {
            f.setAccessible(true);
            Object x = f.get(null);
            if (k.isInstance(x))
                return k.cast(x);
        }
        return null;
    } catch (Exception e) {
        return null;
    }
}
Example 79
Project: hprose-java-master  File: Accessors.java View source code
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (Exception e) {
    }
    try {
        Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
        for (Field f : k.getDeclaredFields()) {
            f.setAccessible(true);
            Object x = f.get(null);
            if (k.isInstance(x))
                return k.cast(x);
        }
        return null;
    } catch (Exception e) {
        return null;
    }
}
Example 80
Project: incubator-twill-master  File: Instances.java View source code
/**
   * Creates a new instance of the given class. It will use the default constructor if it is presents.
   * Otherwise it will try to use {@link sun.misc.Unsafe#allocateInstance(Class)} to create the instance.
   * @param clz Class of object to be instantiated.
   * @param <T> Type of the class
   * @return An instance of type {@code <T>}
   */
@SuppressWarnings("unchecked")
public static <T> T newInstance(Class<T> clz) {
    try {
        try {
            Constructor<T> cons = clz.getDeclaredConstructor();
            if (!cons.isAccessible()) {
                cons.setAccessible(true);
            }
            return cons.newInstance();
        } catch (Exception e) {
            Preconditions.checkState(UNSAFE != null, "Fail to instantiate with Unsafe.");
            return unsafeCreate(clz);
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}
Example 81
Project: intellij-community-master  File: DirectBufferWrapper.java View source code
@ReviseWhenPortedToJDK("9")
static // return true if successful
boolean disposeDirectBuffer(final ByteBuffer buffer) {
    if (!(buffer instanceof DirectBuffer))
        return true;
    if (SystemInfo.IS_AT_LEAST_JAVA9) {
        // in JDK9 the "official" dispose method is sun.misc.Unsafe#invokeCleaner
        // since we have to target both jdk 8 and 9 we have to use reflection
        Unsafe unsafe = AtomicFieldUpdater.getUnsafe();
        try {
            Method invokeCleaner = unsafe.getClass().getMethod("invokeCleaner", ByteBuffer.class);
            invokeCleaner.setAccessible(true);
            invokeCleaner.invoke(unsafe, buffer);
            return true;
        } catch (Exception e) {
            LOG.error(e);
            throw new RuntimeException(e);
        }
    }
    try {
        Cleaner cleaner = ((DirectBuffer) buffer).cleaner();
        // Already cleaned otherwise
        if (cleaner != null)
            cleaner.clean();
        return true;
    } catch (Throwable e) {
        return false;
    }
}
Example 82
Project: nextprot-api-master  File: ExperimentalContextDictAnalyserApp.java View source code
@Override
protected void execute() throws IOException {
    ExperimentalContextDictionaryService bean = getBean(ExperimentalContextDictionaryService.class);
    Map<Long, ExperimentalContext> dict = bean.getAllExperimentalContexts();
    /* If instrumentation is available, use it, otherwise guess the size using sun.misc.Unsafe; if that is unavailable,
         * guess using predefined specifications -> setting jamm as -javaagent is now optional */
    MemoryMeter memMeter = new MemoryMeter().withGuessing(MemoryMeter.Guess.FALLBACK_BEST);
    if (getCommandLineParser().isDebugMode()) {
        memMeter = memMeter.enableDebug();
    }
    long shallowMemory = memMeter.measure(dict);
    long deepMemory = memMeter.measureDeep(dict);
    long childrenCount = memMeter.countChildren(dict);
    StringBuilder sb = new StringBuilder("experimental-context-dictionary memory allocation: ");
    sb.append("shallow=").append(shallowMemory).append("B").append(", deep=").append((int) Math.ceil(deepMemory / 1024.)).append("KB").append(", children#=").append(childrenCount).append("\n");
    System.out.printf(sb.toString());
}
Example 83
Project: es6draft-master  File: UnsafeHolder.java View source code
private static Unsafe initializeUnsafe() {
    try {
        return Unsafe.getUnsafe();
    } catch (SecurityException e) {
        try {
            return AccessController.doPrivileged((PrivilegedExceptionAction<Unsafe>) () -> {
                Field f = Unsafe.class.getDeclaredField("theUnsafe");
                f.setAccessible(true);
                return (Unsafe) f.get(null);
            });
        } catch (PrivilegedActionException e2) {
            throw new ExceptionInInitializerError(e2.getException());
        }
    }
}
Example 84
Project: graal-core-master  File: UnsafeAccess.java View source code
private static Unsafe initUnsafe() {
    try {
        // Fast path when we are trusted.
        return Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            return (Unsafe) theUnsafe.get(Unsafe.class);
        } catch (Exception e) {
            throw new RuntimeException("exception while trying to get Unsafe", e);
        }
    }
}
Example 85
Project: graal-master  File: UnsafeAccess.java View source code
private static Unsafe initUnsafe() {
    try {
        // Fast path when we are trusted.
        return Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            return (Unsafe) theUnsafe.get(Unsafe.class);
        } catch (Exception e) {
            throw new RuntimeException("exception while trying to get Unsafe", e);
        }
    }
}
Example 86
Project: incubator-hivemall-master  File: UnsafeUtils.java View source code
private static Unsafe _getUnsafe() {
    if (UnsafeUtils.class.getClassLoader() == null) {
        return Unsafe.getUnsafe();
    }
    try {
        final Field fld = Unsafe.class.getDeclaredField("theUnsafe");
        fld.setAccessible(true);
        return (Unsafe) fld.get(UnsafeUtils.class);
    } catch (Exception e) {
        return null;
    }
}
Example 87
Project: j2objc-master  File: UnsafeTest.java View source code
public void testAllocInstance() {
    Unsafe unsafe = Unsafe.getUnsafe();
    Object o = unsafe.allocateInstance(UnsafeTest.class);
    assertTrue(o instanceof UnsafeTest);
    try {
        o = unsafe.allocateInstance(AbstractTestClass.class);
        fail("abstract class instantiated");
    } catch (Exception e) {
        assertTrue(e instanceof InstantiationException);
    }
    try {
        o = unsafe.allocateInstance(TestEnum.class);
        fail("enum instantiated");
    } catch (Exception e) {
        assertTrue(e instanceof InstantiationException);
    }
    try {
        o = unsafe.allocateInstance(TestInterface.class);
        fail("interface class instantiated");
    } catch (Exception e) {
        assertTrue(e instanceof InstantiationException);
    }
    try {
        int[] array = new int[0];
        o = unsafe.allocateInstance(array.getClass());
        fail("array class instantiated");
    } catch (Exception e) {
        assertTrue(e instanceof InstantiationException);
    }
}
Example 88
Project: JCGO-master  File: TrigCompileAllVmClasses.java View source code
static void main(String[] args) throws Throwable {
    if (args == null)
        return;
    "".intern();
    new java.lang.ref.SoftReference("");
    new java.util.Date();
    new java.io.File("!").deleteOnExit();
    java.nio.ByteBuffer.allocateDirect(1);
    // throws IndexOutOfBoundsException
    Runtime.getRuntime().exec("");
    Runtime.runFinalizersOnExit(true);
    Compiler.command("");
    new java.net.Socket("", 0);
    java.lang.reflect.Array.newInstance(byte.class, 0);
    Thread.class.getDeclaredFields();
    java.lang.reflect.Proxy.getProxyClass(Object[][].class.getClassLoader(), new Class[] { Runnable.class });
    ManagementFactory.getClassLoadingMXBean().isVerbose();
    ManagementFactory.getCompilationMXBean().getTotalCompilationTime();
    ManagementFactory.getMemoryMXBean().setVerbose(false);
    ManagementFactory.getRuntimeMXBean().getInputArguments();
    ManagementFactory.getThreadMXBean().getThreadCpuTime(0);
    ((GarbageCollectorMXBean) ManagementFactory.getGarbageCollectorMXBeans().get(0)).getCollectionCount();
    ((MemoryManagerMXBean) ManagementFactory.getMemoryManagerMXBeans().get(0)).isValid();
    ((MemoryPoolMXBean) ManagementFactory.getMemoryPoolMXBeans().get(0)).getCollectionUsageThreshold();
    Math.IEEEremainder(0, 0);
    Math.acos(0);
    Math.asin(0);
    Math.atan2(0, 0);
    Math.atan(0);
    Math.cbrt(0);
    Math.ceil(0);
    Math.cos(0);
    Math.cosh(0);
    Math.exp(0);
    Math.expm1(0);
    Math.floor(0);
    Math.hypot(0, 0);
    Math.log10(0);
    Math.log1p(0);
    Math.log(0);
    Math.pow(0, 0);
    Math.rint(0);
    Math.sin(0);
    Math.sinh(0);
    Math.sqrt(0);
    Math.tan(0);
    Math.tanh(0);
    Class.forName("java.lang.VMClassLoader$ClassParser");
    Class.forName("sun.misc.Unsafe").getMethod("getUnsafe", new Class[] {});
    Class.forName("gnu.java.lang.InstrumentationImpl").getMethod("getAllLoadedClasses", new Class[] {});
    Class.forName("gnu.java.lang.management.VMOperatingSystemMXBeanImpl").getMethod("getSystemLoadAverage", new Class[] {});
}
Example 89
Project: JCommon-master  File: TestUnsafeAccessor.java View source code
/**
   * allocates 1MB, write a bunch of bytes, reads them back, frees the memory
   * @throws Exception
   */
@Test(groups = "fast")
public void testSanity() throws Exception {
    Unsafe unsafe = UnsafeAccessor.get();
    int size = 1024 * 1024;
    long ptr = unsafe.allocateMemory(size);
    long writePtr = ptr;
    for (int i = 0; i < size; i++) {
        byte b = (byte) (i % 127);
        unsafe.putByte(writePtr, b);
        writePtr++;
    }
    long readPtr = ptr;
    for (int i = 0; i < size; i++) {
        byte b = (byte) (i % 127);
        byte readByte = unsafe.getByte(readPtr);
        readPtr++;
        Assert.assertEquals(b, readByte);
    }
    unsafe.freeMemory(ptr);
}
Example 90
Project: MCFreedomLauncher-master  File: UnsafeAllocator.java View source code
public static UnsafeAllocator create() {
    try {
        Class unsafeClass = Class.forName("sun.misc.Unsafe");
        Field f = unsafeClass.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        final Object unsafe = f.get(null);
        Method allocateInstance = unsafeClass.getMethod("allocateInstance", new Class[] { Class.class });
        return new UnsafeAllocator() {

            public <T> T newInstance(Class<T> c) throws Exception {
                return this.val$allocateInstance.invoke(unsafe, new Object[] { c });
            }
        };
    } catch (Exception ignored) {
        try {
            Method newInstance = ObjectInputStream.class.getDeclaredMethod("newInstance", new Class[] { Class.class, Class.class });
            newInstance.setAccessible(true);
            return new UnsafeAllocator() {

                public <T> T newInstance(Class<T> c) throws Exception {
                    return this.val$newInstance.invoke(null, new Object[] { c, Object.class });
                }
            };
        } catch (Exception ignored) {
            try {
                Method getConstructorId = ObjectStreamClass.class.getDeclaredMethod("getConstructorId", new Class[] { Class.class });
                getConstructorId.setAccessible(true);
                final int constructorId = ((Integer) getConstructorId.invoke(null, new Object[] { Object.class })).intValue();
                Method newInstance = ObjectStreamClass.class.getDeclaredMethod("newInstance", new Class[] { Class.class, Integer.TYPE });
                newInstance.setAccessible(true);
                return new UnsafeAllocator() {

                    public <T> T newInstance(Class<T> c) throws Exception {
                        return this.val$newInstance.invoke(null, new Object[] { c, Integer.valueOf(constructorId) });
                    }
                };
            } catch (Exception ignored) {
            }
        }
    }
    return new UnsafeAllocator() {

        public <T> T newInstance(Class<T> c) {
            throw new UnsupportedOperationException("Cannot allocate " + c);
        }
    };
}
Example 91
Project: MiBandDecompiled-master  File: UnsafeAllocator.java View source code
public static UnsafeAllocator create() {
    A a;
    try {
        Class class1 = Class.forName("sun.misc.Unsafe");
        Field field = class1.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        Object obj = field.get(null);
        a = new A(class1.getMethod("allocateInstance", new Class[] { java / lang / Class }), obj);
    } catch (Exception exception) {
        B b;
        try {
            Method method2 = java / io / ObjectInputStream.getDeclaredMethod("newInstance", new Class[] { java / lang / Class, java / lang / Class });
            method2.setAccessible(true);
            b = new B(method2);
        } catch (Exception exception1) {
            C c;
            try {
                Method method = java / io / ObjectStreamClass.getDeclaredMethod("getConstructorId", new Class[] { java / lang / Class });
                method.setAccessible(true);
                int i = ((Integer) method.invoke(null, new Object[] { java / lang / Object })).intValue();
                Class aclass[] = new Class[2];
                aclass[0] = java / lang / Class;
                aclass[1] = Integer.TYPE;
                Method method1 = java / io / ObjectStreamClass.getDeclaredMethod("newInstance", aclass);
                method1.setAccessible(true);
                c = new C(method1, i);
            } catch (Exception exception2) {
                return new D();
            }
            return c;
        }
        return b;
    }
    return a;
}
Example 92
Project: openjdk-master  File: UnsafeAccess.java View source code
private static Unsafe initUnsafe() {
    try {
        // Fast path when we are trusted.
        return Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            return (Unsafe) theUnsafe.get(Unsafe.class);
        } catch (Exception e) {
            throw new RuntimeException("exception while trying to get Unsafe", e);
        }
    }
}
Example 93
Project: stormpot-master  File: UnsafeUtil.java View source code
private static Unsafe getUnsafe() {
    try {
        return AccessController.doPrivileged((PrivilegedExceptionAction<Unsafe>) () -> {
            Class<Unsafe> unsafeClass = Unsafe.class;
            for (Field field : unsafeClass.getDeclaredFields()) {
                if (unsafeClass.isAssignableFrom(field.getType())) {
                    field.setAccessible(true);
                    Object obj = field.get(null);
                    return unsafeClass.cast(obj);
                }
            }
            return null;
        });
    } catch (PrivilegedActionException e) {
        return null;
    }
}
Example 94
Project: Truffle-master  File: UnsafeAccess.java View source code
private static Unsafe initUnsafe() {
    try {
        // Fast path when we are trusted.
        return Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            return (Unsafe) theUnsafe.get(Unsafe.class);
        } catch (Exception e) {
            throw new RuntimeException("exception while trying to get Unsafe", e);
        }
    }
}
Example 95
Project: z-stack-master  File: MethodHandlesTest.java View source code
@Test
public void testLOOKUP() {
    assertThat(LOOKUP.toString().endsWith("trusted"), is(true));
    //XXX: we try bootstrapped Unsafe by MethodHandle way
    MethodHandle HANDLE_UNSAFE = uncheckTo(() -> LOOKUP.findStaticGetter(Unsafe.class, "theUnsafe", Unsafe.class));
    Unsafe unsafe = (Unsafe) uncheckTo(() -> HANDLE_UNSAFE.invoke());
    System.out.printf("UNSAFE is %s and unsafe is %s", UNSAFE, unsafe);
    assertThat(UNSAFE == unsafe, is(true));
}
Example 96
Project: jamm-master  File: MemoryMeter.java View source code
/**
     * @return the shallow memory usage of @param object
     * @throws NullPointerException if object is null
     */
public long measure(Object object) {
    switch(guess) {
        case ALWAYS_UNSAFE:
            return MemoryLayoutSpecification.sizeOfWithUnsafe(object);
        case ALWAYS_SPEC:
            return MemoryLayoutSpecification.sizeOf(object);
        default:
            if (instrumentation == null) {
                switch(guess) {
                    case NEVER:
                        throw new IllegalStateException("Instrumentation is not set; Jamm must be set as -javaagent");
                    case FALLBACK_UNSAFE:
                        if (!MemoryLayoutSpecification.hasUnsafe())
                            throw new IllegalStateException("Instrumentation is not set and sun.misc.Unsafe could not be obtained; Jamm must be set as -javaagent, or the SecurityManager must permit access to sun.misc.Unsafe");
                    //$FALL-THROUGH$
                    case FALLBACK_BEST:
                        if (MemoryLayoutSpecification.hasUnsafe())
                            return MemoryLayoutSpecification.sizeOfWithUnsafe(object);
                    //$FALL-THROUGH$
                    case FALLBACK_SPEC:
                        return MemoryLayoutSpecification.sizeOf(object);
                }
            }
            return instrumentation.getObjectSize(object);
    }
}
Example 97
Project: hawtdispatch-master  File: StealingThread.java View source code
/**
     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
     * Replace with a simple call to Unsafe.getUnsafe when integrating
     * into a jdk.
     *
     * @return a sun.misc.Unsafe
     */
private static sun.misc.Unsafe getUnsafe() {
    try {
        return sun.misc.Unsafe.getUnsafe();
    } catch (SecurityException se) {
        try {
            return java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {

                public sun.misc.Unsafe run() throws Exception {
                    java.lang.reflect.Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
                    f.setAccessible(true);
                    return (sun.misc.Unsafe) f.get(null);
                }
            });
        } catch (java.security.PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics", e.getCause());
        }
    }
}
Example 98
Project: Amoeba-for-Aladdin-master  File: JVM.java View source code
/*
     * Support for sun.misc.Unsafe and sun.reflect.ReflectionFactory is present
     * in JRockit versions R25.1.0 and later, both 1.4.2 and 5.0 (and in future
     * 6.0 builds).
     */
private static boolean isBEAWithUnsafeSupport() {
    // This property should be "BEA Systems, Inc."
    if (System.getProperty("java.vm.vendor").indexOf("BEA") != -1) {
        /*
             * Recent 1.4.2 and 5.0 versions of JRockit have a java.vm.version
             * string starting with the "R" JVM version number, i.e.
             * "R26.2.0-38-57237-1.5.0_06-20060209..."
             */
        String vmVersion = System.getProperty("java.vm.version");
        if (vmVersion.startsWith("R")) {
            /*
                 * We *could* also check that it's R26 or later, but that is
                 * implicitly true
                 */
            return true;
        }
        /*
             * For older JRockit versions we can check java.vm.info. JRockit
             * 1.4.2 R24 -> "Native Threads, GC strategy: parallel" and JRockit
             * 5.0 R25 -> "R25.2.0-28".
             */
        String vmInfo = System.getProperty("java.vm.info");
        if (vmInfo != null) {
            // R25.1 or R25.2 supports Unsafe, other versions do not
            return (vmInfo.startsWith("R25.1") || vmInfo.startsWith("R25.2"));
        }
    }
    // If non-BEA, or possibly some very old JRockit version
    return false;
}
Example 99
Project: amoeba-master  File: JVM.java View source code
/*
     * Support for sun.misc.Unsafe and sun.reflect.ReflectionFactory is present
     * in JRockit versions R25.1.0 and later, both 1.4.2 and 5.0 (and in future
     * 6.0 builds).
     */
private static boolean isBEAWithUnsafeSupport() {
    // This property should be "BEA Systems, Inc."
    if (System.getProperty("java.vm.vendor").indexOf("BEA") != -1) {
        /*
             * Recent 1.4.2 and 5.0 versions of JRockit have a java.vm.version
             * string starting with the "R" JVM version number, i.e.
             * "R26.2.0-38-57237-1.5.0_06-20060209..."
             */
        String vmVersion = System.getProperty("java.vm.version");
        if (vmVersion.startsWith("R")) {
            /*
                 * We *could* also check that it's R26 or later, but that is
                 * implicitly true
                 */
            return true;
        }
        /*
             * For older JRockit versions we can check java.vm.info. JRockit
             * 1.4.2 R24 -> "Native Threads, GC strategy: parallel" and JRockit
             * 5.0 R25 -> "R25.2.0-28".
             */
        String vmInfo = System.getProperty("java.vm.info");
        if (vmInfo != null) {
            // R25.1 or R25.2 supports Unsafe, other versions do not
            return (vmInfo.startsWith("R25.1") || vmInfo.startsWith("R25.2"));
        }
    }
    // If non-BEA, or possibly some very old JRockit version
    return false;
}
Example 100
Project: Amoeba-Plus-For-MySQL-master  File: JVM.java View source code
/*
     * Support for sun.misc.Unsafe and sun.reflect.ReflectionFactory is present
     * in JRockit versions R25.1.0 and later, both 1.4.2 and 5.0 (and in future
     * 6.0 builds).
     */
private static boolean isBEAWithUnsafeSupport() {
    // This property should be "BEA Systems, Inc."
    if (System.getProperty("java.vm.vendor").indexOf("BEA") != -1) {
        /*
             * Recent 1.4.2 and 5.0 versions of JRockit have a java.vm.version
             * string starting with the "R" JVM version number, i.e.
             * "R26.2.0-38-57237-1.5.0_06-20060209..."
             */
        String vmVersion = System.getProperty("java.vm.version");
        if (vmVersion.startsWith("R")) {
            /*
                 * We *could* also check that it's R26 or later, but that is
                 * implicitly true
                 */
            return true;
        }
        /*
             * For older JRockit versions we can check java.vm.info. JRockit
             * 1.4.2 R24 -> "Native Threads, GC strategy: parallel" and JRockit
             * 5.0 R25 -> "R25.2.0-28".
             */
        String vmInfo = System.getProperty("java.vm.info");
        if (vmInfo != null) {
            // R25.1 or R25.2 supports Unsafe, other versions do not
            return (vmInfo.startsWith("R25.1") || vmInfo.startsWith("R25.2"));
        }
    }
    // If non-BEA, or possibly some very old JRockit version
    return false;
}
Example 101
Project: ARTPart-master  File: Main.java View source code
public static void main(String[] args) throws Exception {
    Unsafe unsafe = getUnsafe();
    check(unsafe.arrayBaseOffset(boolean[].class), vmArrayBaseOffset(boolean[].class), "Unsafe.arrayBaseOffset(boolean[])");
    check(unsafe.arrayBaseOffset(byte[].class), vmArrayBaseOffset(byte[].class), "Unsafe.arrayBaseOffset(byte[])");
    check(unsafe.arrayBaseOffset(char[].class), vmArrayBaseOffset(char[].class), "Unsafe.arrayBaseOffset(char[])");
    check(unsafe.arrayBaseOffset(double[].class), vmArrayBaseOffset(double[].class), "Unsafe.arrayBaseOffset(double[])");
    check(unsafe.arrayBaseOffset(float[].class), vmArrayBaseOffset(float[].class), "Unsafe.arrayBaseOffset(float[])");
    check(unsafe.arrayBaseOffset(int[].class), vmArrayBaseOffset(int[].class), "Unsafe.arrayBaseOffset(int[])");
    check(unsafe.arrayBaseOffset(long[].class), vmArrayBaseOffset(long[].class), "Unsafe.arrayBaseOffset(long[])");
    check(unsafe.arrayBaseOffset(Object[].class), vmArrayBaseOffset(Object[].class), "Unsafe.arrayBaseOffset(Object[])");
    check(unsafe.arrayIndexScale(boolean[].class), vmArrayIndexScale(boolean[].class), "Unsafe.arrayIndexScale(boolean[])");
    check(unsafe.arrayIndexScale(byte[].class), vmArrayIndexScale(byte[].class), "Unsafe.arrayIndexScale(byte[])");
    check(unsafe.arrayIndexScale(char[].class), vmArrayIndexScale(char[].class), "Unsafe.arrayIndexScale(char[])");
    check(unsafe.arrayIndexScale(double[].class), vmArrayIndexScale(double[].class), "Unsafe.arrayIndexScale(double[])");
    check(unsafe.arrayIndexScale(float[].class), vmArrayIndexScale(float[].class), "Unsafe.arrayIndexScale(float[])");
    check(unsafe.arrayIndexScale(int[].class), vmArrayIndexScale(int[].class), "Unsafe.arrayIndexScale(int[])");
    check(unsafe.arrayIndexScale(long[].class), vmArrayIndexScale(long[].class), "Unsafe.arrayIndexScale(long[])");
    check(unsafe.arrayIndexScale(Object[].class), vmArrayIndexScale(Object[].class), "Unsafe.arrayIndexScale(Object[])");
    TestClass t = new TestClass();
    int intValue = 12345678;
    Field intField = TestClass.class.getDeclaredField("intVar");
    long intOffset = unsafe.objectFieldOffset(intField);
    check(unsafe.getInt(t, intOffset), 0, "Unsafe.getInt(Object, long) - initial");
    unsafe.putInt(t, intOffset, intValue);
    check(t.intVar, intValue, "Unsafe.putInt(Object, long, int)");
    check(unsafe.getInt(t, intOffset), intValue, "Unsafe.getInt(Object, long)");
    Field longField = TestClass.class.getDeclaredField("longVar");
    long longOffset = unsafe.objectFieldOffset(longField);
    long longValue = 1234567887654321L;
    check(unsafe.getLong(t, longOffset), 0, "Unsafe.getLong(Object, long) - initial");
    unsafe.putLong(t, longOffset, longValue);
    check(t.longVar, longValue, "Unsafe.putLong(Object, long, long)");
    check(unsafe.getLong(t, longOffset), longValue, "Unsafe.getLong(Object, long)");
}