Implementing the "." word from Forth in x86 assembly

167 views Asked by At

I am trying to make a function that, prints a number out on screen. Eventually, I'll make it able to take the top stack item, print it, and then pop it (like the "." word in Forth). But for now, I am trying to keep it simple. I think that I need to align the call stack in some way - and I figured that pushing and popping an arbitrary register before and after calling printf (rbx) would do the trick - but I am still getting a segmentation fault. A backtrace in GDB hasn't helped me make any progress either. Does anyone know why this code is causing a segmentation fault, and how to fix it?

How I am assembling (GAS): gcc -masm=intel

.data
    format_num: .ascii "%d\0"

.text
    .global _main
    .extern _printf

print_num:
    push rbx
    lea rdi, format_num[RIP]
    mov esi, 250
    xor eax, eax
    call _printf
    pop rbx
    ret

_main:
    call print_num

    mov rdi, 0
    mov rax, 0x2000001
    syscall
0

There are 0 answers