Skip to content

Instantly share code, notes, and snippets.

@bellbind
Last active August 22, 2018 23:04
Show Gist options
  • Save bellbind/2bb6436c22ee2da2e19d to your computer and use it in GitHub Desktop.
Save bellbind/2bb6436c22ee2da2e19d to your computer and use it in GitHub Desktop.
[clang][gcc][c][osx] inline asm to syscall on OSX amd64
/* clang hello-asm.c -o hello-asm */
int main() {
long write = 0x2000004; /* syscall "write" on MacOS X */
long stdout = 1;
char * str = "Hello World\n";
unsigned long len = 12;
unsigned long ret = 0;
/* ret = write(stdout, str, len); */
__asm__("movq %1, %%rax;\n"
"movq %2, %%rdi;\n"
"movq %3, %%rsi;\n"
"movq %4, %%rdx;\n"
"syscall;\n"
"movq %%rax, %0;\n"
: "=g"(ret)
: "g"(write), "g"(stdout), "g"(str), "g"(len)
: ); /* assign from generic registers to syscall registers */
return ret; /* will be 12 ("echo $?") */
/* clang hello-asm2.c -o hello-asm2 */
int main() {
long write = 0x2000004; /* syscall "write" on MacOS X */
long stdout = 1;
char * str = "Hello World\n";
unsigned long len = 12;
unsigned long ret = 0;
/* ret = write(stdout, str, len); */
__asm__("syscall"
: "=a"(ret)
: "a"(write), "D"(stdout), "S"(str), "d"(len)
: ); /* directly assigned by register attribute */
return ret; /* will be 12 ("echo $?") */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment