Sunday, January 20, 2013

DLLExport with naked functions.

Not so long ago I've read a blog post written by Gynvael Coldwind about creating naked functions in C/C++ with MinGW compiler on x86 platform. He pointed out, that GCC is not supporting naked attribute on platforms other than ARM, AVR, IP2K and SPU. So basically, if you'd like to generate header-less function, you'd be stuck. But a method presented by Gynvael Coldwind works, and it works pretty flawlessly.  But what if we want to export one naked function? Definition of the function is provided in the header file, but the proper declaration header is... not generated by the compiler, and has to be written by us. So we have to provide a proper information for the linking process. What's the solution then?

.globl _returnfive
push ebp
mov ebp, esp
mov eax, 0x5
pop ebp

.section .drectve
.ascii " -export:\"returnfive\""

Looking into asm code generated by GCC, we can clearly see, that function generated with __declspec(dllexport) has an additional section called drectv, just under it's body:

.section .drectve
.ascii " -export:\"returnfive\""

Which is added specifically for the linker, so pointed function can be included in the export table.
Of course, function name depends on the case. Changing call convention, adding function arguments (if using __stdcall), function decorations in C++, etc. so we have to type the proper function name as the export symbol.

Below you can find the source code for that method:
Source Code

No comments:

Post a Comment