Fiddling with the JVM

Java is a very safe language if used in a normal way, however just like the CLR it can be used in an unsafe manor.

The main reason for using Java in a unsafe manor is performance, some unsafe operations are optimised by the JVM itself.

The boot class loader grants enough permissions to access a key undocumented class sun.misc.Unsafe. As I will state, this is an undocumented class and as the name implies it’s unsafe.

This class provides methods that allows you to manipulate objects and the memory of the objects directly.

For example, you could use it to access the object itself, lets look at an example to manipulate a String object.. not nice I hear you say…. and boy are you are so right. The purpose of this example is to demonstrate the power of the JVM if used to the extreme but not to demonstrate how to destroy the JVM.


import sun.misc.Unsafe;
import java.lang.reflect.Field;

// To Compile: javac BadBoy.java
// To Run: java -Xbootclasspath/p:. BadBoy

public class BadBoy
{
private final static Unsafe unsafe = Unsafe.getUnsafe();

public static void main(String args[]) throws Exception
{
// Find the field "count" inside java.lang.String
Field field = String.class.getDeclaredField("count");

// Find the memory offset within the field...
long countOffset = unsafe.objectFieldOffset(field);

field = String.class.getDeclaredField("offset");
long offset4Offset = unsafe.objectFieldOffset(field);

// Lets read the memory directory...
Object object = "Hello World from Java, the ultra safe language... or is it..";

int length = unsafe.getInt(object, countOffset);
System.out.println("The original Length is length: " + length);

System.out.println("1- The 'object' contains : ");
System.out.println(" -> "+object);
System.out.println(" hashCode is : " + object.hashCode());

unsafe.putInt(object, offset4Offset, 17);
unsafe.putInt(object, countOffset, 32);
System.out.println("2- The 'object' contains : ");
System.out.println(" -> "+object);
System.out.println(" hashCode is : " + object.hashCode());
}
}

Then, the output of the example on my little macbook is:


stephen-gennards-macbook:blob spg$ java -Xbootclasspath/p:. BadBoy
The original Length is length: 60
1- The 'object' contains :
-> Hello World from Java, the ultra safe language... or is it..
hashCode is : 573430574
2- The 'object' contains :
-> Java, the ultra safe language...
hashCode is : 573430574

As you can see the String object is changed but the hashCode remains the same. 🙂

Even if the above example seems weird to the extreme and it is, I offer you one take home from this blog…

Be very careful what you place on your “bootclasspath!”

This entry was posted in Java, JVM, Tips and tagged , , , . Bookmark the permalink.