将 llvm 生成的目标代码与 ld 链接起来

linking llvm produced object code with ld

我编写了一个小型编译器,它使用 llvm(通过 C++)生成目标文件(在 linux 系统中)。

当我link用gcc编译输出时,程序运行没问题:

myCompiler source.mylang -o objCode
gcc objCode -o program
./program #runs fine

但是如果我尝试使用 ld link 它,当我 运行 程序时会出现分段错误:

myCompiler source.mylang -o objCode
ld objCode -e main -o program   #ld does not print any error or warning.
./program #Segmentation fault (core dumped)

这里是编译器输出的llvm代码(使用myLlvmModule->print函数):

; ModuleID = 'entryPointModule'
source_filename = "entryPointModule"

define i32 @main() {
entry:
  %x = alloca i32
  store i32 55, i32* %x
  ret i32 0
  ret i32 0
}

为什么 ld 失败,而 gcc 成功? 我认为在编写编译器之后,唯一需要的步骤就是调用 linker。是否需要其他编译器(例如 gcc)?

如果是,为什么? 如果没有,我怎么能让 ld 工作?

编辑: 工作二进制文件的 readelf -d:

Dynamic section at offset 0xe00 contains 24 entries:
  Tag        Type                         Name/Value
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
 0x000000000000000c (INIT)               0x4b8
 0x000000000000000d (FINI)               0x684
 0x0000000000000019 (INIT_ARRAY)         0x200df0
 0x000000000000001b (INIT_ARRAYSZ)       8 (bytes)
 0x000000000000001a (FINI_ARRAY)         0x200df8
 0x000000000000001c (FINI_ARRAYSZ)       8 (bytes)
 0x000000006ffffef5 (GNU_HASH)           0x298
 0x0000000000000005 (STRTAB)             0x348
 0x0000000000000006 (SYMTAB)             0x2b8
 0x000000000000000a (STRSZ)              125 (bytes)
 0x000000000000000b (SYMENT)             24 (bytes)
 0x0000000000000015 (DEBUG)              0x0
 0x0000000000000003 (PLTGOT)             0x200fc0
 0x0000000000000007 (RELA)               0x3f8
 0x0000000000000008 (RELASZ)             192 (bytes)
 0x0000000000000009 (RELAENT)            24 (bytes)
 0x000000000000001e (FLAGS)              BIND_NOW
 0x000000006ffffffb (FLAGS_1)            Flags: NOW PIE
 0x000000006ffffffe (VERNEED)            0x3d8
 0x000000006fffffff (VERNEEDNUM)         1
 0x000000006ffffff0 (VERSYM)             0x3c6
 0x000000006ffffff9 (RELACOUNT)          3
 0x0000000000000000 (NULL)               0x0

对损坏的二进制文件使用相同的命令:

There is no dynamic section in this file.

您的入口点试图 return 到堆栈上不存在的 return 地址,这就是程序跳转到地址零的原因。

程序的入口点不应return。它必须通过调用 _exit(或相关的系统调用)来终止进程。