Skip to content

Instantly share code, notes, and snippets.

@DosAmp
Last active July 21, 2016 15:57
Show Gist options
  • Save DosAmp/1aa4743bb509fa9dd772212a3d18f59a to your computer and use it in GitHub Desktop.
Save DosAmp/1aa4743bb509fa9dd772212a3d18f59a to your computer and use it in GitHub Desktop.
Simple Linux/x86_64 Assembler exercise
; how to compile:
; nasm -f elf64 [-g] -o lines.o lines.asm
; ld [-s] -o lines lines.o
TIOCGWINSZ: equ 0x5413 ; from asm-generic/ioctls.h
sys_write: equ 1 ; from arch/x86/entry/syscalls/syscall_64.tbl
sys_ioctl: equ 16
sys_exit: equ 60 ; no threads, so no exit_group needed
section .text
global _start
_start: mov rax, sys_write
mov rdi, 1 ; stdout
mov rsi, hello_msg
mov rdx, hello_len
syscall
mov rax, sys_ioctl ; rdi is still stdout
mov rsi, TIOCGWINSZ
mov rdx, winsize
syscall
test rax, rax ; was ioctl successful?
jne error
bitfiddle: mov ax, [winsize_rows]
xor rdx, rdx ; "Bizarrely, on input rdx must be zero,
; or you get a SIGFPE."
mov rcx, 10
div rcx ; rows/10 in rax, rows%10 in rdx
sal rdx, 8
add rax, rdx
add rax, 0x3030 ; yz rows -> 0x3z3y
cmp al, 0x30 ; y = 0?
jne result
sub rax, 0x10 ; turn 0 into a space (0x20)
result: mov [termsize_msglines], ax
mov rax, sys_write ; rdi is still stdout
mov rsi, termsize_msg
mov rdx, termsize_len
syscall
xor rdi, rdi
jmp exit
error: mov rdi, 1
exit: mov rax, sys_exit
syscall
section .rodata
hello_msg: db "Hello world!", 0xa
hello_len: equ $-hello_msg
section .data
termsize_msg: db "Your terminal is "
termsize_msglines: db " "
termsize_msgend: db " lines high.", 10
termsize_len: equ $-termsize_msg
section .bss
winsize:
winsize_rows: resw 1
winsize_cols: resw 1
winsize_unused: resd 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment