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 no sizeof 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;
}
Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

nike

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today