Sun.misc.Unsafe: How to get bytes from an address

I heard that there is a way to read the value from memory (as long as the memory is controlled by the JVM). But how can I get bytes from an address 8E5203for example? There is a method called getBytes(long). Can i use this?

Thanks a lot! Pete

+3
source share
1 answer

You cannot directly access any memory location! It must be managed by the JVM. A security exception occurs or EXCEPTION_ACCESS_VIOLATION. This can cause the JVM to crash. But if we allocate memory from code, we can access bytes.

public static void main(String[] args) {
     Unsafe unsafe = null;

        try {
            Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (sun.misc.Unsafe) field.get(null);
        } catch (Exception e) {
            throw new AssertionError(e);
        }

        byte size = 1;//allocate 1 byte
        long allocateMemory = unsafe.allocateMemory(size);
        //write the bytes
        unsafe.putByte(allocateMemory, "a".getBytes()[0]);
        byte readValue = unsafe.getByte(allocateMemory);            
        System.out.println("value : " + new String(new byte[]{ readValue}));
}
+2
source

Source: https://habr.com/ru/post/1718773/


All Articles