Inferring a method's stack memory use in Java

浪尽此生 提交于 2019-12-05 00:46:34

This question may be way over my head, perhaps you are talking about this on a deeper level, but I'll throw my answer out there anyway.

Firstly, what do you refer to by return address pointer? When a method is finished the return method is popped from the stack frame. So no return address is stored within the executing method Frame.

The method Frame stores local variables. Since it's static, and parameterless, these should be empty as you say, and the sizes of the op stack and locals are fixed at compile time, with each unit in each being 32bits wide. But as well as this the method also must have a reference to the constant pool of the class to which it belongs.

In additional the JVM spec specifies that method frames may be extended with additional implementation-specific information, such as debugging information. Which could explain the remaining bytes, depending on the compiler.

All sourced from the JVM Specification on Frames.

UPDATE

Scouring the OpenJDK source reveals this, which appears to be the struct that is passed to Frames on method invocation. Gives a pretty good insight on what to expect within:

/* Invoke types */

#define INVOKE_CONSTRUCTOR 1
#define INVOKE_STATIC      2
#define INVOKE_INSTANCE    3

typedef struct InvokeRequest {
    jboolean pending;      /* Is an invoke requested? */
    jboolean started;      /* Is an invoke happening? */
    jboolean available;    /* Is the thread in an invokable state? */
    jboolean detached;     /* Has the requesting debugger detached? */
    jint id;
    /* Input */
    jbyte invokeType;
    jbyte options;
    jclass clazz;
    jmethodID method;
    jobject instance;    /* for INVOKE_INSTANCE only */
    jvalue *arguments;
    jint argumentCount;
    char *methodSignature;
    /* Output */
    jvalue returnValue;  /* if no exception, for all but INVOKE_CONSTRUCTOR */
    jobject exception;   /* NULL if no exception was thrown */
} InvokeRequest;

Source

Peter Lawrey

You need to include in the stack the instruction pointer (8 bytes) and there may be other context information which is saved even if you don't believe it would need to be. The alignment could be 16 bytes, 8 bytes like the heap is. e.g. it could reserve 8-bytes for the return value even if there isn't one.

Java isn't as suited to heavy use of recursion like many languages are. e.g. it doesn't do tail-call optimisation which in this case would cause your program to run forever. ;)

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