0

我有一个简单的 nasm 代码:

test.nasm

section .text

global _start

_start:
    jmp _start
    ret

我构建它如下:

nasm -f elf64 test.nasm -o test.o
ld test.o -o test -pie

然后我尝试运行它:

./test

它给了我这个:

bash: ./test: No such file or directory

所以我检查了文件头:

readelf -h test

它显示了这一点:

ELF Header:
  Magic:   7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 
  Class:                             ELF64
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              DYN (Shared object file) <====== NOT an executable
  Machine:                           Advanced Micro Devices X86-64
  Version:                           0x1
  Entry point address:               0x1f0
  Start of program headers:          64 (bytes into file)
  Start of section headers:          4616 (bytes into file)
  Flags:                             0x0
  Size of this header:               64 (bytes)
  Size of program headers:           56 (bytes)
  Number of program headers:         6
  Size of section headers:           64 (bytes)
  Number of section headers:         12
  Section header string table index: 11

但是我可以很容易地使用 GCC 为以下程序创建一个与位置无关的可执行文件:

测试2.c

#include <stdio.h>

void main(void)
{
    printf("hello, pie!\n");
}

我用以下方式构建它:

gcc test2.c -o test2 -pie

它像这样运行:

hello, pie!

那么如何使用而不是共享对象创建与位置无关的可执行文件nasmld

加 1

我检查了test2ELF 标头。它也是一个共享对象。所以这可能不是问题。(感谢@Nate Eldredge)

ELF Header:
  Magic:   7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 
  Class:                             ELF64
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              DYN (Shared object file) <===== ALSO a shared object
  Machine:                           Advanced Micro Devices X86-64
  Version:                           0x1
  Entry point address:               0x530
  Start of program headers:          64 (bytes into file)
  Start of section headers:          6440 (bytes into file)
  Flags:                             0x0
  Size of this header:               64 (bytes)
  Size of program headers:           56 (bytes)
  Number of program headers:         9
  Size of section headers:           64 (bytes)
  Number of section headers:         29
  Section header string table index: 28

那么如何使用ld生成的目标文件获取与位置无关的可执行文件nasm

4

0 回答 0