Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check used stack size using core file

I have a core file where the application terminated with SIGSEGV. I suspect this is because the application ran out of stack space. Is there any way to check the used stack size from the core file?

like image 250
ashish Avatar asked May 19 '16 11:05

ashish


2 Answers

If you think your stack size limit has been reached due to infinite recursion, an easy way to determine this is to run bt or info stack and see if there are many more frames than you expect. Here's an example where I recursively called a function with around 1024 bytes of local data in each stack frame:

(gdb) info stack
#0  recurse () at loop.c:5
#1  0x0000000000400565 in recurse () at loop.c:5
...
#7939 0x0000000000400565 in recurse () at loop.c:5
#7940 0x000000000040058f in main (argc=1, argv=0x7ffe63afef48) at loop.c:10

You can also exceed the stack size limit with just a few frames if you have a large amount of local data in the frames.

To check the approximate size of the stack, on Linux/x86 you can check the difference between _environ, which contains a high address that's fairly close to the base of the stack, and $sp, the stack pointer in the current frame (top of stack).

(gdb) print (char *)_environ - (char *)$sp
$5 = 8384904

This looks pretty close to the stack size limit of 8MB.

(gdb) shell ulimit -s
8192

You can also look at the difference between the $sp in the frame at the top of the stack and the $sp in the frame at the base of the stack.

(gdb) frame 0
#0  recurse () at loop.c:5
(gdb) set $topsp=$sp
(gdb) frame 7940
#7940 0x000000000040058f in main (argc=1, argv=0x7ffe63afef48) at loop.c:10
(gdb) print (char *)$sp - (char *)$topsp
$6 = 8384640
like image 96
Mark Plotnick Avatar answered Oct 06 '22 01:10

Mark Plotnick


There is a nifty way to get the stack size in the program.

You can store the address of the first variable in main in a global. Then you can make a function which finds the difference between this address and the current stack address. This will give you the stack size used within 2 bytes.

In main.

char * initaddr;
int main()
{
   char dummy;  // Note -- first variable declared.

   initaddr = &dummy;

   // Other stuff...
}

int stacksize(void)
{
   char dummy2, *lastptr;
   lastptr = &dummy2;

   return(lastptr-initaddr); // This will give the stacksize at the instant of the return function.
}

You can call this function to determine the stacksize used upto that point. This can be used as a debug tool.

like image 27
Rishikesh Raje Avatar answered Oct 06 '22 02:10

Rishikesh Raje