├── .DS_Store ├── README.md └── clang-obfuscator ├── CMakeLists.txt ├── obfuscator.cpp └── obfuscator.h /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fenglh/ObjcClassNameObfuscator/a1b112339207f8a1febc66cd33dad236ddd24d1a/.DS_Store -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ObjcClassNameObfuscator 2 | ”基于LLVM的Objective-C代码混淆(六) 核心代码编写 “ 中的源码。 3 | 4 | 详见文章:www.banmalu.top/llvm-06/ 5 | -------------------------------------------------------------------------------- /clang-obfuscator/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(LLVM_LINK_COMPONENTS 2 | Support 3 | ) 4 | 5 | #对应的cpp文件都要加进来 6 | add_clang_executable(ClangObfuscator 7 | obfuscator.cpp 8 | ) 9 | 10 | # 后面会使用到这些库 11 | target_link_libraries(ClangObfuscator 12 | PRIVATE 13 | clangAST 14 | clangBasic 15 | clangDriver 16 | clangFormat 17 | clangLex 18 | clangParse 19 | clangSema 20 | clangFrontend 21 | clangTooling 22 | clangToolingCore 23 | clangRewrite 24 | clangRewriteFrontend 25 | ) 26 | 27 | if(UNIX) 28 | set(CLANGXX_LINK_OR_COPY create_symlink) 29 | else() 30 | set(CLANGXX_LINK_OR_COPY copy) 31 | endif() 32 | -------------------------------------------------------------------------------- /clang-obfuscator/obfuscator.cpp: -------------------------------------------------------------------------------- 1 | 2 | // 3 | // obfuscator.cpp 4 | // obfuscator 5 | // 6 | // Created by 冯立海/335418265@qq.com on 2020/2/1. 7 | // Copyright © 2020 fenglh. All rights reserved. 8 | // 9 | 10 | #include "clang/Frontend/FrontendActions.h" 11 | #include "clang/Tooling/CommonOptionsParser.h" 12 | #include "clang/Tooling/Tooling.h" 13 | #include "clang/AST/ASTConsumer.h" 14 | #include "clang/ASTMatchers/ASTMatchFinder.h" 15 | #include "clang/ASTMatchers/ASTMatchers.h" 16 | #include "clang/Frontend/CompilerInstance.h" 17 | #include "clang/Rewrite/Core/Rewriter.h" 18 | #include 19 | 20 | using namespace std; 21 | using namespace llvm; 22 | using namespace clang; 23 | using namespace clang::tooling; 24 | using namespace clang::ast_matchers; 25 | 26 | static cl::OptionCategory ObfOptionCategory("ObfOptionCategory"); 27 | 28 | 29 | 30 | // 匹配回调 31 | class MatchCallbackHandler : public MatchFinder::MatchCallback { 32 | public: 33 | //构造函数 34 | MatchCallbackHandler(Rewriter &aRewriter, CompilerInstance *aCompilerInstance):rewriter(aRewriter), compilerInstance(aCompilerInstance) {} 35 | virtual void run(const MatchFinder::MatchResult &Result) { 36 | 37 | const ObjCInterfaceDecl *interfaceDecl = Result.Nodes.getNodeAs("objcInterfaceDecl"); 38 | const ObjCImplementationDecl *implDecl = Result.Nodes.getNodeAs("objcImplementationDecl"); 39 | const ObjCCategoryDecl *categoryDecl = Result.Nodes.getNodeAs("objcCategoryDecl"); 40 | const ObjCCategoryImplDecl *categoryImplDecl = Result.Nodes.getNodeAs("objcCategoryImplDecl"); 41 | const VarDecl *varDecl = Result.Nodes.getNodeAs("varDecl"); 42 | const ObjCIvarDecl *objcIvarDecl = Result.Nodes.getNodeAs("objcIvarDecl"); 43 | const ObjCPropertyDecl *objcPropertyDecl = Result.Nodes.getNodeAs("objcPropertyDecl"); 44 | const ObjCMethodDecl *methodDecl = Result.Nodes.getNodeAs("objcMethodDecl"); 45 | const ObjCMessageExpr *messageExpr = Result.Nodes.getNodeAs("objcMessageExpr"); 46 | const ExplicitCastExpr *explicitCastExpr = Result.Nodes.getNodeAs("explicitCastExpr"); 47 | const clang::StringLiteral *stringLiteral = Result.Nodes.getNodeAs("stringLiteral"); 48 | const TypedefDecl *typedefDecl = Result.Nodes.getNodeAs("typedefDecl"); 49 | 50 | 51 | 52 | if (isUserSourceDecl(interfaceDecl)) handleInterfaceDecl(interfaceDecl); 53 | if (isUserSourceDecl(implDecl)) handleImplementationDecl(implDecl); 54 | if (isUserSourceDecl(categoryDecl)) handleCategoryDecl(categoryDecl); 55 | if (isUserSourceDecl(categoryImplDecl)) handleCategoryImplDecl(categoryImplDecl); 56 | if (isUserSourceDecl(explicitCastExpr)) handleExplicitCastExpr(explicitCastExpr); 57 | if (isUserSourceDecl(varDecl)) handleVarDecl(varDecl); 58 | if (isUserSourceDecl(objcIvarDecl)) handleObjcIVarDecl(objcIvarDecl); 59 | if (isUserSourceDecl(objcPropertyDecl)) handleObjcPropertyDecl(objcPropertyDecl); 60 | if (isUserSourceDecl(methodDecl)) handleMethodDecl(methodDecl); 61 | if (isUserSourceDecl(messageExpr)) handleMessageExpr(messageExpr); 62 | if (stringLiteral) handleStringLiteral(stringLiteral); 63 | if (isUserSourceDecl(typedefDecl)) handleTypedefDecl(typedefDecl); 64 | 65 | } 66 | 67 | void ReplaceText(SourceLocation Start, unsigned OrigLength,StringRef NewStr){ 68 | if (compilerInstance->getSourceManager().isMacroBodyExpansion(Start)) { 69 | Start = compilerInstance->getSourceManager().getSpellingLoc(Start); 70 | } 71 | rewriter.ReplaceText(Start, OrigLength, NewStr); 72 | } 73 | 74 | //需要混淆的类名 75 | bool isNeedObfuscateClassName(string name) { 76 | return name == "DemoViewController"; 77 | } 78 | 79 | string getNewClassName(string oldName){ 80 | return "NewViewController"; 81 | } 82 | 83 | //处理类声明 84 | void handleInterfaceDecl(const ObjCInterfaceDecl *interfaceDecl){ 85 | string oldClassName = interfaceDecl->getNameAsString(); 86 | if (isNeedObfuscateClassName(oldClassName)) { 87 | string newClassName = getNewClassName(oldClassName); 88 | SourceLocation loc = interfaceDecl->getLocation(); 89 | ReplaceText(loc , oldClassName.length(), getNewClassName(oldClassName)); 90 | cout << "类声明:" << oldClassName << "替换为:" << newClassName<< endl; 91 | } 92 | } 93 | //处理类定义 94 | void handleImplementationDecl(const ObjCImplementationDecl *objcImplementationDecl){ 95 | string oldClassName = objcImplementationDecl->getNameAsString(); 96 | if (isNeedObfuscateClassName(oldClassName)) { 97 | string newClassName = getNewClassName(oldClassName); 98 | SourceLocation loc = objcImplementationDecl->getLocation(); 99 | ReplaceText(loc , oldClassName.length(), getNewClassName(oldClassName)); 100 | cout << fileNameOfNode(objcImplementationDecl)<< ":类定义:" << oldClassName << "替换为:" << newClassName << endl; 101 | } 102 | 103 | } 104 | //处理分类声明 105 | void handleCategoryDecl(const ObjCCategoryDecl *objcCategoryDecl){ 106 | string oldClassName = objcCategoryDecl->getClassInterface()->getNameAsString(); 107 | 108 | if (isNeedObfuscateClassName(oldClassName)) { 109 | string newClassName = getNewClassName(oldClassName); 110 | SourceLocation loc = objcCategoryDecl->getLocation(); 111 | ReplaceText(loc , oldClassName.length(), getNewClassName(oldClassName)); 112 | cout << fileNameOfNode(objcCategoryDecl)<< ":分类声明:" << oldClassName << "替换为:" << newClassName << endl; 113 | } 114 | } 115 | //处理分类定义 116 | void handleCategoryImplDecl(const ObjCCategoryImplDecl *objcCategoryImplDecl){ 117 | string oldClassName = objcCategoryImplDecl->getNameAsString(); 118 | if (isNeedObfuscateClassName(oldClassName)) { 119 | string newClassName = getNewClassName(oldClassName); 120 | SourceLocation loc = objcCategoryImplDecl->getLocation(); 121 | ReplaceText(loc , oldClassName.length(), getNewClassName(oldClassName)); 122 | cout << fileNameOfNode(objcCategoryImplDecl)<< ":分类定义:" << oldClassName << "替换为:" << newClassName<< endl; 123 | } 124 | 125 | } 126 | 127 | 128 | //处理消息表达式 129 | void handleMessageExpr(const ObjCMessageExpr *messageExpr){ 130 | if (messageExpr->isClassMessage()) { //是类方法 131 | const ObjCInterfaceDecl *objcInterfaceDecl = messageExpr->getReceiverInterface(); 132 | if (isUserSourceDecl(objcInterfaceDecl)) { 133 | string oldClassName = objcInterfaceDecl->getNameAsString(); 134 | if (isNeedObfuscateClassName(oldClassName)) { 135 | string newClassName = getNewClassName(oldClassName); 136 | SourceLocation loc = messageExpr->getClassReceiverTypeInfo()->getTypeLoc().getBeginLoc(); 137 | ReplaceText(loc, oldClassName.length(), newClassName); 138 | cout << "消息表达式:" << "[" << oldClassName << " " << messageExpr->getSelector().getAsString() << "]" "替换为:" << "[" << newClassName << " " << messageExpr->getSelector().getAsString() << "]" << endl; 139 | } 140 | } 141 | 142 | } 143 | } 144 | 145 | 146 | //处理显式转换 147 | void handleExplicitCastExpr(const ExplicitCastExpr *explicitCastExpr){ 148 | 149 | // explicitCastExpr->getd 150 | QualType qualType = explicitCastExpr->getTypeAsWritten(); 151 | SourceLocation typeBeginLoc = explicitCastExpr->getTypeInfoAsWritten()->getTypeLoc().getBeginLoc(); 152 | SourceLocation typeEndLoc = explicitCastExpr->getTypeInfoAsWritten()->getTypeLoc().getEndLoc(); 153 | //宏替换后,是否会处理多余的空格? 154 | bool success = recursiveHandleQualType(typeBeginLoc,typeEndLoc,qualType); 155 | 156 | 157 | if (success) { 158 | string rewriteString = rewriter.getRewrittenText(SourceRange(explicitCastExpr->getBeginLoc(), explicitCastExpr->getExprLoc())); 159 | cout << "显式转换:"<< qualType.getAsString() << "替换为:" << rewriteString << endl; 160 | } 161 | 162 | 163 | } 164 | 165 | //处理字符串 166 | void handleStringLiteral(const clang::StringLiteral *stringLiteral){ 167 | clang::StringRef content = stringLiteral->getString(); 168 | if (isNeedObfuscateClassName(content)) { 169 | SourceLocation loc = stringLiteral->getBeginLoc();//loc的位置在 170 | string newClassName = getNewClassName(content); 171 | ReplaceText(loc.getLocWithOffset(-1), content.str().length()+2, newClassName); 172 | cout << "字符串:" << content.str() << " 替换为:" << newClassName << endl; 173 | } 174 | } 175 | 176 | //处理typeDef 177 | void handleTypedefDecl(const TypedefDecl *typedefDecl){ 178 | //underlyingType 179 | QualType type = typedefDecl->getUnderlyingType(); 180 | recursiveHandleQualType(typedefDecl->getBeginLoc(), typedefDecl->getEndLoc(), type); 181 | } 182 | 183 | //处理变量声明或者定义 184 | void handleVarDecl(const VarDecl *varDecl){ 185 | 186 | ////隐式实现的,并非在显示的写源码中则不作处理。例如:编译器会实现 property 的实例变量 187 | if (varDecl->isImplicit()) { 188 | return; 189 | } 190 | QualType qualType = varDecl->getType(); 191 | //隐式实现的Decl ,则varDecl->getTypeSourceInfo() 为NULL 192 | if (qualType.isNull()) { 193 | return; 194 | } 195 | 196 | TypeSourceInfo *typeSourceInfo = varDecl->getTypeSourceInfo(); 197 | //即使varDecl->isImplicit() == false ,typeSourceInfo 也会为NULL,所以下面再次进行NULL判断 198 | if (!typeSourceInfo) { 199 | return; 200 | } 201 | SourceLocation typeBeginLoc = typeSourceInfo->getTypeLoc().getBeginLoc(); 202 | SourceLocation typeEndLoc = typeSourceInfo->getTypeLoc().getEndLoc(); 203 | bool success = recursiveHandleQualType(typeBeginLoc,typeEndLoc,qualType); 204 | if(success){ 205 | SourceLocation beginLoc = compilerInstance->getSourceManager().getSpellingLoc(varDecl->getBeginLoc()); 206 | SourceLocation endLoc = compilerInstance->getSourceManager().getSpellingLoc(varDecl->getEndLoc()); 207 | string rewriteString = rewriter.getRewrittenText(SourceRange(beginLoc, endLoc)); 208 | cout << "变量声明:" << qualType.getAsString() << " " << varDecl->getNameAsString() << "替换为:" << rewriteString << endl; 209 | } 210 | 211 | } 212 | //处理实例变量 213 | void handleObjcIVarDecl(const ObjCIvarDecl *objcIvarDecl){ 214 | ////隐式实现的,并非在显示的写源码中则不作处理。例如:编译器会实现 property 的实例变量 215 | if (objcIvarDecl->isImplicit()) { 216 | return; 217 | } 218 | QualType qualType = objcIvarDecl->getType(); 219 | //隐式实现的Decl ,则varDecl->getTypeSourceInfo() 为NULL 220 | if (qualType.isNull()) { 221 | return; 222 | } 223 | TypeSourceInfo *typeSourceInfo = objcIvarDecl->getTypeSourceInfo(); 224 | //即使varDecl->isImplicit() == false ,typeSourceInfo 也会为NULL,所以下面再次进行NULL判断 225 | if (!typeSourceInfo) { 226 | return; 227 | } 228 | SourceLocation typeBeginLoc = typeSourceInfo->getTypeLoc().getBeginLoc(); 229 | SourceLocation typeEndLoc = typeSourceInfo->getTypeLoc().getEndLoc(); 230 | bool success = recursiveHandleQualType(typeBeginLoc,typeEndLoc,qualType); 231 | if(success){ 232 | SourceLocation beginLoc = compilerInstance->getSourceManager().getSpellingLoc(objcIvarDecl->getBeginLoc()); 233 | SourceLocation endLoc = compilerInstance->getSourceManager().getSpellingLoc(objcIvarDecl->getEndLoc()); 234 | string rewriteString = rewriter.getRewrittenText(SourceRange(beginLoc, endLoc)); 235 | cout << "变量声明:" << qualType.getAsString() << " " << objcIvarDecl->getNameAsString() << "替换为:" << rewriteString << endl; 236 | } 237 | 238 | } 239 | //处理属性 240 | void handleObjcPropertyDecl(const ObjCPropertyDecl *objcPropertyDecl){ 241 | 242 | QualType qualType = objcPropertyDecl->getType(); 243 | TypeSourceInfo *typeSourceInfo = objcPropertyDecl->getTypeSourceInfo(); 244 | if (!typeSourceInfo) { 245 | return; 246 | } 247 | SourceLocation typeBeginLoc = typeSourceInfo->getTypeLoc().getBeginLoc(); 248 | SourceLocation typeEndLoc = typeSourceInfo->getTypeLoc().getEndLoc(); 249 | bool success = recursiveHandleQualType(typeBeginLoc,typeEndLoc,qualType); 250 | if(success){ 251 | SourceLocation beginLoc = compilerInstance->getSourceManager().getSpellingLoc(objcPropertyDecl->getBeginLoc()); 252 | SourceLocation endLoc = compilerInstance->getSourceManager().getSpellingLoc(objcPropertyDecl->getEndLoc()); 253 | string rewriteString = rewriter.getRewrittenText(SourceRange(beginLoc, endLoc)); 254 | cout << "属性声明:" << qualType.getAsString() << " " << objcPropertyDecl->getNameAsString() << "替换为:" << rewriteString << endl; 255 | } 256 | } 257 | 258 | 259 | //处理方法声明或者定义 260 | void handleMethodDecl(const ObjCMethodDecl *methodDecl){ 261 | 262 | //隐式实现的,并非在显示的写源码中则不作处理。例如:编译器会实现 property 的getter 和 setter 方法 263 | if (methodDecl->isImplicit()) { 264 | return; 265 | } 266 | 267 | //1. 获取返回类型 268 | QualType qualType = methodDecl->getReturnType(); 269 | if (qualType.isNull()) { 270 | return; 271 | } 272 | TypeSourceInfo *typeSourceInfo = methodDecl->getReturnTypeSourceInfo(); 273 | if (!typeSourceInfo) { 274 | return; 275 | } 276 | //2. 获取type的开始和结束位置,注:当methodDecl是隐式实现的,methodDecl->getReturnTypeSourceInfo()->getTypeLoc() 为NULL 277 | SourceLocation typeBeginLoc = typeSourceInfo->getTypeLoc().getBeginLoc(); 278 | SourceLocation typeEndLoc = typeSourceInfo->getTypeLoc().getEndLoc(); 279 | //3. 递归处理返回类型 280 | bool handleReturnTypeSuccess = recursiveHandleQualType(typeBeginLoc, typeEndLoc, qualType); 281 | //4. 获取参数列表 282 | ArrayRef params = methodDecl->parameters(); 283 | bool handleParamersTypeSuccess = false; 284 | //5. 遍历参数列表 285 | for(ArrayRef< ParmVarDecl * >::iterator i = params.begin(), e = params.end(); i != e; i++){ 286 | ParmVarDecl *p = *i; 287 | //6. 获取参数的类型 288 | QualType type = p->getType(); 289 | //7. 递归处理参数类型 290 | handleParamersTypeSuccess = handleParamersTypeSuccess || recursiveHandleQualType(p->getBeginLoc(), p->getEndLoc(), type); 291 | } 292 | 293 | if (handleReturnTypeSuccess || handleParamersTypeSuccess) { 294 | //-1 是去掉左花括号"{" 295 | string rewriteString = rewriter.getRewrittenText(SourceRange(methodDecl->getBeginLoc(), methodDecl->getDeclaratorEndLoc().getLocWithOffset(-1))); 296 | cout << "方法声明/定义:" << getMethodDeclStringOfMethoddecl(methodDecl) << "替换为:"<< rewriteString<< endl; 297 | } 298 | 299 | 300 | 301 | } 302 | 303 | //递归处理, ture 表示处理成功,false 表示失败,或者无需处理 304 | bool recursiveHandleQualType(SourceLocation start , SourceLocation end, QualType type) { 305 | 306 | if (start.isInvalid() || end.isInvalid() ) { 307 | return false; 308 | } 309 | 310 | bool success = false; 311 | SourceLocation slideLoc = start; 312 | if (isa(type)) { //ObjCObjectPointerType类型 313 | const ObjCObjectPointerType *pointerType = type->getAs(); //指针类型 314 | const ObjCInterfaceDecl *IDecl = pointerType->getInterfaceDecl(); 315 | if (isUserSourceDecl(IDecl) && isNeedObfuscateClassName(IDecl->getNameAsString())) { //是用户源码,并且类名是 316 | string oldClassName = IDecl->getNameAsString(); 317 | string newClassName = getNewClassName(oldClassName); 318 | //获取类型声明的字符数据的开始指针 319 | const char* startBuffer = compilerInstance->getSourceManager().getCharacterData(slideLoc); 320 | //获取类型声明的字符数据的结束指针 321 | const char* endBuffer = compilerInstance->getSourceManager().getCharacterData(end); 322 | //两个指针的偏移量 323 | int offset = endBuffer - startBuffer; 324 | //获取雷声声明的字符窜 例如:NSSArray 325 | string originTypeDefineStr(startBuffer, offset); 326 | 327 | //查找该字符串中包含oldClassName 字符串的位置 328 | int index = originTypeDefineStr.find(oldClassName, 0); 329 | 330 | slideLoc =slideLoc .getLocWithOffset(index); 331 | ReplaceText(slideLoc, oldClassName.length(), newClassName); 332 | slideLoc = slideLoc.getLocWithOffset(index+oldClassName.length()); 333 | success = true; 334 | } 335 | 336 | if (pointerType->isSpecialized()) { //有类型参数 337 | const ArrayRef< QualType > params = pointerType->getTypeArgs(); 338 | unsigned index = 0; 339 | for(ArrayRef< QualType >::iterator i = params.begin(), e = params.end(); i != e; i++,index++){ 340 | QualType t = *i; 341 | success = recursiveHandleQualType(slideLoc, end, t) || success; 342 | } 343 | } 344 | }else if(isa(type)) { 345 | //与ObjCObjectPointerType 处理方式一致,省略... 346 | 347 | } 348 | else if(isa(type)){ 349 | const AttributedType *attributedType = type->getAs(); //指针类型 350 | success = recursiveHandleQualType(slideLoc, end, attributedType->getModifiedType()); 351 | } 352 | 353 | return success; 354 | } 355 | 356 | string getMethodDeclStringOfMethoddecl(const ObjCMethodDecl *methodDecl){ 357 | string methodDeclStr; 358 | 359 | methodDeclStr += (methodDecl->isInstanceMethod()?"-":"+"); 360 | methodDeclStr += "("; 361 | methodDeclStr += methodDecl->getReturnType().getAsString(); 362 | methodDeclStr += ")"; 363 | int numSelectorLocs = methodDecl->getNumSelectorLocs();//段个数 364 | int numParams = methodDecl->getSelector().getNumArgs();//参数个数 365 | for (int i = 0; i < numSelectorLocs; i++) { 366 | methodDeclStr += methodDecl->getSelector().getNameForSlot(i).str(); 367 | if (i < numParams) { 368 | methodDeclStr += ":"; 369 | const ParmVarDecl *paramVarDecl = methodDecl->getParamDecl(i); 370 | methodDeclStr += "("; 371 | methodDeclStr += paramVarDecl->getType().getAsString(); 372 | methodDeclStr += ")"; 373 | methodDeclStr += paramVarDecl->getNameAsString(); 374 | } 375 | if (i+1 < numSelectorLocs) { 376 | methodDeclStr += " "; 377 | } 378 | } 379 | 380 | return methodDeclStr; 381 | } 382 | 383 | 384 | 385 | 386 | //获取方法对应的类名或者协议名 387 | string getClassNameOfMethodDecl(const ObjCMethodDecl *methodDecl){ 388 | string className; 389 | methodDecl->getClassInterface(); 390 | 391 | if (isa(methodDecl->getDeclContext())) { // 392 | const ObjCCategoryDecl *categoryDecl = dyn_cast_or_null(methodDecl->getDeclContext()); 393 | const ObjCInterfaceDecl *interfaceDecl = categoryDecl->getClassInterface(); 394 | if (interfaceDecl) className = interfaceDecl->getNameAsString(); 395 | }else if (isa(methodDecl->getDeclContext())) { 396 | const ObjCCategoryImplDecl *categoryImplDecl = dyn_cast_or_null(methodDecl->getDeclContext()); 397 | const ObjCInterfaceDecl *interfaceDecl = categoryImplDecl->getClassInterface(); 398 | if (interfaceDecl) className = interfaceDecl->getNameAsString(); 399 | }else if (isa(methodDecl->getDeclContext())) { 400 | const ObjCInterfaceDecl *interfaceDecl = dyn_cast_or_null(methodDecl->getDeclContext()); 401 | if (interfaceDecl) className = interfaceDecl->getNameAsString(); 402 | }else if (isa(methodDecl->getDeclContext())) { 403 | const ObjCImplementationDecl *implementationDecl = dyn_cast_or_null(methodDecl->getDeclContext()); 404 | if (implementationDecl) className = implementationDecl->getNameAsString(); 405 | }else { //ObjCProtocolDecl 406 | const ObjCProtocolDecl *protocolDecl = dyn_cast_or_null(methodDecl->getDeclContext()); 407 | if (protocolDecl) className = protocolDecl->getNameAsString(); 408 | } 409 | return className; 410 | } 411 | 412 | //判断是否用户源码,过滤掉系统源码 413 | template 414 | bool isUserSourceDecl(const Node node) { 415 | if(!node)return false; 416 | string filename = sourcePathNode(node); 417 | if (filename.empty()) 418 | return false; 419 | //非XCode中的源码都认为是用户源码 420 | if(filename.find("/Applications/Xcode.app/") == 0) 421 | return false; 422 | return true; 423 | } 424 | //获取decl所在的文件 425 | template 426 | string sourcePathNode(const Node node ) { 427 | if(!node)return ""; 428 | 429 | SourceLocation spellingLoc = compilerInstance->getSourceManager().getSpellingLoc(node->getSourceRange().getBegin()); 430 | string filePath = compilerInstance->getSourceManager().getFilename(spellingLoc).str(); 431 | return filePath; 432 | } 433 | 434 | //获取文件名,截取'/'后面的部分 435 | template 436 | string fileNameOfNode(const Node node) { 437 | string filePath = sourcePathNode(node); 438 | size_t index = filePath.find_last_of("/"); 439 | if (index == StringRef::npos) { 440 | return ""; 441 | } 442 | StringRef fileName = filePath.substr(index+1,-1); 443 | return fileName.str(); 444 | } 445 | 446 | 447 | private: 448 | Rewriter &rewriter; 449 | CompilerInstance *compilerInstance; 450 | }; 451 | 452 | //AST 构造器 453 | class ObfASTConsumer : public ASTConsumer { 454 | public: 455 | ObfASTConsumer(Rewriter &aRewriter,CompilerInstance *aCI) :handlerMatchCallback(aRewriter,aCI) { 456 | 457 | //类声明 458 | matcher.addMatcher(objcInterfaceDecl().bind("objcInterfaceDecl"), &handlerMatchCallback); 459 | //类定义 460 | matcher.addMatcher(objcImplementationDecl().bind("objcImplementationDecl"), &handlerMatchCallback); 461 | //分类声明 462 | matcher.addMatcher(objcCategoryDecl().bind("objcCategoryDecl"), &handlerMatchCallback); 463 | //分类定义 464 | matcher.addMatcher(objcCategoryImplDecl().bind("objcCategoryImplDecl"), &handlerMatchCallback); 465 | //方法声明 466 | matcher.addMatcher(objcMethodDecl().bind("objcMethodDecl"), &handlerMatchCallback); 467 | //变量声明或定义 468 | matcher.addMatcher(varDecl().bind("varDecl"), &handlerMatchCallback); 469 | //实例变量 470 | matcher.addMatcher(objcIvarDecl().bind("objcIvarDecl"), &handlerMatchCallback); 471 | //属性声明 472 | matcher.addMatcher(objcPropertyDecl().bind("objcPropertyDecl"), &handlerMatchCallback); 473 | //类消息表达式 474 | matcher.addMatcher(objcMessageExpr(isClassMessage()).bind("objcMessageExpr"), &handlerMatchCallback); 475 | //显式转换表达式 476 | matcher.addMatcher(explicitCastExpr().bind("explicitCastExpr"), &handlerMatchCallback); 477 | //typedef 声明 478 | matcher.addMatcher(typedefDecl().bind("typedefDecl"), &handlerMatchCallback); 479 | //字符串,小端 480 | matcher.addMatcher(stringLiteral().bind("stringLiteral"), &handlerMatchCallback); 481 | 482 | 483 | 484 | } 485 | 486 | void HandleTranslationUnit(ASTContext &Context) override { 487 | //运行匹配器 488 | matcher.matchAST(Context); 489 | } 490 | 491 | private: 492 | MatchFinder matcher; 493 | MatchCallbackHandler handlerMatchCallback; 494 | 495 | }; 496 | 497 | //action 498 | class ObfASTFrontendAction : public ASTFrontendAction { 499 | public: 500 | //创建AST Consumer 501 | std::unique_ptr CreateASTConsumer(clang::CompilerInstance &CI, StringRef file) override { 502 | size_t index = file.str().find_last_of("/"); 503 | StringRef fileName = file.str().substr(index+1,-1); //获取文件名,截取'/'后面的部分 504 | cout << "【混淆】开始处理文件:" << fileName.str() << endl; 505 | 506 | rewriter.setSourceMgr(CI.getSourceManager(), CI.getLangOpts()); 507 | return std::make_unique(rewriter,&CI); 508 | } 509 | //源文件操作结束 510 | void EndSourceFileAction() override { 511 | 512 | SourceManager &SM = rewriter.getSourceMgr(); 513 | 514 | string Filename = SM.getFileEntryForID(SM.getMainFileID())->getName(); 515 | 516 | std::error_code error_code; 517 | llvm::raw_fd_ostream outFile(Filename, error_code, llvm::sys::fs::F_None); 518 | rewriter.getEditBuffer(SM.getMainFileID()).write(outFile); 519 | 520 | //文件处理完成 521 | cout << "【混淆】文件处理完成: " << Filename << endl; 522 | } 523 | private: 524 | Rewriter rewriter; 525 | 526 | }; 527 | 528 | int main(int argc, const char **argv) { 529 | CommonOptionsParser OptionsParser(argc, argv, ObfOptionCategory); 530 | ClangTool Tool(OptionsParser.getCompilations(),OptionsParser.getSourcePathList()); 531 | return Tool.run(newFrontendActionFactory().get()); 532 | } 533 | -------------------------------------------------------------------------------- /clang-obfuscator/obfuscator.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | // obfuscator.h 4 | // obfuscator 5 | // 6 | // Created by 冯立海/335418265@qq.com on 2020/2/1. 7 | // Copyright © 2020 fenglh. All rights reserved. 8 | // 9 | --------------------------------------------------------------------------------