Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get current values of locals and parameters on the stack?

In a .NET application I have some points where I need to collect some debug info about the current thread state. I can obtain some information new StackTrace() constructor. In particular, I can get the list of current stack frames, including corresponding MethodInfo objects, which can provide me the IL code, the number of local variables and parameters and parameter names.

How can I get current values of these locals and parameters (at least of primitive types)?

I am not able to manually attach any debuggers to the application, but the application can spawn new processes if needed.

like image 932
X.C. Avatar asked May 27 '13 02:05

X.C.


People also ask

How are local variables stored on the stack?

The stack is used for dynamic memory allocation, and local variables are stored at the top of the stack in a stack frame. A frame pointer is used to refer to local variables in the stack frame.

How are parameters passed on the stack?

To pass parameters to a subroutine, the calling program pushes them on the stack in the reverse order so that the last parameter to pass is the first one pushed, and the first parameter to pass is the last one pushed. This way the first parameter is on top of the stack and the last one is at the bottom of the stack.

What is a stack frame and Why is it so important?

A stack frame is a memory management technique used in some programming languages for generating and eliminating temporary variables. In other words, it can be considered the collection of all information on the stack pertaining to a subprogram call. Stack frames are only existent during the runtime process.


1 Answers

Reflection, what you are using to obtain MethodInfo and other details, uses metadata created at compile time -- that is, the data you are accessing has no relation to run-time data, which is what you want.

You mentioned that you can't use a debugger, and you're right, because in production code there's usually no debug symbols loaded in your assembly; a debugger would be no use there.

A important thing here is that, per .NET architecture, once you run an assembly, a "jitter" runs and transforms your IL code into native code; The result is that what is loaded in memory is pure machine code that you can't very easily hack into to obtain values (although theoretically possible). Another point mentioned are optimizations - as long as they are on, you can expect methods to disappear (being inlined), execution order may be changed and variables replaced by literals. The compiler does a lot of stuff to get your code to run faster.


Although I can't see a good solution for obtaining locals' values in run-time, I think there are ways to obtain parameters' value using interception techniques. Take a look at what PostSharp can do for you.

like image 112
Bruno Brant Avatar answered Oct 22 '22 03:10

Bruno Brant