Last active
April 12, 2020 13:27
-
-
Save elazarl/bed80b62e77778e6099172ddf37397f3 to your computer and use it in GitHub Desktop.
This is a demonstration showing how to print stack size of a certain function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// We demonstrate how to get the stack usage of a function | |
// using the __builtin_frame_address function of GCC and clang. | |
// | |
// This function returns: | |
// The frame is the area on the stack that holds local variables and saved registers. | |
// The frame address is normally the address of the first word pushed on to | |
// the stack by the function. | |
// | |
// by saving its value and comparing it to a callee, we get the stack usage of this | |
// function. | |
// | |
// $ make stack_size | |
// cc stack_size.c -o stack_size | |
// $ ./stack_size | |
// stack size of big_func: 0x7ffee6b716e0-0x7ffee6b712d0 = 1040 | |
// stack size of small_func: 0x7ffee6b716e0-0x7ffee6b716b0 = 48 | |
#include <stdio.h> | |
void* last_frame_addr; | |
void | |
__attribute__ ((noinline)) | |
_print_stack_size(const char* func_name) { | |
printf("stack size of %s: %p-%p = %ld\n", | |
func_name, | |
last_frame_addr, | |
__builtin_frame_address(0), | |
last_frame_addr-__builtin_frame_address(0)); | |
} | |
#define print_stack_size() _print_stack_size(__func__) | |
volatile int sink; | |
void big_func() | |
{ | |
char buf[1000]; | |
int i; | |
last_frame_addr = __builtin_frame_address(0); | |
buf[0] = 1; | |
for (i=1;i<sizeof(buf);i++) { | |
buf[i] = i + buf[i-1]; | |
} | |
print_stack_size(); | |
for (i=0;i<sizeof(buf);i++) { | |
sink = buf[i]; | |
} | |
} | |
void small_func() | |
{ | |
char buf[10]; | |
int i; | |
buf[0] = 1; | |
last_frame_addr = __builtin_frame_address(0); | |
for (i=1;i<sizeof(buf);i++) { | |
buf[i] = i + buf[i-1]; | |
} | |
print_stack_size(); | |
for (i=0;i<sizeof(buf);i++) { | |
sink = buf[i]; | |
} | |
} | |
int main() { | |
big_func(); | |
small_func(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment