Inline assembly basics
Inline assembly functionality allows embedding assembly code in C program. This is like an inline function, where the corresponding value gets substituted. Here assembler substitutes our assembly code in proper place with no change. GCC follows AT&T systax for assembly code.
AT&T syntax
- Register prefixed with % and $ for immediate/constant.(%eax and $10)
- Source operand comes first.(opcode source destination)
- Size of operand as a suffix to opcode. i.e. b -> byte, w -> word,
l -> long.(movl) - Indirect memory reference using parenthesis, ‘( ‘ and ‘ )’.( (eax) )
In C
syntax: asm(” assembly code “);
function asm is used to write assembly code in C.
test.c
-------
#include<stdio.h>
int fun()
{
asm("mov $24, %eax");
}
int main()
{
int n = fun();
printf("%d\n", n);
return 0;
}
In test.c function fun has no return statement. But it returns 24. When a function returns, its return value is places in eax register. But we can explicitly set eax using asm. So a value can be returned without a return statement. The move instruction used is darkened above.
Operation which are very difficult or unable to perform in C can be achieved easily using inline assembly. Rotation of a block of bytes is done in a single step using asm.( ror or rol ). But in C, it takes an effort. And all machine level instructions can be used, which can’t be produced with gcc. eg: logical and arithmetic shift. Architecture dependent coding and optimization is done using inline assembly. Speed of code can be further improved with hand written assembly.


