0

I want to analyze the String object reference difference between heap reference and constant pool reference,using jmap to dump a java Program binary file,a Object address in bin
enter image description here

trying to use System.out.println to get a real address ,and i can use it to find it binary form,but this method to println[Ljava.lang.String;@18b4aac2,not a real address ,may like is virtual memory address.

so change method like is:

public class Main {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {

        String[] key = {"qwerty"};
        String obj = "qwerty";
        Unsafe unsafe = getUnsafe();
        System.out.println(getAddressOf(key,unsafe));
        System.out.println(getAddressOf(key[0],unsafe));
        System.out.println(getAddressOf(args,unsafe));
        System.out.println(getAddressOf(args[0],unsafe));
        System.out.println(getAddressOf(obj,unsafe));
    }

    private static Unsafe getUnsafe() throws NoSuchFieldException, IllegalAccessException {
        Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
        unsafeField.setAccessible(true);
        return (Unsafe) unsafeField.get(null);
    }

    private static <T> String getAddressOf(T object, Unsafe unsafe) throws NoSuchFieldException {
        Object[] array = {object};
        long baseOffset = unsafe.arrayBaseOffset(Object[].class);
        int addressSize = unsafe.addressSize();
        long objectAddress;
        switch (addressSize) {
            case 4:
                objectAddress = unsafe.getInt(array, baseOffset);
                break;
            case 8:
                objectAddress = unsafe.getLong(array, baseOffset);
                break;
            default:
                throw new Error("unsupported address size: " + addressSize);
        }
        return Long.toHexString(objectAddress);
    }
}

but its still not right

how to get a real address or Why can't I get the true answer when using the methods mentioned above?

  • This might be related: https://stackoverflow.com/questions/25120546/trick-behind-jvms-compressed-oops – Solomon Ucko May 24 '23 at 04:12
  • 2
    I'm not sure if that's even possible. The hexadecimal value within the printed address, `18b4aac2`, is a hash-code, it's not an address. – Reilas May 24 '23 at 04:40
  • What's not right about your second method? First `System.out.println` is not going to "get an address" . Which version of java are you targeting. `Unsafe` is removed at some point but in java 8 it should do what you want. (As your answer has done, but we don't know what is wrong with the code. – matt May 24 '23 at 07:12

0 Answers0