Search code examples
assemblyx86-64openbsd

Why does this assembly program produce no output?


Being new to x86_64 assembly, I am trying to write a basic "hello" program on my laptop running 64-bit OpenBSD. The program runs to completion with exit code 0, but seems to ignore the system call to write text to stdout. Why?

I am using the GNU assembler and creating the executable with:

as -o hello.o hello.s; ld -Bstatic hello.o

# OpenBSD ELF identification
.section ".note.opensd.ident", "a"
.p2align 2
.long 0x8
.long 0x4
.long 0x1
.ascii "OpenBSD\0"
.long 0x0
.p2align 2

.section .data
msg: .ascii "hello"

.section .text
.globl _start
_start:
    push $5 # number of bytes to write
    push $msg # message address
    push $1 # file descriptor 1 for stdout
    mov $4, %eax # write is system call 4
    syscall

    push $0 # exit code 0
    mov $1, %eax # exit is system call 1
    syscall

Solution

  • Since you tag x86_64 and probably are on an x86_64 system. Therefore you need to:

    • as --64
    • use pushq instead of pushl to push 64bit values on the stack
    • transfer those values to the appropriate registers before syscall

      .section ".note.opensd.ident", "a"
      .p2align 2
      .long 0x8
      .long 0x4
      .long 0x1
      .ascii "OpenBSD\0"
      .long 0x0
      .p2align 2
      
      .section .data
       msg: .ascii "hello"
      
      .section .text
      .globl _start
      _start:
              pushq $0x4
              popq %rax               # 4 (write syscall) into rax
              pushq $0x1
              popq %rdi               # 1 (STDOUT) into rdi
              pushq $msg
              popq %rsi               # address of hello msg into rsi
              pushq $0x5
              popq %rdx               # length of hello msg into rdx
              syscall
              pushq $1
              popq %rax
              pushq $0
              popq %rdi
              syscall
      

    the following articles offer some good info:

    x64 asm on FreeBSD

    differences between x86 and x64 asm