【发布时间】:2020-02-26 23:59:38
【问题描述】:
我正在 NASM 中做一个小小的“Hello World”程序,以便在我的 Ubuntu 机器上运行(uname -a 输出包括在下面):
$uname -a
Linux desk069 4.15.0-66-generic #75-Ubuntu SMP Tue Oct 1 05:24:09 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
现在保存到文件后,我必须运行
nasm -f elf64 ./test. ./test.nasm -o test.o
ld -o test test.o -m elf_x86_64
为了让我的代码正常工作。尝试运行test.o 给了我
bash: ./test.o: cannot execute binary file: Exec format error
并试图让 NASM 生成一个 bin 文件给了我:
$nasm -f bin ./test.nasm -o test.bin
$chmod +x ./test.bin
$./test.bin
bash: ./test.bin: cannot execute binary file: Exec format error
我的问题是,我没有使用任何库。为什么我必须使用链接器 ld? bin文件到底有什么问题?我可以做些什么让它在没有ld 的情况下运行吗?
我的代码包含在下面。
section .text
global _start
section .data
msg db 'Hello, world!', 0xa
len equ $- msg
section .text
_start:
mov edx, len
mov ecx, msg
mov ebx, 1
mov eax, 4
int 0x80
mov ebx, 0
mov eax, 1
int 0x80
【问题讨论】:
-
您不运行目标文件。当您执行
ld -o test test.o -m elf_x86_64时,这会从test.o创建一个ELF 可执行文件,并将其输出为一个名为test的ELF 可执行文件。要运行它,请使用./test。您也不会将bin文件作为 ELF 可执行文件运行。你想做什么? -
nasm -f bin ./test.nasm -o test.bin怎么样?当然,如果我告诉 NASM 给我二进制文件,它必须给我一个二进制文件? -
它会生成一个二进制文件,但 Linux 的加载器不运行 bin 文件。它将运行 ELF 可执行文件。除非您的 bin 文件碰巧被设计为看起来像 ELF 可执行文件,否则它不会运行。链接器获取目标文件并生成可由 Linux 加载程序加载的可执行文件。