How to print the location of Heap using java for a process?

回眸只為那壹抹淺笑 提交于 2020-01-06 08:24:15

问题


I want to test if ASLR which randomizes the location of a heap for a process actually works.


回答1:


You can't do this in pure Java.

  • Machine address (pointers) are not exposed to Java applications.

  • Even if they did, there's no Java API that tells you were the heap is.

I suppose that you could use the values returned by System.identityHashcode() as ersatz machine addresses. If you wrote a simple Java test application that examined identity hashcode of a sample object, then ran it multiple times with ASLR enabled and disabled, you might observe a difference in predictability.




回答2:


You can call Unsafe.allocateMemory(size) on some JVMs. This returns a memory location.

I don't recommend you do that and I don't recommend you worry about ASLR with Java.




回答3:


You should be able to do this with JNI. Allocate an array of longs the size of your heap or just smaller and call the JNI test method.

package com.example.aslrtest;

public class Test {
    private static native void test(long[] heapa);

    public void doTest()
    {
        long[] a=new long[size_of_available_heap/8];
        for (long i=0; i!=a.length; i++)
            a[i]=i;
        test(a);
        System.out.println(a[0]);
    }
}

Then with something like this JNI code, you can get the address of that array.

JNIEXPORT void JNICALL Java_com_example_aslrtest_Test_test(JNIEnv * env, jclass jc, jlongArray heapa)
{
  jlong* heapp;
  jboolean jniNoCopy = JNI_FALSE;
  heapp = (*env)->GetLongArrayElements(env, heapa, &jniNoCopy);
  heapp[0] = (jlong)heapp;
  (*env)->ReleaseLongArrayElements(env,heapa,heapp,0);
}

When this code returns, the first element of the array should contain the address of the array.

Whether doing this makes sense is another question. Depends what you're doing. I'm guessing probably not, but that's your call.



来源:https://stackoverflow.com/questions/5819651/how-to-print-the-location-of-heap-using-java-for-a-process

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!