Skip to content

Instantly share code, notes, and snippets.

@florence
Created January 21, 2015 04:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save florence/b1c9bcb3823fc5590e23 to your computer and use it in GitHub Desktop.
Save florence/b1c9bcb3823fc5590e23 to your computer and use it in GitHub Desktop.
import java.lang.reflect.*;
import sun.misc.Unsafe;
public class Print {
static Unsafe u = getUnsafe();
public static void main(String... args) {
try {
long addr = u.staticFieldOffset(System.class.getDeclaredField("err")) +4;
System.out.println("Java says sm is " + System.getSecurityManager());
System.out.println("we say it is: " + (SecurityManager) u.getObject(System.class, addr));
System.out.println("creating new sm in the normal way");
System.setSecurityManager(new SecurityManager());
System.out.println("Java says sm is " + System.getSecurityManager());
System.out.println("we say it is: " + (SecurityManager) u.getObject(System.class, addr));
System.out.println("Setting sm to null manually");
u.putObject(System.class, addr, null);
System.out.println("Java says sm is " + System.getSecurityManager());
System.out.println("we say it is: " + (SecurityManager) u.getObject(System.class, addr));
} catch (Exception e) {
System.out.println(e);
}
}
public static Unsafe getUnsafe() {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
return (Unsafe) f.get(null);
} catch (Exception e) {
throw new RuntimeException("", e);
}
}
public static long addressOf(Object o) throws Exception {
Object[] array = new Object[] { o };
long baseOffset = u.arrayBaseOffset(Object[].class);
int addressSize = u.addressSize();
long objectAddress;
switch (addressSize) {
case 4:
objectAddress = u.getInt(array, baseOffset);
break;
case 8:
objectAddress = u.getLong(array, baseOffset);
break;
default:
throw new Error("unsupported address size: " + addressSize);
}
return (objectAddress);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment