Definition: assembly routines written as an inline function. Allows one to access architecture dependent instructions not available in C.
Form: must be inside of a function beginning with either 'asm' or '__asm__'
int main(){
// volatile keyword tells the compiler to not optimize this area of code. The compiled binary will contain this exact sequence of code
// optional: output operands, input operands, or clobbered registers
__asm__ __volatile__ (
<assembler template>
; <output operands>
; <input operands>
; <list of clobbered registers>
);
}
Assembler Template: houses the assembly instructions. Each assembly instruction is inside double quotes ending with \n\t. Also, by default instruction is in AT&T syntax. Example: "movl $1, %%eax\n\t". You can also use semicolon instead
Output Operands: C variables modified by assembler template. Can contain constraints and is referenced in assembler template with %[num]. [num] is the position the operand is in comparison to the other operands. Example: "=r" (var_1). "=" is the constraint modifier that tells gcc that this operand is write-only and "r" is the constraint that let gcc knows that any general-purpose register is fine to be used for the operand
Input Operands: C variables used by assembler template. Can contain constraints and is referenced in assembler template with %[num] just like output operands
Clobbered Registers: Registers changed in the assembler template. Needs to explicitly tell gcc since the registers used by assembler template could contain important data used in current function after the inline assembly. This informs gcc to properly save and restore those registers before and after the inline assembly. Example: "ebx", "eax", "ecx"
Constraints:
Constraints | Register(s) |
---|---|
r | any GPR |
a | eax, ax, al |
b | ebx, bx, bl |
c | ecx, cx, cl |
d | edx, dx, dl |
S | esi, si |
D | edi, di |
Note: Input and output operands are referenced in code with %