Skip to content

Instantly share code, notes, and snippets.

@julp
Created March 29, 2016 20:14
Show Gist options
  • Select an option

  • Save julp/93c4ba6a986fd4bf32d66f33a5b34576 to your computer and use it in GitHub Desktop.

Select an option

Save julp/93c4ba6a986fd4bf32d66f33a5b34576 to your computer and use it in GitHub Desktop.
x64 (N)ASM: some libc functions
; 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
; 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