Last active
May 6, 2020 16:50
-
-
Save kariya-mitsuru/7341c3b49f72fd4115545ddc0fbf41eb to your computer and use it in GitHub Desktop.
x64 Assembly FizzBuzz(258bytes version)
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
# vim: ts=8 sw=8 | |
# build and execute | |
# $ gcc -mx32 -nostdlib -static -s -Wl,--build-id=none,-Ttext,0x400074 fizzbuzz.s | |
# $ dd if=a.out of=fizzbuzz count=258 bs=1 | |
# $ chmod +x fizzbuzz | |
# $ ./fizzbuzz | |
.text | |
.Sfizzbuzz: | |
.ascii "Fizz" | |
.ascii "Buzz\n" | |
.ascii "Fizz\n" | |
.Lcheck: | |
add $4, %esi | |
xor %edx, %edx | |
mov %ebp, %eax | |
div %ebx | |
test %edx, %edx | |
mov $5, %dl # mov $5, %edx | |
ret | |
.global _start | |
_start: | |
# sbrk(0x10) | |
xor %edi, %edi | |
xor %eax, %eax | |
mov $12, %al # mov $12, %eax | |
syscall | |
lea 0x10(%rax), %edi | |
mov %edi, %r8d | |
xor %eax, %eax | |
mov $12, %al # mov $12, %eax | |
syscall | |
# loop index | |
xor %ebp, %ebp | |
# divisor | |
xor %ebx, %ebx | |
.Lloop: | |
# increment loop index | |
inc %ebp | |
# check multiple of 15 | |
mov $.Sfizzbuzz-4, %esi | |
mov $15, %bl # mov $15, %ebx | |
call .Lcheck | |
mov $9, %dl # mov $9, %edx | |
je .Loutput | |
# check multiple of 5 | |
mov $5, %bl # mov $5, %ebx | |
call .Lcheck | |
je .Loutput | |
# check multiple of 3 | |
inc %esi | |
mov $3, %bl # mov $3, %ebx | |
call .Lcheck | |
je .Loutput | |
# convert number to string | |
mov %r8d, %edi | |
lea -1(%rdi), %esi | |
mov %ebp, %eax | |
mov $10, %bl # mov $10, %ebx | |
mov %bl, (%rsi) | |
.Ltostrloop: | |
xor %edx, %edx | |
div %ebx | |
add $'0', %dl | |
dec %esi | |
mov %dl, (%rsi) | |
test %eax, %eax | |
jne .Ltostrloop | |
# calculate # of bytes for output | |
mov %edi, %edx | |
sub %esi, %edx | |
.Loutput: | |
# write(1, %rsi, %rdx) | |
xor %eax, %eax | |
inc %eax # mov $1, %eax | |
mov %eax, %edi # mov $1, %edi | |
syscall | |
# check loop condition | |
cmp $40, %ebp | |
jl .Lloop | |
.Lexit: | |
# exit(0) | |
xor %edi, %edi | |
xor %eax, %eax | |
mov $60, %al # mov $60, %eax | |
syscall |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment