9

In a C program that doesn't use recursion, it should be possible in theory to work out the maximum/worst case stack size needed to call a given function, and anything that it calls. Are there any free, open source tools that can do this, either from the source code or compiled ELF files?

Alternatively, is there a way to extract a function's stack frame size from an ELF file, so I can try to work it out manually?

I'm compiling for the MSP430 using MSPGCC 3.2.3 (I know it's an old version, but I have to use it in this case). The stack space to allocate is set in the source code, and should be as small as possible so that the rest of memory can be used for other things. I have read that you need to take account of the stack space used by interrupts, but the system I'm using already takes account of this - I'm trying to work out how much extra space to add on top of that. Also, I've read that function pointers make this difficult. In the few places where function pointers are used here, I know which functions they can call, so could take account of these cases manually if the stack space needed for the called functions and the calling functions was known.

Static analysis seems like a more robust option than stack painting at runtime, but working it out at runtime is an option if there's no good way to do it statically.

Edit:

I found GCC's -fstack-usage flag, which saves the frame size for each function as it is compiled. Unfortunately, MSPGCC doesn't support it. But it could be useful for anyone who is trying to do something similar on a different platform.

4

5 回答 5

1

虽然静态分析是确定最大堆栈使用量的最佳方法,但您可能不得不求助于实验方法。这种方法不能保证你有一个绝对的最大值,但可以让你很好地了解堆栈的使用情况。

您可以检查链接描述文件以获取 __STACK_END 和 __STACK_SIZE 的位置。您可以使用它们以易于识别的模式(如 0xDEAD 或 0xAA55)填充堆栈空间。通过酷刑测试运行您的代码,以尝试确保生成尽可能多的中断。

测试后,您可以检查堆栈空间以查看有多少堆栈被覆盖。

于 2013-07-09T03:04:45.010 回答
0

我认为唯一要做的就是通过静态分析。您需要考虑所有非静态局部变量的空间,这些变量主要是指针,但无论如何都将存储在堆栈中的指针,您还需要为当前运行地址保留空间调用者,因为它将由编译器存储在堆栈中,因此可以在函数返回后将控制权返回给调用者,而且,所有函数参数都需要空间。基于此,如果你有一个工具能够计算所有参数、自动变量并计算它们的大小,你应该能够计算出你需要的最小堆栈帧大小。请注意,编译器还可以尝试为您的特定架构对齐堆栈上的值,

于 2013-04-01T13:46:38.587 回答
0

一些嵌入式 IDE 可以在运行时提供有关堆栈使用情况的信息我知道 IAR 嵌入式工作台支持它。

请注意,您需要考虑到中断是异步发生的,因此请采用最大的堆栈使用场景并为其添加中断上下文。如果像 ARM 处理器一样支持嵌套中断,您也需要考虑到这一点。

于 2013-04-01T18:51:28.090 回答
0

TinyOS 在堆栈大小分析方面做了一些工作。它在这里描述:http: //tinyos.stanford.edu/tinyos-wiki/index.php/Stack_Analysis

他们只支持AVR,但说“MSP430不难支持,但这不是超高优先级”。无论如何,该页面提供了大量资源。

于 2013-09-03T20:42:37.573 回答
0

有趣的问题。

我希望这些信息在调试版本中包含的调试数据中静态可用。

我简要了解了DWARF标准,它确实为调用的函数指定了两个属性,DW_AT_frame_baseDW_AT_static_link用于“计算立即包含子例程或入口点的子例程的相关实例的框架基础”。

于 2013-04-01T10:43:07.023 回答