C language > Expert questions

How to get the size of function body?

(1/3) > >>

bitcoin:
May be you know about it..

I try to get size of function body, to compute crc32 of this (protection of crackers / debugers). I found some macroses, like:


--- Code: ---#define start(f) __declspec(naked) void start_##f(void) {};
#define end(f) __declspec(naked) void end_##f(void) {};
#define calc_size(f) (uint8_t*)end_##f - (uint8_t*)start_##f
--- End code ---

Usage:

--- Code: ---start(some_func);
int some_func(int a,int b)
{
int x = 2;
int y = 3;
int z = x+y;
y = a * 5;
x = b + 12;
z = x + y;

return z;
}
end(some_func);
....
int func_size = calc_size(some_func);

--- End code ---
But it only works with compiler options -Os -Ob1 (min size), i have 18 bytes size of function. If I use another compiler option optimization, the result are diffences. Example - in Ida dizasembler I see that func size is X byte, buf macros tell me another value. Why? And what is the rigth way to calculate function body size?

frankie:
There is no standard way to know the size in bytes of a function.
The method you used is based on the, wrong, assumption that the functions are linked in the executable in the exact same order in which they are defined in source code.
With almost all decent linkers this isn't true.

bitcoin:

--- Quote ---The method you used is based on the, wrong, assumption that the functions are linked in the executable in the exact same order in which they are defined in source code
--- End quote ---
But isn’t there some linker key , that defines this behavior (order linking functions) ?

frankie:

--- Quote from: bitcoin on January 25, 2020, 06:23:18 PM ---
--- Quote ---The method you used is based on the, wrong, assumption that the functions are linked in the executable in the exact same order in which they are defined in source code
--- End quote ---
But isn’t there some linker key , that defines this behavior (order linking functions) ?

--- End quote ---
Short answer: No
Consider also that future versions of linkers and compilers may behave differently, and also what apparently works using  -Os -Ob1 switch could not work anymore.
See this.

Vortex:
Not an universal method but it's possible to search for the RET instruction in the epilogue code of a function. 32-bit code demo :


--- Code: ---#include <stdio.h>

int testfunc(int x,int y,int *pSize)
{
    int temp;
    int result;

    __asm{
            mov edx,OFFSET label1
            dec edx
l1:
            inc edx
           
// Search for the RET ( 0xC3 ) instruction

            cmp BYTE PTR [edx],0xC3
            jne l1

            mov temp,edx
}

    result=x;
    result+=y;

    *pSize=1+(int)temp-(int)testfunc;
   
label1:

return result;
}

int main(void)
{
    int fSize;

    testfunc(10,20,&fSize);

    printf("Size of the function testfunc = %d bytes\n",fSize);

    return 0;

}
--- End code ---

Navigation

[0] Message Index

[#] Next page

Go to full version