为什么这个汇编程序不产生输出?

时间:2015-01-10 20:23:10

标签: assembly x86-64 openbsd

作为x86_64程序集的新手,我正在尝试在运行64位OpenBSD的笔记本电脑上编写一个基本的“hello”程序。程序运行完成,退出代码为0,但似乎忽略了将文本写入stdout的系统调用。为什么呢?

我正在使用GNU汇编程序并使用:

创建可执行文件

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

1 个答案:

答案 0 :(得分:0)

由于您标记了x86_64,并且可能位于x86_64系统上。因此,您需要:

  • as --64
  • 使用pushq而不是pushl来推送堆栈上的64位值
  • 在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
    

以下文章提供了一些很好的信息:

x64 asm on FreeBSD

differences between x86 and x64 asm