首页 > 解决方案 > 使用 GCC 在 Linux 上生成“平面”hello world 二进制文件

问题描述

我试图让 gcc 生成一个“平面二进制”hello world 程序,即一个可重定位的自包含程序,它由一个组合 .text、.data 和 .rodata 的部分组成,其入口和出口点只是文件。

到目前为止,我已经编写了以下 C 代码:

#include <sys/types.h>

static inline ssize_t _write(int fd, const void *buf, size_t count) {
  ssize_t ret;

  __asm__ volatile(
    "mov %0, %%rdi\n"
    "mov %1, %%rsi\n"
    "mov %2, %%rdx\n"
    "mov $1, %%rax\n"
    "syscall\n"
    :
    : "g"(fd), "g"(buf), "g"(count));

  __asm__ volatile ("mov %%rax, %0" : "=r"(ret));

  return ret;
}

int _start() {
  char const *msg = "hello world\n";

  _write(0, msg, sizeof(msg));

  __builtin_unreachable(); /* don't generate ret statement */
}

我正在尝试用以下方式编译它:

gcc -std=c99 -fPIC -fno-stack-protector -c hello.c -o hello.o
gcc -N -nostdlib -fno-stack-protector hello.c -o hello

但这会导致:

/usr/bin/ld: hello: error: PHDR segment not covered by LOAD segment
collect2: error: ld returned 1 exit status

这似乎是由-N链接器选项引起的,但我不知道究竟是为什么。

我正在研究5.12.12-arch1-1GCC11.1.0和 GNU ld 2.36.1

标签: clinuxgccx86-64

解决方案


推荐阅读