Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the size of a C++ function?

Tags:

c++

function

How can I get the size of a function in C++?

Let's say I have a function:

void f()
{
/*do something*/
}

...By "size of f", I mean the size of the code /*do something*/, starting from the address indicated by a pointer to f.

like image 753
x1234x Avatar asked Nov 29 '22 04:11

x1234x


1 Answers

You can't. It may not even be a well-defined concept. For example, consider the following code:

int f(int a) {
    return (3*a)+1;
}

int g(int a) {
    return (2*a)+1;
}

I doubt it happens in practice for this particular example, because it wouldn't be an optimization, but the compiler is permitted to introduce a block of code that computes a+1 then returns, and jump to that block from each of the entry points of f and g (after doing a multiplication in each case). What then would be the size of f? Should it include the size of the shared block? Half that size? It just doesn't make sense in C++ terms to claim that the function f has a size.

Also, a "pointer to f" may not simply be the address of the function f. It certainly provides a way to get to the entry point of f, but for example on an ARM processor in interworking mode, a pointer to a function consisting of Thumb code is actually the address of the first instruction, plus 1. In effect, the lsb of the pointer is masked off by the CPU when performing the jump to the function, but that bit tells the CPU to switch into Thumb mode rather than ARM mode. So the value of the pointer is not the address of the function (although it's close). Anyway, the entry point of a function need not necessarily be the at the start of it - if your compiler creates constant pools or similar, they could precede the executable code.

There may be platform-specific ways of examining your executables (either the files, or after loading into memory, or both), and saying what code is associated with what C++ functions. After all, it's what debug info is for. But there's no way of doing that in standard C++, and the standard doesn't require that any such mechanism exists.

like image 122
Steve Jessop Avatar answered Dec 15 '22 16:12

Steve Jessop