Monthly Archives: August 2017

Back to the stupid search function

What I intended to do was to write a file search function with as few characters of C code as possible. I dont think I did, but it was a start.

This time I have the same code in somewhat optimized nasm assembler code. Optimized as in as few instructions as possible while still having a readable source code. This is not omptimized for speed as I would guess loading big chunks into memory would be the way to go. (And some other magic I surely dont know anything about.)

This is for me a programming lesson. Maybe I will take a look at it again in a few years and see if I have improved 🙂

Compiled on OSX with nasm-2.12.02.


section .data
s db "%s: %i: %i: %s",10,0
o db "usage: ",10,0
section .bss
section .text

global _main
extern _open
extern _strlen
extern _read
extern _printf
extern _close

_main:
push rbp
mov rbp,rsp
sub rsp,48
cmp edi,3
jne .help
mov rax,qword [rsi+8]
mov qword [rbp-16],rax
mov rax,qword [rsi+16]
mov qword [rbp-24],rax
mov rdi,qword [rbp-16]
mov esi,0
call _open
mov dword [rbp-28],eax
mov rdi,qword [rbp-24]
call _strlen
mov qword [rbp-36],rax
mov r12,0
mov r13,0
mov r14,qword [rbp-24]
lea r15,[rbp-37]

.read:
mov edx,1
mov edi,dword [rbp-28]
mov rsi,r15
call _read
inc r13
cmp eax,0
je .end
movzx eax,byte [rbp-37]
movsxd rcx,r12d
lea r12d,[rcx+1]
cmp al, byte [r14+rcx]
mov eax,0
cmovne r12d,eax
cmp r12,qword [rbp-36]
jne .read
mov r12,0
mov ecx,r13d
mov edx,r13d
mov rax,qword [rbp-36]
sub edx,eax
lea rdi,[rel s]
mov rsi,qword [rbp-16]
mov r8,qword [rbp-24]
call _printf
jmp .read

.help:
lea rdi,[rel o]
call _printf

.end:
mov edi,dword [rbp-28]
call _close
add rsp,48
pop rbp
ret