V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
rookiemaster
V2EX  ›  C

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

  •  1
     
  •   rookiemaster · 25 天前 · 1324 次点击

    就一个简单的 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
    
    9 条回复    2024-04-05 00:28:59 +08:00
    koebehshian
        1
    koebehshian  
       25 天前
    又不是裸机,操作系统解释了吧
    SteveLee
        2
    SteveLee  
       25 天前 via iPhone   ❤️ 2
    可能 binfmt_misc 自动调用 qemu 了,可以 ls /proc/sys/fs/binfmt_misc/ 看下
    rookiemaster
        3
    rookiemaster  
    OP
       25 天前
    @SteveLee 谢谢,我使用 strace 命令观察系统调用(strace ./hello_riscv64),发现了一个系统调用为 readlink("/proc/self/exe", "/usr/bin/qemu-riscv64-static", 4096) = 28 。
    但是不知道是什么意思
    anntt
        4
    anntt  
       25 天前 via iPhone
    亲测不能运行,不知道题主那里的问题
    rookiemaster
        5
    rookiemaster  
    OP
       25 天前
    @anntt 我试试在没有装 qemu 的机子上试试
    pagxir
        6
    pagxir  
       25 天前 via Android
    因为是用 qemu-user 解释执行了。效率很低,arm64/arm 一样可以解释执行。
    peachpeach
        7
    peachpeach  
       25 天前
    你可以理解 qemu 就是个虚拟机, 虚拟各种 CPU 架构, 甚至可以虚拟嵌入式开发板
    rookiemaster
        8
    rookiemaster  
    OP
       25 天前
    应该是 qemu 会自动执行,把 qemu 卸载了就会正常报错了
    jim9606
        9
    jim9606  
       25 天前
    可能是利用了内核的 binfmt_misc 机制自动调用 qemu 运行了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3460 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 04:42 · PVG 12:42 · LAX 21:42 · JFK 00:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.