Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent for GCC's naked attribute

I've got an application written in pure C, mixed with some functions that contain pure ASM. Naked attribute isn't available for x86 (why? why?!) and my asm functions don't like when prologue and epilogue is messing with the stack. Is it somehow possible to create a pure assembler function that can be referenced from C code parts? I simply need the address of such ASM function.

like image 896
kjagiello Avatar asked Dec 04 '11 09:12

kjagiello


2 Answers

Just use asm() outside a function block. The argument of asm() is simply ignored by the compiler and passed directly on to the assembler. For complex functions a separate assembly source file is the better option to avoid the awkward syntax.

Example:

#include <stdio.h>

asm("_one:              \n\
        movl $1,%eax    \n\
        ret             \n\
");

int one();

int main() {
        printf("result: %d\n", one());
        return 0;
}

PS: Make sure you understand the calling conventions of your platform. Many times you can not just copy/past assembly code.

PPS: If you care about performance, use extended asm instead. Extended asm essentially inlines the assembly code into your C/C++ code and is much faster, especially for short assembly functions. For larger assembly functions a seperate assembly source file is preferable, so this answer is really a hack for the rare case that you need a function pointer to a small assembly function.

like image 146
Mackie Messer Avatar answered Oct 07 '22 07:10

Mackie Messer


Good news everyone. GCC developers finally implemented attribute((naked)) for x86. The feature will be available in GCC 8.

like image 34
user576557 Avatar answered Oct 07 '22 06:10

user576557