堆栈/帧指针作为外部变量

时间:2021-08-04 19:57:50

Currently, I was writing some logging logic and wanted to make some indentation. The easiest way to understand whether any function call was present or if some function has finished is to look at the current address of stack/frame. Let's suppose that stack grows upside down, then if stack address in log() call is smaller then during the previous call we can increase indent since some function call was present. I know that there are functions like backtrace() that knows how to dump it, or you can use some assembly, however, I remember reading of external variables that can be used to retrieve this information. Can someone name these variables or give a reference where can I find them (as far as I remember it was in some computer systems book like "Computer Systems: A Programmer's Perspective "). Otherwise, what is the most convenient/fast way of getting this information?

目前,我正在编写一些日志记录逻辑,并希望进行一些缩进。理解是否存在任何函数调用或者某些函数是否已完成的最简单方法是查看堆栈/帧的当前地址。假设堆栈上下颠倒,那么如果log()调用中的堆栈地址较小,那么在上一次调用期间,我们可以增加缩进,因为存在一些函数调用。我知道有像backtrace()这样的函数知道如何转储它,或者你可以使用一些程序集,但是,我记得读过可以用来检索这些信息的外部变量。有人可以命名这些变量或提供参考我可以在哪里找到它们(据我记得它是在某些计算机系统书中,如“计算机系统:程序员的视角”)。否则,获取此信息最方便/最快捷的方法是什么?

1 个解决方案

#1


1  

This method is highly nonportable and will break under various transformations, but if you're just using it for debug logging it might be suitable.

此方法非常不可移植,并且会在各种转换下中断,但如果您只是将它用于调试日志记录,那么它可能是合适的。

The easiest way to get something resembling the current stack frame address is just take the address of any automatic-storage (local, non-static) variable. If you want a baseline to compare it against, save the address of some local in main or similar to a global variable. If your program is or might be multi-threaded, use a thread-local variable for this if needed.

获取类似当前堆栈帧地址的最简单方法是获取任何自动存储(本地,非静态)变量的地址。如果您希望基线与其进行比较,请将主要或类似地址中的某些地址保存到全局变量中。如果您的程序是或可能是多线程的,请根据需要使用线程局部变量。

#1


1  

This method is highly nonportable and will break under various transformations, but if you're just using it for debug logging it might be suitable.

此方法非常不可移植,并且会在各种转换下中断,但如果您只是将它用于调试日志记录,那么它可能是合适的。

The easiest way to get something resembling the current stack frame address is just take the address of any automatic-storage (local, non-static) variable. If you want a baseline to compare it against, save the address of some local in main or similar to a global variable. If your program is or might be multi-threaded, use a thread-local variable for this if needed.

获取类似当前堆栈帧地址的最简单方法是获取任何自动存储(本地,非静态)变量的地址。如果您希望基线与其进行比较,请将主要或类似地址中的某些地址保存到全局变量中。如果您的程序是或可能是多线程的,请根据需要使用线程局部变量。