CSES - A+B sample
# Compile
nasm -f elf64 aplusb.asm -o aplusb.o && ld aplusb.o -o aplusb
# With debug info
nasm -f elf64 -g -F dwarf aplusb.asm -o aplusb.o && ld aplusb.o -o aplusb
# Debug with gdb
gdb aplusb
(gdb) tui enable
(gdb) layout reg
(gdb) break _start
(gdb) run
(gdb) stepi # Run one instruction
# (Ctrl-L to fix the view if it gets messed up)
# NASM bug: GDB says "No Source Available". Use YASM instead
yasm -f elf -m amd64 -g dwarf2 aplusb.asm -o aplusb.o && ld aplusb.o -o aplusb
section .bss
buff: resb 100
section .text
global _start
_start:
; read(0, buff, 100)
xor rax, rax
xor rdi, rdi
mov rsi, buff
mov rdx, 100
syscall
mov rsi, buff
lodsb
mov rsi, buff
call atoi
mov rcx, rdx
call atoi
add rcx, rdx
mov rdi, buff+99
mov rsi, rdi
std
mov rax, 10
stosb
mov rax, rcx
call itoa
sub rsi, rdi
mov rdx, rsi
mov rsi, rdi
; write(1, buff, rdx)
inc rdx
mov rax, 1
mov rdi, rax
syscall
mov rax, 60
xor rdi, rdi
syscall
atoi: ; Read one int
xor rax, rax
xor rdx, rdx
lodsb
cmp al, '-'
sete bl
jne .lpv
.lp:
lodsb
.lpv:
sub al, '0'
jl .end
imul rdx, 10
add rdx, rax
jmp .lp
.end:
test bl, bl
jz .p
neg rdx
.p:
ret
itoa: ; Write one int
std
mov r9, 10
bt rax, 63
setc bl
jnc .lp
neg rax
.lp:
xor rdx, rdx
div r9
xchg rax, rdx
add rax, '0'
stosb
xchg rax, rdx
test rax, rax
jnz .lp
test bl, bl
jz .p
mov al, '-'
stosb
.p:
cld
inc rdi
ret