Calculate a C Function Size x64, x86
Hi to everyone,
For a project i’m working on i needed to calculate a function size for anti-debugging purposes, but could not find any acceptable solution for this problem on the internet.
This let me to think alone and i came up with a solution.
The solution was simple, placing some known opcode at the end of the function we need to find the size. We already know the start address, and if we put known opcode at the end, we can search from the start to the opcodes we placed in order to calculate the function size at runtime.
So let’s do that together
In order to see what’s going on in the background, switch your assembler output option to /FAcs for both debug and release configuration of your project, like seen in the below picture.
Now let’s choose an opcode to insert into the code, i have chosen __debugbreak which you can see in the microsoft website which is actually int 3 instruction and in turn, it is a 1 byte instruction, 0xCC.
i have created a macro to place 8 byte sequential int 3, 8 byte 0xCC sequentially
In debug configuration, microsoft not actually calls functions, instead, they do relative jump (E9 JUMP). So we need to find the actual start address of the function like seen below.
So the function which look for our 8 byte 0xCC
And last functions are test and main, in order to test our attempt.
When you look at the debug output, everything looks normal as follows
We can see lots of int 3(0xCC) (actually 8 of them)
But when you look at the release output, compiler thinks that, that bunch of int 3 under the ret (return n) would not actually be executed, so emit them from the code (optimisation)
So here comes to magic, every compiler suffers from fearing volatile variables, so if we use one, even if it’s meaningless, compiler will fear and put that code in there for us
We change our test function as follows,
After rebuilding the project, the release output magically will have those int 3 instructions we need.
And to try it out, i executed both debug and release version of the exe,
So we get the results,
Have a good day, happy coding…