llvm pass的编写
可以参考一下官网,本文基于llvm11.0.1,也是参考官网来编写的。
https://releases.llvm.org/11.0.1/docs/WritingAnLLVMPass.html
在
/home/juziss/llvm-project-11.0.1.src/llvm/lib/Transforms
该目录下创建一个目录,这里就叫EncodeFunctionName
,然后在该目录创建.cpp文件和CMakeLists.txt。在
../llvm-project-11.0.1.src/llvm/lib/Transforms
目录的CMakeLists.txt加上add_subdirectory(EncodeFunctionName)
,括号里的内容为刚才创建的目录名在刚才创建的CMakeLists.txt添加
1 | add_llvm_library( LLVMEncodeFunctionName MODULE |
- 从示例Hello处copy示例进行修改
最终修改成的代码如下
1 | // |
- 直接在clion里build project
编写示例代码查看llvm pass效果
编写简单的c/cpp代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void hello_2(){
printf("hello 2");
}
void hello_1(){
printf("hello 1");
}
int main(){
printf("hello world!");
return 0;
}clang -emit-llvm -S ./hello_c.c
编译生成.ll文件
opt -load /home/juziss/llvm-project-11.0.1.src/llvm/cmake-build-debug/lib/LLVMEncodeFunctionName.so -encodeFuntionName hello_c.ll -o hello_c.bc
opt -load /home/juziss/llvm-project-11.0.1.src/llvm/cmake-build-debug/lib/LLVMEncodeFunctionName.so -encodeFuntionName /home/juziss/c_workspace/hello_c.ll -o hello_c.bc
clang hello_c.cb -o hello_c
用IDA打开编译生成后的文件
在llvm源码外编译llvm项目
官方文档位置 https://llvm.org/docs/CMake.html#cmake-out-of-source-pass
- 按照以下目录结构创建项目
1
2
3
4
5
6
7
8<project dir>/
|
CMakeLists.txt
<pass name>/
|
CMakeLists.txt
Pass.cpp
...
在项目根目录下的CMakeLists.txt文件添加如下内容
1
2
3
4
5
6find_package(LLVM REQUIRED CONFIG)
add_definitions(${LLVM_DEFINITIONS})
include_directories(${LLVM_INCLUDE_DIRS})
add_subdirectory(<pass name>)在pass的目录里的CMakeLists.txt添加这行命令
在
<project dir>/CMakeLists.txt
(after find_package(LLVM …))添加如下命令
1 | list(APPEND CMAKE_MODULE_PATH "${LLVM_CMAKE_DIR}") |
- 在
<project dir>/<pass name>/CMakeLists.txt
下添加如下命令1
2
3add_llvm_library(LLVMPassname MODULE
Pass.cpp
)
把llvm源码外创建的pass项目添加到llvm源码目录下(可选项)
复制
目录 到 /lib/Transform目录下。 .添加
add_subdirectory(<pass name>)
到<LLVM root>/lib/Transform/CMakeLists.txt
下。用clion打开该项目
配置好cmake之后会报错,按报错的内容来进行项目修改即可
编译一个带我们编写的pass的llvm()
在
<LLVM root>/include/Transforms
下创建与<LLVM root>/lib/Transforms
创建的目录一致。在该目录下创建.h文件,该.h文件是为了创建刚才在
<LLVM root>/lib/Transforms
创建的.cpp文件的那个类能自由通过引入.h文件来创建类。
然后再源文件里引入该.h文件,并实现该函数。
在
<LLVM root>/lib/Transforms/IPO/PassManageBuilder.cpp
添加如下代码
并在
<LLVM root>/lib/Transforms/EncodeFunctionName/
创建LLVMBuild.txt
在
<LLVM root>/lib/Transforms/EncodeFunctionName/
下的CMakeLists.txt
当中添加如下内容1
2
3ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/Transforms
${LLVM_MAIN_INCLUDE_DIR}/llvm/Transforms/EncodeFunctionName在以下文件添加EncodeFunctionName
编译
出现截图的.a文件就可以了~
附:EncodeFunctionName的CMakeLists.txt如下所示
1 | add_llvm_library( LLVMEncodeFunctionName |
注意,Module是删掉了!!!