Skip to content

Instantly share code, notes, and snippets.

@chrislattman
Last active May 13, 2024 06:13
Show Gist options
  • Save chrislattman/8a81d2d12f0c3a875903e0e97cae7f87 to your computer and use it in GitHub Desktop.
Save chrislattman/8a81d2d12f0c3a875903e0e97cae7f87 to your computer and use it in GitHub Desktop.
#include <stdio.h>
__asm__(".globl func\n\t" // optional, makes the function visible outside of main_x86_64.c
"func:\n\t" // for macOS (Mach-O), change func to _func
"movl $7,%eax\n\t"
"ret"
);
// the definition of func is written in assembly language above
extern int func(void);
int func2(int x, int y)
{
int z;
__asm__("movl %1,%%eax\n\t"
"imull $3,%%eax\n\t"
"addl $4,%%eax\n\t"
"addl %2,%%eax\n\t"
"movl %%eax,%0" // if we returned here, a ret would be automatically generated
: "=r" (z) // output registers (register index starts here)
: "r" (x), "r" (y) // input registers
: "eax" // clobbered registers
); // stores 3x + 4 + y in z
return z + 5;
}
int main(void)
{
int n = func();
__asm__("leal (%0,%0,4),%0" // stores n + 4n = 5n in n
: "=r" (n) // r means load into any available register
: "0" (n) // a means %rax, D means %rdi, S means %rsi
: // d means %rdx, c means %rcx
); // 0 means that input register must be the same as the 0th output register
printf("7*5 = %d\n", n);
printf("(3*%d + 4 + %d) + 5 = %d\n", 5, 8, func2(5, 8));
fflush(stdout); // flush is intentional
return 0;
}
@chrislattman
Copy link
Author

This uses AT&T syntax

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment