Nikolay Igotti
Computing function body size in more or less portable way
Sometimes it could be interesting to figure out how big is particular function in machine code, and there's nosizeof operator applicable to functions in C and C++.
There are two approaches to figure out function size, one is to add dummy function, right
after one in question, and hope linker will not do smart reordering, and another is to
ask dynamic linker about symbol size.
This little program allows to compute size of function body at the runtime on both
Linux and Solaris. Note that on Linux program must be compiled with -fPIC
and linked with -ldl like this: gcc -fPIC -m32 ssize.c -o /tmp/a -ldl
#define _GNU_SOURCE 1
#include <dlfcn.h>
#include <elf.h>
#include <stdio.h>
int compute_size(void* start) {
Dl_info dlip;
Elf32_Sym* sym = 0;
int rv = dladdr1(start, &dlip, (void**)&sym, RTLD_DL_SYMENT);
return (rv && sym) ? sym->st_size : -1;
}
int foo() {
static int bar = 0;
printf("FOO\n");
return bar++;
}
static void foo_end() {}
int main() {
int size1 = (char*)&foo_end-(char*)&foo;
int size2 = compute_size((void*)&foo);
printf("size1=%d size2=%d\n", size1, size2);
return 0;
}
Posted at 02:42PM Jun 06, 2007 by nike in Sun | Comments[0]
Comments:
Wednesday Jun 06, 2007