Last active
August 22, 2018 23:04
-
-
Save bellbind/2bb6436c22ee2da2e19d to your computer and use it in GitHub Desktop.
[clang][gcc][c][osx] inline asm to syscall on OSX amd64
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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 $?") */ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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