用 riscv64- Linux -gnu-gcc 编译的 c 文件为啥能在 x8664 下运行?

46 天前
 rookiemaster

就一个简单的 c 程序:

#include <stdio.h>
int main()
{
    printf("Hello, World\n");
}

使用如下命令编译:

riscv64-linux-gnu-gcc --static hello.c -o hello_riscv64

居然可以直接运行

> ./hello_riscv64 
Hello, World

使用 qemu 也能运行:

> qemu-riscv64-static  hello_riscv64 
Hello, World

readelf 结果:

> readelf -h hello_riscv64 
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:                              EXEC (Executable file)
  Machine:                           RISC-V
  Version:                           0x1
  Entry point address:               0x1054c
  Start of program headers:          64 (bytes into file)
  Start of section headers:          501880 (bytes into file)
  Flags:                             0x5, RVC, double-float ABI
  Size of this header:               64 (bytes)
  Size of program headers:           56 (bytes)
  Number of program headers:         7
  Size of section headers:           64 (bytes)
  Number of section headers:         28
  Section header string table index: 27
1454 次点击
所在节点    C
9 条回复
koebehshian
46 天前
又不是裸机,操作系统解释了吧
SteveLee
46 天前
可能 binfmt_misc 自动调用 qemu 了,可以 ls /proc/sys/fs/binfmt_misc/ 看下
rookiemaster
46 天前
@SteveLee 谢谢,我使用 strace 命令观察系统调用(strace ./hello_riscv64),发现了一个系统调用为 readlink("/proc/self/exe", "/usr/bin/qemu-riscv64-static", 4096) = 28 。
但是不知道是什么意思
anntt
46 天前
亲测不能运行,不知道题主那里的问题
rookiemaster
46 天前
@anntt 我试试在没有装 qemu 的机子上试试
pagxir
46 天前
因为是用 qemu-user 解释执行了。效率很低,arm64/arm 一样可以解释执行。
peachpeach
46 天前
你可以理解 qemu 就是个虚拟机, 虚拟各种 CPU 架构, 甚至可以虚拟嵌入式开发板
rookiemaster
46 天前
应该是 qemu 会自动执行,把 qemu 卸载了就会正常报错了
jim9606
46 天前
可能是利用了内核的 binfmt_misc 机制自动调用 qemu 运行了。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1029725

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX