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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With