Stack Size Estimation

前端 未结 10 1444
醉酒成梦
醉酒成梦 2020-12-02 11:30

In multi-threaded embedded software (written in C or C++), a thread must be given enough stack space in order to allow it to complete its operations without overflowing. Co

相关标签:
10条回答
  • 2020-12-02 12:06

    We tried to solve this problem on an embedded system at my work. It got crazy, there is just too much code (both our own and 3rd party frameworks) to get any reliable answer. Luckily, our device was Linux based so we fell back to the standard behavior of giving every thread 2mb and letting the virtual memory manager optimize the use.

    Our one issue with this solution was one of the 3rd party tools performed an mlock on its entire memory space (ideally to improve performance). This caused all 2mb of stack for each thread of its threads (75-150 of them) to be paged in. We lost half of our memory space to until we figured it out and commented out the offending line.

    Sidenote: Linux's virtual memory manager(vmm) allocates RAM in 4k chunks. When a new thread asks for 2MB of address space for its stack, the vmm assigns bogus memory pages to all but the top most page. When the stack grows into bogus page the kernel detects a page fault and swaps the bogus page with a real one, (which consumes another 4k of actual RAM). This way a thread's stack can grow to any size it needs (as long as it's less than 2mb) and the vmm will ensure only a minimal amount of memory is used.

    0 讨论(0)
  • 2020-12-02 12:08

    Not 100% sure, but I think this may also be done. If you have a jtag port exposed, you can connect to Trace32 and check the maximum stack usage. Though for this, you will have to give an initial pretty big arbitrary stack size.

    0 讨论(0)
  • 2020-12-02 12:11

    You can use a static analysis tool like StackAnalyzer, if your target fits the requirements.

    0 讨论(0)
  • 2020-12-02 12:17

    This is not an offline method but on the project that I am working on we have a debug command that reads the high water mark on all of the task stacks within the application. This outputs a table of the stack usage for each task and the amount of headroom available. Checking this data after a 24 hour run with lots of user interaction gives us some confidence that the defined stack allocations are "safe".

    This works using the well tried technique of filling the stacks with a known pattern and assuming that the only way that this can be re-written is by the normal stack usage, although if it is being written by any other means a stack overflow is the least of your worries!

    0 讨论(0)
提交回复
热议问题