无法理解nasm错误。如何修复代码。

时间:2018-09-01 20:07:37

标签: assembly x86 nasm x86-64

我尝试从asm代码调用printf函数。

hello.asm:

%macro exit 0
    mov eax, 1
    mov ebx, 0
    int 80h
%endmacro

extern   printf      ; the C function, to be called

SECTION .data
    hello:     db   'Hello world!', 0

SECTION .text
    GLOBAL main

main:
    sub 8, rsp
    push dword hello
    call printf      ; Call C function
    add 8, rsp
    exit

Makefile:

all:
    nasm -f elf64 hello.asm -o hello.o
    ld hello.o -e main -o hello -lc -I/lib/ld-linux.so.2

clean:
    rm -f hello.o hello

拨打电话:

nasm -f elf64 hello.asm -o hello.o
hello.asm:16: error: invalid combination of opcode and operands
hello.asm:19: error: invalid combination of opcode and operands
make: *** [all] Error 1

请说明错误以及如何修复代码。

谢谢。

2 个答案:

答案 0 :(得分:2)

两个错误消息都提供了很好的线索。它们发生在第16和19行。

在第16行中,您具有:

sub 8, rsp

这里的问题是您不能从文字常量中减去(任何东西)。我认为实际意图是

sub rsp, 8

第19行类似,而不是

add 8, rsp

你想要什么

add rsp, 8

请注意,对于诸如subadd之类的指令,第一个操作数将获取运算结果。而且文字常量不能做到这一点!

答案 1 :(得分:1)

工作解决方案:

hello.c:

extern exit      ; the C function, to be called
extern puts      ; the C function, to be called

SECTION .data
    hello:     db   'Hello world!', 0

SECTION .text
    GLOBAL _start

_start:
    mov edi, hello
    call puts      ; Call C function
    mov edi, 0
    call exit      ; Call C function

Makefile:

all:
    nasm -f elf64 hello.asm -o hello.o
    gcc -nostartfiles -no-pie hello.o -o hello

clean:
    rm -f hello.o hello