LLVM 如何在任何其他代码之前执行模块中的代码

LLVM how to execute code in a module before any other code

我想检测一些在我的模块中的任何其他代码之前执行的代码。

我想过在main函数的开头调用代码。但是并不总是有一个main函数或者它并不总是被命名为"main"。或者它是一个库,它甚至没有一个主要功能。

还有其他更聪明的方法吗?

您可以将想要 运行 的代码提前放入函数中,然后将该函数添加到 C 或 C++ 中的 llvm.global_ctors. This is the equivalent of using __attribute__((constructor))

要通过传递执行此操作,您可以使用 llvm::appendToGlobalCtors 函数,该函数在 llvm/Transforms/Utils/ModuleUtils.h 中声明。