Created
March 29, 2016 20:14
-
-
Save julp/93c4ba6a986fd4bf32d66f33a5b34576 to your computer and use it in GitHub Desktop.
x64 (N)ASM: some libc functions
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
| ; nasm -f elf64 strlen.asm -o strlen.o && gcc -c main.c -o main.o && gcc main.o strlen.o && ./a.out | |
| bits 64 | |
| global asm_strlen | |
| section .text | |
| asm_strlen: | |
| ; save rdi | |
| push rdi | |
| ; *al = '\0' | |
| xor al, al | |
| ; clear rcx | |
| xor rcx, rcx | |
| ; *rcx = ~*rcx | |
| not rcx | |
| ; while (*al /* '\0' */ != *rdi) ++rdi, --*rcx; | |
| cld | |
| repne scasb | |
| ; *rcx = ~*rcx | |
| not rcx | |
| dec rcx | |
| ; set return value | |
| mov rax, rcx | |
| ; restore rdi | |
| pop rdi | |
| ret |
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
| ; nasm -f elf64 strncpy.asm -o strncpy.o && gcc -c main.c -o main.o && gcc main.o strncpy.o && ./a.out | |
| bits 64 | |
| global asm_strncpy | |
| section .text | |
| asm_strncpy: | |
| ; save rdi | |
| push rdi | |
| ; 1st (rdi) | |
| ; 2nd (rsi) | |
| ; switch rsi to rdi | |
| mov rdi, rsi | |
| ; copy 3rd (rdx) argument to rcx | |
| mov rcx, rdx | |
| ; set *al to 0 ('\0') | |
| xor al, al | |
| ; look for a '\0' (*al) in the first *rdx bytes of rdi while (*rcx--) | |
| ; while ('\0' != *rdi && 0 != *rcw) --*rcx, ++rdi; | |
| cld | |
| repne scasb | |
| mov rcx, rdi | |
| ; restore rdi | |
| pop rdi | |
| ; rcx -= rsi, rcx = the length to copy | |
| sub rcx, rsi | |
| push rdi ; to return rdi later | |
| ; copy from rsi to rdi while | |
| ; while (0 != *rcx) --*rcx, *rsi++ = *rdi++; | |
| cld | |
| rep movsb | |
| ; append '\0' | |
| mov byte [rdi], 0 | |
| ; restore rdi | |
| pop rdi | |
| ; set return value to initial value of rdi | |
| mov rax, rdi | |
| ; return value in rax | |
| ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment