注册

iOS底层探索开发 必不可少的 clang插件

Clang插件

LLVM下载

由于国内的网络限制,我们需要借助镜像下载LLVM的源码

https://mirror.tuna.tsinghua.edu.cn/help/llvm/

  • 下载llvm项目

git clone https://mirrors.tuna.tsinghua.edu.cn/git/llvm/llvm.git

  • 在LLVM的tools目录下下载Clang

cd llvm/tools
git clone https://mirrors.tuna.tsinghua.edu.cn/git/llvm/clang.git

  • 在 LLVM 的 projects 目录下下载 compiler-rt, libcxx, libcxxabi

cd ../projects
git clone https://mirrors.tuna.tsinghua.edu.cn/git/llvm/compiler-rt.g it
git clone https://mirrors.tuna.tsinghua.edu.cn/git/llvm/libcxx.git
git clone https://mirrors.tuna.tsinghua.edu.cn/git/llvm/libcxxabi.git

  • 在Clang的tools下安装extra工具

cd ../tools/clang/tools
git clone https://mirrors.tuna.tsinghua.edu.cn/git/LLvm/cLang-tooLs-e xtra.git

LLVM编译

由于最新的LLVM只支持c make来编译了,我们还需要安装c make。

安装cmake

  • 查看brew是否安装cmake如果有就跳过下面步骤

brew list

  • 通过brew安装cmake

brew install cmake

编译LLVM

通过xcode编译LLVM

  • cmake编译成Xcode项目

mkdir build_xcode
cd build_xcode
cmake -G Xcode ../llvm

  • 使用Xcode编译Clang。
    • 选择自动创建Schemes


f677225b7f9353710b676218876368a4.png6b7d5f73b7da089263770fcb6bead93d.png780a77ad77bf6930a20816dd12cbe3ce.png332c03e29741c0df1df147844997f96d.pngeaf7832015fbd085f3e43c08d73b635d.png

  • 在HKPlugin目录下新建一个名为HKPlugin.cpp的文件和CMakeLists.txt的文件。在CMakeLists.txt中写上

add_llvm_library( HKPlugin MODULE BUILDTREE_ONLY
HKPlugin.cpp
)
接下来利用cmake重新生成一下Xcode项目,在build_xcode中cmake -g Xcode ../llvm

  • 最后可以在LLVM的Xcode项目中可以看到Loadable modules目录下有自己 的Plugin目录了。我们可以在里面编写插件代码。
85812faaccba45e4bb37687a91839954.png

添加下自己的插件,等下编译

#include <iostream>
#include "clang/AST/AST.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
using namespace clang;
using namespace std;
using namespace llvm;
using namespace clang::ast_matchers;

namespace HKPlugin {
class HKConsumer: public ASTConsumer {
public:
//解析一个顶级的声明就回调一次
bool HandleTopLevelDecl(DeclGroupRef D) {
cout<<"正在解析..."<<endl;
return true;
}

//整个文件都解析完成的回调
void HandleTranslationUnit(ASTContext &Ctx) {
cout << "文件解析完毕" << endl;
}
};

//继承PluginASTAction 实现我们自定义的Action
class HKASTAction:public PluginASTAction{
public:
//重写
bool ParseArgs(const CompilerInstance &CI, const std::vector<std::string> &arg){
return true;
}

std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
return unique_ptr<HKConsumer>(new HKConsumer);
}
};
}
//注册插件

static FrontendPluginRegistry::Add<HKPlugin::HKASTAction> HK("HKPlugin","this is HKPlugin");

先简单写些测试代码,然后编译生成dylib

8649627e43e6628731857d5319cdf668.png

int sum(int a);
int a;
int sum(int a){
int b = 10;
return 10 + b;
}
int sum2(int a,int b){
int c = 10;
return a + b + c;
}


写些测试代码

自己编译的 clang 文件路径 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/ -Xclang -load -Xclang 自己编译的 clang 文件路径 -Xclang -add-plugin -Xclang 自己编译的 clang 文件路径 -c 自己编译的 clang 文件路径

例: /Users/xxx/Desktop/LLVMENV/build_xcode/Debug/bin/clang -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/ -Xclang -load -Xclang /Users/xxx/Desktop/LLVMENV/build_xcode/Debug/lib/HKPlugin.dylib -Xclang -add-plugin -Xclang HKPlugin -c ./hello.m
注:iPhoneSimulator13.5.sdk换成自己目录下的sdk版本


正在解析...
正在解析...
正在解析...
正在解析...
文件解析完毕

现在在viewController中声明属性

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic, strong) NSDictionary* dict;
@property(nonatomic, strong) NSArray* arr;
@property(nonatomic, strong) NSString* name;
@end

@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
@end

然后通过语法分析,查看抽象语法树

clang -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk -fmodules -fsyntax-only -Xclang -ast-dump ViewController.m




TranslationUnitDecl 0x7f9e57000008 <<invalid sloc>> <invalid sloc> <undeserialized declarations>
|-TypedefDecl 0x7f9e570008a0 <<invalid sloc>> <invalid sloc> implicit __int128_t '__int128'
| `-BuiltinType 0x7f9e570005a0 '__int128'
|-TypedefDecl 0x7f9e57000910 <<invalid sloc>> <invalid sloc> implicit __uint128_t 'unsigned __int128'
| `-BuiltinType 0x7f9e570005c0 'unsigned __int128'
|-TypedefDecl 0x7f9e570009b0 <<invalid sloc>> <invalid sloc> implicit SEL 'SEL *'
| `-PointerType 0x7f9e57000970 'SEL *' imported
| `-BuiltinType 0x7f9e57000800 'SEL'
|-TypedefDecl 0x7f9e57000a98 <<invalid sloc>> <invalid sloc> implicit id 'id'
| `-ObjCObjectPointerType 0x7f9e57000a40 'id' imported
| `-ObjCObjectType 0x7f9e57000a10 'id' imported
|-TypedefDecl 0x7f9e57000b78 <<invalid sloc>> <invalid sloc> implicit Class 'Class'
| `-ObjCObjectPointerType 0x7f9e57000b20 'Class' imported
| `-ObjCObjectType 0x7f9e57000af0 'Class' imported
|-ObjCInterfaceDecl 0x7f9e57000bd0 <<invalid sloc>> <invalid sloc> implicit Protocol
|-TypedefDecl 0x7f9e57000f48 <<invalid sloc>> <invalid sloc> implicit __NSConstantString 'struct __NSConstantString_tag'
| `-RecordType 0x7f9e57000d40 'struct __NSConstantString_tag'
| `-Record 0x7f9e57000ca0 '__NSConstantString_tag'
|-TypedefDecl 0x7f9e58008400 <<invalid sloc>> <invalid sloc> implicit __builtin_ms_va_list 'char *'
| `-PointerType 0x7f9e57000fa0 'char *'
| `-BuiltinType 0x7f9e570000a0 'char'
|-TypedefDecl 0x7f9e580086e8 <<invalid sloc>> <invalid sloc> implicit __builtin_va_list 'struct __va_list_tag [1]'
| `-ConstantArrayType 0x7f9e58008690 'struct __va_list_tag [1]' 1
| `-RecordType 0x7f9e580084f0 'struct __va_list_tag'
| `-Record 0x7f9e58008458 '__va_list_tag'
|-ImportDecl 0x7f9e5852bc18 <./ViewController.h:9:1> col:1 implicit UIKit
|-ObjCInterfaceDecl 0x7f9e58541e00 <line:11:1, line:14:2> line:11:12 ViewController
| |-super ObjCInterface 0x7f9e5852be78 'UIViewController'
| `-ObjCImplementation 0x7f9e5857f460 'ViewController'
|-ObjCCategoryDecl 0x7f9e58541f30 <ViewController.m:11:1, line:15:2> line:11:12
| |-ObjCInterface 0x7f9e58541e00 'ViewController'
| |-ObjCPropertyDecl 0x7f9e58548a00 <line:12:1, col:44> col:44 dict 'NSDictionary *' readwrite nonatomic strong
| |-ObjCMethodDecl 0x7f9e58548a80 <col:44> col:44 implicit - dict 'NSDictionary *'
| |-ObjCMethodDecl 0x7f9e58548c28 <col:44> col:44 implicit - setDict: 'void'
| | `-ParmVarDecl 0x7f9e58548cb0 <col:44> col:44 dict 'NSDictionary *'
| |-ObjCPropertyDecl 0x7f9e58551cd0 <line:13:1, col:39> col:39 arr 'NSArray *' readwrite nonatomic strong
| |-ObjCMethodDecl 0x7f9e58551d50 <col:39> col:39 implicit - arr 'NSArray *'
| |-ObjCMethodDecl 0x7f9e58551ea8 <col:39> col:39 implicit - setArr: 'void'
| | `-ParmVarDecl 0x7f9e58551f30 <col:39> col:39 arr 'NSArray *'
| |-ObjCPropertyDecl 0x7f9e585650d0 <line:14:1, col:40> col:40 name 'NSString *' readwrite nonatomic strong
| |-ObjCMethodDecl 0x7f9e58565150 <col:40> col:40 implicit - name 'NSString *'
| `-ObjCMethodDecl 0x7f9e585652a8 <col:40> col:40 implicit - setName: 'void'
| `-ParmVarDecl 0x7f9e58565330 <col:40> col:40 name 'NSString *'
`-ObjCImplementationDecl 0x7f9e5857f460 <line:17:1, line:25:1> line:17:17 ViewController
|-ObjCInterface 0x7f9e58541e00 'ViewController'
|-ObjCMethodDecl 0x7f9e5857f580 <line:19:1, line:22:1> line:19:1 - viewDidLoad 'void'
| |-ImplicitParamDecl 0x7f9e585c9c08 <<invalid sloc>> <invalid sloc> implicit self 'ViewController *'
| |-ImplicitParamDecl 0x7f9e585c9c70 <<invalid sloc>> <invalid sloc> implicit _cmd 'SEL':'SEL *'
| `-CompoundStmt 0x7f9e585cf2b8 <col:21, line:22:1>
| `-ObjCMessageExpr 0x7f9e585c9cd8 <line:20:5, col:23> 'void' selector=viewDidLoad super (instance)
|-ObjCIvarDecl 0x7f9e585c8168 <line:12:44> col:44 implicit _dict 'NSDictionary *' synthesize private
|-ObjCPropertyImplDecl 0x7f9e585c81c8 <<invalid sloc>, col:44> <invalid sloc> dict synthesize
| |-ObjCProperty 0x7f9e58548a00 'dict'
| `-ObjCIvar 0x7f9e585c8168 '_dict' 'NSDictionary *'
|-ObjCIvarDecl 0x7f9e585c84e0 <line:13:39> col:39 implicit _arr 'NSArray *' synthesize private
|-ObjCPropertyImplDecl 0x7f9e585c8540 <<invalid sloc>, col:39> <invalid sloc> arr synthesize
| |-ObjCProperty 0x7f9e58551cd0 'arr'
| `-ObjCIvar 0x7f9e585c84e0 '_arr' 'NSArray *'
|-ObjCIvarDecl 0x7f9e585c9890 <line:14:40> col:40 implicit _name 'NSString *' synthesize private
|-ObjCPropertyImplDecl 0x7f9e585c98f0 <<invalid sloc>, col:40> <invalid sloc> name synthesize
| |-ObjCProperty 0x7f9e585650d0 'name'
| `-ObjCIvar 0x7f9e585c9890 '_name' 'NSString *'
|-ObjCMethodDecl 0x7f9e585c82f8 <line:12:44> col:44 implicit - dict 'NSDictionary *'
|-ObjCMethodDecl 0x7f9e585c8450 <col:44> col:44 implicit - setDict: 'void'
| `-ParmVarDecl 0x7f9e58548cb0 <col:44> col:44 dict 'NSDictionary *'
|-ObjCMethodDecl 0x7f9e585c8670 <line:13:39> col:39 implicit - arr 'NSArray *'
|-ObjCMethodDecl 0x7f9e585c9800 <col:39> col:39 implicit - setArr: 'void'
| `-ParmVarDecl 0x7f9e58551f30 <col:39> col:39 arr 'NSArray *'
|-ObjCMethodDecl 0x7f9e585c9a20 <line:14:40> col:40 implicit - name 'NSString *'
`-ObjCMethodDecl 0x7f9e585c9b78 <col:40> col:40 implicit - setName: 'void'
`-ParmVarDecl 0x7f9e58565330 <col:40> col:40 name 'NSString *'

我们可以找到其中的属性节点和他的修饰符

| |-ObjCPropertyDecl 0x7f9e585650d0 <line:14:1, col:40> col:40 name 'NSString *' readwrite nonatomic strong
完整代码如下

#include <iostream>
#include "clang/AST/AST.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
using namespace clang;
using namespace std;
using namespace llvm;
using namespace clang::ast_matchers;

namespace HKPlugin {

class HKMatchCallback:public MatchFinder::MatchCallback{
private:
CompilerInstance &CI;

bool isUserSourceCode(const string fileName){
if (fileName.empty()) return false;
//非xcode中的源码都认为是用户的
if(fileName.find("/Applications/Xcode.app/") == 0)return false;
return true;
}

//判断是否应该用copy修饰
bool isShouldUseCopy(const string typeStr){
if (typeStr.find("NSString") != string::npos ||
typeStr.find("NSArray") != string::npos ||
typeStr.find("NSDictionary") != string::npos ) {
return true;
}
return false;
}
public:
HKMatchCallback(CompilerInstance &CI):CI(CI){}
void run(const MatchFinder::MatchResult &Result) {
//通过Result获得节点
//之前绑定的标识
const ObjCPropertyDecl * propertyDecl = Result.Nodes.getNodeAs<ObjCPropertyDecl>("objcPropertyDecl");


//获取文件名称
string fileName = CI.getSourceManager().getFilename(propertyDecl-> getSourceRange().getBegin()).str();

//判断节点有值并且是用户文件
if (propertyDecl && isUserSourceCode(fileName)) {
//节点类型转为字符串
string typeStr = propertyDecl->getType().getAsString();
//拿到及诶单的描述信息
ObjCPropertyDecl::PropertyAttributeKind attrKind = propertyDecl->getPropertyAttributes();
//判断应该使用copy但是没有使用copy
if (isShouldUseCopy(typeStr) && !(attrKind & clang::ObjCPropertyDecl::OBJC_PR_copy)) {
cout << typeStr << "应该用copy修饰!但你没有" << endl;
//诊断引擎
DiagnosticsEngine &diag = CI.getDiagnostics();
//Report 报告
diag.Report(propertyDecl->getBeginLoc(),diag.getCustomDiagID(DiagnosticsEngine::Warning, "--- %0 这个地方推荐使用copy"))<<typeStr
}
// cout<<"--拿到了:"<<typeStr<<"---属于文件:"<<fileName<<endl;

}
}
};

class HKConsumer: public ASTConsumer {
private:
//AST节点的查找过滤器
MatchFinder matcher;
HKMatchCallback callback;
public:
HKConsumer(CompilerInstance &CI):callback(CI){
//添加一个MatchFinder去匹配objcPropertyDecl节点
//回调在HKMatchCallback里面run方法

matcher.addMatcher(objcPropertyDecl().bind("objcPropertyDecl"), &callback);
}
//解析一个顶级的声明就回调一次
bool HandleTopLevelDecl(DeclGroupRef D) {
cout<<"正在解析..."<<endl;
return true;
}

//整个文件都解析完成的回调
void HandleTranslationUnit(ASTContext &Ctx) {
cout << "文件解析完毕" << endl;
matcher.matchAST(Ctx);//将语法树交给过滤器
}
};

//继承PluginASTAction 实现我们自定义的Action
class HKASTAction:public PluginASTAction{
public:
//重写
bool ParseArgs(const CompilerInstance &CI, const std::vector<std::string> &arg){
return true;
}

std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
//ASTConsumer是一个抽象类,这里返回一个自定义的类来继承
return unique_ptr<HKConsumer>(new HKConsumer(CI));
}
};
}
//注册插件

static FrontendPluginRegistry::Add<HKPlugin::HKASTAction> HK("HKPlugin","this is HKPlugin");

ac75de1196f57db230184e411b227765.png4c6a4cdfa9a5fefe750b5660a302889a.png017fa440f8d8539fac81618eeafeb98c.png2d35e402d3bccd8305dfb5900817b49f.png713b69ccdb5c9a3316b3bf393790c84d.png




作者:Mjs
链接:https://www.jianshu.com/p/d613d935662d



0 个评论

要回复文章请先登录注册