From 5e9286b9eae9fcee43c8a584c434f1f19559a78c Mon Sep 17 00:00:00 2001 From: vanhauser-thc Date: Mon, 28 Feb 2022 17:43:58 +0100 Subject: [PATCH 01/11] todo list for llvm --- TODO_LLVM | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 TODO_LLVM diff --git a/TODO_LLVM b/TODO_LLVM new file mode 100644 index 00000000..3dea8cca --- /dev/null +++ b/TODO_LLVM @@ -0,0 +1,10 @@ +with LLVM 14: only new pass manager +up to LLVM 13: only old pass manager + +These do not work yet with the new pass manager: +cmplog-instructions-pass.so +compare-transform-pass.so +afl-llvm-dict2file.so +afl-llvm-lto-instrumentlist.so +SanitizerCoverageLTO.so +SanitizerCoveragePCGUARD.so From d325fa5db8287e0b4984b12b07b16cf0f643c468 Mon Sep 17 00:00:00 2001 From: vanhauser-thc Date: Tue, 1 Mar 2022 20:13:57 +0100 Subject: [PATCH 02/11] code format --- instrumentation/cmplog-instructions-pass.cc | 31 ++++++++++++-------- instrumentation/compare-transform-pass.so.cc | 23 ++++++++------- src/afl-cc.c | 10 +++---- 3 files changed, 36 insertions(+), 28 deletions(-) diff --git a/instrumentation/cmplog-instructions-pass.cc b/instrumentation/cmplog-instructions-pass.cc index b6d51ef3..b3fe3880 100644 --- a/instrumentation/cmplog-instructions-pass.cc +++ b/instrumentation/cmplog-instructions-pass.cc @@ -60,14 +60,16 @@ using namespace llvm; namespace { -#if LLVM_MAJOR >= 11 /* use new pass manager */ +#if LLVM_MAJOR >= 11 /* use new pass manager */ class CmpLogInstructions : public PassInfoMixin { + public: CmpLogInstructions() { initInstrumentList(); } + #else class CmpLogInstructions : public ModulePass { @@ -78,23 +80,25 @@ class CmpLogInstructions : public ModulePass { initInstrumentList(); } + #endif -#if LLVM_MAJOR >= 11 /* use new pass manager */ +#if LLVM_MAJOR >= 11 /* use new pass manager */ PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM); #else - bool runOnModule(Module &M) override; + bool runOnModule(Module &M) override; -#if LLVM_VERSION_MAJOR >= 4 + #if LLVM_VERSION_MAJOR >= 4 StringRef getPassName() const override { -#else + #else const char *getPassName() const override { -#endif + #endif return "cmplog instructions"; } + #endif private: @@ -104,7 +108,7 @@ class CmpLogInstructions : public ModulePass { } // namespace -#if LLVM_MAJOR <= 10 /* use old pass manager */ +#if LLVM_MAJOR <= 10 /* use old pass manager */ char CmpLogInstructions::ID = 0; #endif @@ -634,11 +638,13 @@ bool CmpLogInstructions::hookInstrs(Module &M) { } -#if LLVM_MAJOR >= 11 /* use new pass manager */ +#if LLVM_MAJOR >= 11 /* use new pass manager */ PreservedAnalyses CmpLogInstructions::run(Module & M, - ModuleAnalysisManager &MAM) { + ModuleAnalysisManager &MAM) { + #else bool CmpLogInstructions::runOnModule(Module &M) { + #endif if (getenv("AFL_QUIET") == NULL) @@ -648,7 +654,7 @@ bool CmpLogInstructions::runOnModule(Module &M) { hookInstrs(M); verifyModule(M); -#if LLVM_MAJOR >= 11 /* use new pass manager */ +#if LLVM_MAJOR >= 11 /* use new pass manager */ return PreservedAnalyses::all(); #else return true; @@ -671,9 +677,10 @@ static RegisterStandardPasses RegisterCmpLogInstructionsPass( static RegisterStandardPasses RegisterCmpLogInstructionsPass0( PassManagerBuilder::EP_EnabledOnOptLevel0, registerCmpLogInstructionsPass); -#if LLVM_VERSION_MAJOR >= 11 + #if LLVM_VERSION_MAJOR >= 11 static RegisterStandardPasses RegisterCmpLogInstructionsPassLTO( PassManagerBuilder::EP_FullLinkTimeOptimizationLast, registerCmpLogInstructionsPass); + #endif #endif -#endif + diff --git a/instrumentation/compare-transform-pass.so.cc b/instrumentation/compare-transform-pass.so.cc index cd3f0e6f..4e471ea3 100644 --- a/instrumentation/compare-transform-pass.so.cc +++ b/instrumentation/compare-transform-pass.so.cc @@ -81,27 +81,28 @@ class CompareTransform : public ModulePass { } #if LLVM_MAJOR < 11 -#if LLVM_VERSION_MAJOR >= 4 + #if LLVM_VERSION_MAJOR >= 4 StringRef getPassName() const override { -#else + #else const char *getPassName() const override { -#endif + + #endif #endif #if LLVM_MAJOR >= 11 /* use new pass manager */ - PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM); + PreservedAnalyses run(Module & M, ModuleAnalysisManager & MAM); #else bool runOnModule(Module &M) override; #endif - private: - bool transformCmps(Module &M, const bool processStrcmp, - const bool processMemcmp, const bool processStrncmp, - const bool processStrcasecmp, - const bool processStrncasecmp); + private: + bool transformCmps(Module & M, const bool processStrcmp, + const bool processMemcmp, const bool processStrncmp, + const bool processStrcasecmp, + const bool processStrncasecmp); -}; + }; } // namespace @@ -170,7 +171,7 @@ bool CompareTransform::transformCmps(Module &M, const bool processStrcmp, #if LLVM_VERSION_MAJOR >= 9 FunctionCallee tolowerFn; #else - Function * tolowerFn; + Function *tolowerFn; #endif { diff --git a/src/afl-cc.c b/src/afl-cc.c index 3e67085e..fae572f6 100644 --- a/src/afl-cc.c +++ b/src/afl-cc.c @@ -462,7 +462,7 @@ static void edit_params(u32 argc, char **argv, char **envp) { } else { -#if LLVM_MAJOR >= 11 /* use new pass manager */ +#if LLVM_MAJOR >= 11 /* use new pass manager */ cc_params[cc_par_cnt++] = "-fexperimental-new-pass-manager"; cc_params[cc_par_cnt++] = alloc_printf("-fpass-plugin=%s/split-switches-pass.so", obj_path); @@ -488,7 +488,7 @@ static void edit_params(u32 argc, char **argv, char **envp) { } else { -#if LLVM_MAJOR >= 11 /* use new pass manager */ +#if LLVM_MAJOR >= 11 /* use new pass manager */ cc_params[cc_par_cnt++] = "-fexperimental-new-pass-manager"; cc_params[cc_par_cnt++] = alloc_printf( "-fpass-plugin=%s/compare-transform-pass.so", obj_path); @@ -571,7 +571,7 @@ static void edit_params(u32 argc, char **argv, char **envp) { } -#if LLVM_MAJOR == 13 // TODO: set to 14 when done FIXME +#if LLVM_MAJOR == 13 // TODO: set to 14 when done FIXME // Use the old pass manager in LLVM 13 which the afl++ passes still use. cc_params[cc_par_cnt++] = "-flegacy-pass-manager"; #endif @@ -684,8 +684,8 @@ static void edit_params(u32 argc, char **argv, char **envp) { #if LLVM_MAJOR >= 11 cc_params[cc_par_cnt++] = "-fexperimental-new-pass-manager"; - cc_params[cc_par_cnt++] = - alloc_printf("-fpass-plugin=%s/cmplog-instructions-pass.so", obj_path); + cc_params[cc_par_cnt++] = alloc_printf( + "-fpass-plugin=%s/cmplog-instructions-pass.so", obj_path); #else cc_params[cc_par_cnt++] = "-Xclang"; cc_params[cc_par_cnt++] = "-load"; From f2831419f5ceb28e1bc0cbf67cada012bccfb843 Mon Sep 17 00:00:00 2001 From: vanhauser-thc Date: Thu, 3 Mar 2022 08:55:05 +0100 Subject: [PATCH 03/11] ported cmplog-instructions-pass --- instrumentation/cmplog-instructions-pass.cc | 29 ++++++++++++++++++--- instrumentation/cmplog-routines-pass.cc | 24 +++++++++++++++++ instrumentation/cmplog-switches-pass.cc | 21 +++++++++++++++ 3 files changed, 71 insertions(+), 3 deletions(-) diff --git a/instrumentation/cmplog-instructions-pass.cc b/instrumentation/cmplog-instructions-pass.cc index b3fe3880..aa3ad560 100644 --- a/instrumentation/cmplog-instructions-pass.cc +++ b/instrumentation/cmplog-instructions-pass.cc @@ -32,8 +32,8 @@ #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #if LLVM_MAJOR >= 11 -// #include "llvm/Passes/PassPlugin.h" -// #include "llvm/Passes/PassBuilder.h" + #include "llvm/Passes/PassPlugin.h" + #include "llvm/Passes/PassBuilder.h" #include "llvm/IR/PassManager.h" #else #include "llvm/IR/LegacyPassManager.h" @@ -41,6 +41,9 @@ #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Pass.h" #include "llvm/Analysis/ValueTracking.h" +#if LLVM_VERSION_MAJOR >= 14 /* how about stable interfaces? */ + #include "llvm/Passes/OptimizationLevel.h" +#endif #if LLVM_VERSION_MAJOR >= 4 || \ (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR > 4) @@ -108,7 +111,27 @@ class CmpLogInstructions : public ModulePass { } // namespace -#if LLVM_MAJOR <= 10 /* use old pass manager */ +#if LLVM_MAJOR >= 11 +extern "C" ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK +llvmGetPassPluginInfo() { + + return {LLVM_PLUGIN_API_VERSION, "cmploginstructions", "v0.1", + /* lambda to insert our pass into the pass pipeline. */ + [](PassBuilder &PB) { + +#if LLVM_VERSION_MAJOR <= 13 + using OptimizationLevel = typename PassBuilder::OptimizationLevel; +#endif + PB.registerOptimizerLastEPCallback( + [](ModulePassManager &MPM, OptimizationLevel OL) { + + MPM.addPass(CmpLogInstructions()); + + }); + }}; + +} +#else char CmpLogInstructions::ID = 0; #endif diff --git a/instrumentation/cmplog-routines-pass.cc b/instrumentation/cmplog-routines-pass.cc index 2af01a7a..2c2f2fc4 100644 --- a/instrumentation/cmplog-routines-pass.cc +++ b/instrumentation/cmplog-routines-pass.cc @@ -83,7 +83,31 @@ class CmpLogRoutines : public ModulePass { } // namespace + +#if LLVM_MAJOR >= 11 && 1 == 0 +llvmGetPassPluginInfo() { + + return {LLVM_PLUGIN_API_VERSION, "cmplogroutines", "v0.1", + /* lambda to insert our pass into the pass pipeline. */ + [](PassBuilder &PB) { + +#if LLVM_VERSION_MAJOR <= 13 + using OptimizationLevel = typename PassBuilder::OptimizationLevel; +#endif + PB.registerOptimizerLastEPCallback( + [](ModulePassManager &MPM, OptimizationLevel OL) { + + MPM.addPass(SplitComparesTransform()); + + }); + }}; + +} +#else char CmpLogRoutines::ID = 0; +#endif + + bool CmpLogRoutines::hookRtns(Module &M) { diff --git a/instrumentation/cmplog-switches-pass.cc b/instrumentation/cmplog-switches-pass.cc index 068650ce..7c591e13 100644 --- a/instrumentation/cmplog-switches-pass.cc +++ b/instrumentation/cmplog-switches-pass.cc @@ -84,7 +84,28 @@ class CmpLogInstructions : public ModulePass { } // namespace +#if LLVM_MAJOR >= 11 && 1 == 0 +llvmGetPassPluginInfo() { + + return {LLVM_PLUGIN_API_VERSION, "cmplogswitches", "v0.1", + /* lambda to insert our pass into the pass pipeline. */ + [](PassBuilder &PB) { + +#if LLVM_VERSION_MAJOR <= 13 + using OptimizationLevel = typename PassBuilder::OptimizationLevel; +#endif + PB.registerOptimizerLastEPCallback( + [](ModulePassManager &MPM, OptimizationLevel OL) { + + MPM.addPass(SplitComparesTransform()); + + }); + }}; + +} +#else char CmpLogInstructions::ID = 0; +#endif template Iterator Unique(Iterator first, Iterator last) { From 899fa59ab60e3924f986e17814cdfee544418e08 Mon Sep 17 00:00:00 2001 From: vanhauser-thc Date: Thu, 3 Mar 2022 17:11:41 +0100 Subject: [PATCH 04/11] port cmplog-switches-pass --- instrumentation/cmplog-instructions-pass.cc | 6 +- instrumentation/cmplog-routines-pass.cc | 9 +-- instrumentation/cmplog-switches-pass.cc | 89 +++++++++++++++------ 3 files changed, 72 insertions(+), 32 deletions(-) diff --git a/instrumentation/cmplog-instructions-pass.cc b/instrumentation/cmplog-instructions-pass.cc index aa3ad560..5bd98072 100644 --- a/instrumentation/cmplog-instructions-pass.cc +++ b/instrumentation/cmplog-instructions-pass.cc @@ -119,18 +119,20 @@ llvmGetPassPluginInfo() { /* lambda to insert our pass into the pass pipeline. */ [](PassBuilder &PB) { -#if LLVM_VERSION_MAJOR <= 13 + #if LLVM_VERSION_MAJOR <= 13 using OptimizationLevel = typename PassBuilder::OptimizationLevel; -#endif + #endif PB.registerOptimizerLastEPCallback( [](ModulePassManager &MPM, OptimizationLevel OL) { MPM.addPass(CmpLogInstructions()); }); + }}; } + #else char CmpLogInstructions::ID = 0; #endif diff --git a/instrumentation/cmplog-routines-pass.cc b/instrumentation/cmplog-routines-pass.cc index 2c2f2fc4..d146dfa3 100644 --- a/instrumentation/cmplog-routines-pass.cc +++ b/instrumentation/cmplog-routines-pass.cc @@ -83,7 +83,6 @@ class CmpLogRoutines : public ModulePass { } // namespace - #if LLVM_MAJOR >= 11 && 1 == 0 llvmGetPassPluginInfo() { @@ -91,24 +90,24 @@ llvmGetPassPluginInfo() { /* lambda to insert our pass into the pass pipeline. */ [](PassBuilder &PB) { -#if LLVM_VERSION_MAJOR <= 13 + #if LLVM_VERSION_MAJOR <= 13 using OptimizationLevel = typename PassBuilder::OptimizationLevel; -#endif + #endif PB.registerOptimizerLastEPCallback( [](ModulePassManager &MPM, OptimizationLevel OL) { MPM.addPass(SplitComparesTransform()); }); + }}; } + #else char CmpLogRoutines::ID = 0; #endif - - bool CmpLogRoutines::hookRtns(Module &M) { std::vector calls, llvmStdStd, llvmStdC, gccStdStd, gccStdC, diff --git a/instrumentation/cmplog-switches-pass.cc b/instrumentation/cmplog-switches-pass.cc index 7c591e13..37bf3889 100644 --- a/instrumentation/cmplog-switches-pass.cc +++ b/instrumentation/cmplog-switches-pass.cc @@ -28,7 +28,14 @@ #include "llvm/Config/llvm-config.h" #include "llvm/ADT/Statistic.h" #include "llvm/IR/IRBuilder.h" -#include "llvm/IR/LegacyPassManager.h" +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ + #include "llvm/Passes/PassPlugin.h" + #include "llvm/Passes/PassBuilder.h" + #include "llvm/IR/PassManager.h" +#else + #include "llvm/IR/LegacyPassManager.h" + #include "llvm/Transforms/IPO/PassManagerBuilder.h" +#endif #include "llvm/IR/Module.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" @@ -37,6 +44,7 @@ #include "llvm/Pass.h" #include "llvm/Analysis/ValueTracking.h" +#include "llvm/IR/IRBuilder.h" #if LLVM_VERSION_MAJOR >= 4 || \ (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR > 4) #include "llvm/IR/Verifier.h" @@ -54,29 +62,42 @@ using namespace llvm; namespace { -class CmpLogInstructions : public ModulePass { +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ +class CmplogSwitches : public PassInfoMixin { + + public: + CmplogSwitches() { + +#else +class CmplogSwitches : public ModulePass { public: static char ID; - CmpLogInstructions() : ModulePass(ID) { + CmplogSwitches() : ModulePass(ID) { +#endif initInstrumentList(); } - bool runOnModule(Module &M) override; +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ + PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM); +#else + bool runOnModule(Module &M) override; -#if LLVM_VERSION_MAJOR < 4 + #if LLVM_VERSION_MAJOR < 4 const char *getPassName() const override { -#else + #else StringRef getPassName() const override { -#endif - return "cmplog instructions"; + #endif + return "cmplog switch split"; } +#endif + private: bool hookInstrs(Module &M); @@ -84,27 +105,30 @@ class CmpLogInstructions : public ModulePass { } // namespace -#if LLVM_MAJOR >= 11 && 1 == 0 +#if LLVM_MAJOR >= 11 +extern "C" ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK llvmGetPassPluginInfo() { return {LLVM_PLUGIN_API_VERSION, "cmplogswitches", "v0.1", /* lambda to insert our pass into the pass pipeline. */ [](PassBuilder &PB) { -#if LLVM_VERSION_MAJOR <= 13 + #if LLVM_VERSION_MAJOR <= 13 using OptimizationLevel = typename PassBuilder::OptimizationLevel; -#endif + #endif PB.registerOptimizerLastEPCallback( [](ModulePassManager &MPM, OptimizationLevel OL) { - MPM.addPass(SplitComparesTransform()); + MPM.addPass(CmplogSwitches()); }); + }}; } + #else -char CmpLogInstructions::ID = 0; +char CmplogSwitches::ID = 0; #endif template @@ -122,7 +146,7 @@ Iterator Unique(Iterator first, Iterator last) { } -bool CmpLogInstructions::hookInstrs(Module &M) { +bool CmplogSwitches::hookInstrs(Module &M) { std::vector switches; LLVMContext & C = M.getContext(); @@ -404,36 +428,51 @@ bool CmpLogInstructions::hookInstrs(Module &M) { } -bool CmpLogInstructions::runOnModule(Module &M) { +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ +PreservedAnalyses CmplogSwitches::run(Module &M, ModuleAnalysisManager &MAM) { + +#else +bool CmplogSwitches::runOnModule(Module &M) { + +#endif if (getenv("AFL_QUIET") == NULL) printf("Running cmplog-switches-pass by andreafioraldi@gmail.com\n"); else be_quiet = 1; hookInstrs(M); +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ + auto PA = PreservedAnalyses::all(); +#endif verifyModule(M); +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ + return PA; +#else return true; +#endif } -static void registerCmpLogInstructionsPass(const PassManagerBuilder &, - legacy::PassManagerBase &PM) { +#if LLVM_VERSION_MAJOR < 11 /* use old pass manager */ +static void registerCmplogSwitchesPass(const PassManagerBuilder &, + legacy::PassManagerBase &PM) { - auto p = new CmpLogInstructions(); + auto p = new CmplogSwitches(); PM.add(p); } -static RegisterStandardPasses RegisterCmpLogInstructionsPass( - PassManagerBuilder::EP_OptimizerLast, registerCmpLogInstructionsPass); +static RegisterStandardPasses RegisterCmplogSwitchesPass( + PassManagerBuilder::EP_OptimizerLast, registerCmplogSwitchesPass); -static RegisterStandardPasses RegisterCmpLogInstructionsPass0( - PassManagerBuilder::EP_EnabledOnOptLevel0, registerCmpLogInstructionsPass); +static RegisterStandardPasses RegisterCmplogSwitchesPass0( + PassManagerBuilder::EP_EnabledOnOptLevel0, registerCmplogSwitchesPass); -#if LLVM_VERSION_MAJOR >= 11 -static RegisterStandardPasses RegisterCmpLogInstructionsPassLTO( + #if LLVM_VERSION_MAJOR >= 11 +static RegisterStandardPasses RegisterCmplogSwitchesPassLTO( PassManagerBuilder::EP_FullLinkTimeOptimizationLast, - registerCmpLogInstructionsPass); + registerCmplogSwitchesPass); + #endif #endif From a2d54218ad22a5dfe29745422d853e45c5bba0d1 Mon Sep 17 00:00:00 2001 From: vanhauser-thc Date: Thu, 3 Mar 2022 17:27:50 +0100 Subject: [PATCH 05/11] ported cmplog-routines-pass --- instrumentation/cmplog-routines-pass.cc | 54 +++++++++++++++++++++---- 1 file changed, 46 insertions(+), 8 deletions(-) diff --git a/instrumentation/cmplog-routines-pass.cc b/instrumentation/cmplog-routines-pass.cc index d146dfa3..8205cfb0 100644 --- a/instrumentation/cmplog-routines-pass.cc +++ b/instrumentation/cmplog-routines-pass.cc @@ -27,7 +27,14 @@ #include "llvm/ADT/Statistic.h" #include "llvm/IR/IRBuilder.h" -#include "llvm/IR/LegacyPassManager.h" +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ + #include "llvm/Passes/PassPlugin.h" + #include "llvm/Passes/PassBuilder.h" + #include "llvm/IR/PassManager.h" +#else + #include "llvm/IR/LegacyPassManager.h" + #include "llvm/Transforms/IPO/PassManagerBuilder.h" +#endif #include "llvm/IR/Module.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" @@ -36,6 +43,7 @@ #include "llvm/Pass.h" #include "llvm/Analysis/ValueTracking.h" +#include "llvm/IR/IRBuilder.h" #if LLVM_VERSION_MAJOR >= 4 || \ (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR > 4) #include "llvm/IR/Verifier.h" @@ -53,29 +61,43 @@ using namespace llvm; namespace { +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ +class CmpLogRoutines : public PassInfoMixin { + + public: + CmpLogRoutines() { + +#else class CmpLogRoutines : public ModulePass { public: static char ID; CmpLogRoutines() : ModulePass(ID) { +#endif + initInstrumentList(); } - bool runOnModule(Module &M) override; +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ + PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM); +#else + bool runOnModule(Module &M) override; -#if LLVM_VERSION_MAJOR >= 4 + #if LLVM_VERSION_MAJOR >= 4 StringRef getPassName() const override { -#else + #else const char *getPassName() const override { -#endif + #endif return "cmplog routines"; } +#endif + private: bool hookRtns(Module &M); @@ -83,7 +105,8 @@ class CmpLogRoutines : public ModulePass { } // namespace -#if LLVM_MAJOR >= 11 && 1 == 0 +#if LLVM_MAJOR >= 11 +extern "C" ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK llvmGetPassPluginInfo() { return {LLVM_PLUGIN_API_VERSION, "cmplogroutines", "v0.1", @@ -96,7 +119,7 @@ llvmGetPassPluginInfo() { PB.registerOptimizerLastEPCallback( [](ModulePassManager &MPM, OptimizationLevel OL) { - MPM.addPass(SplitComparesTransform()); + MPM.addPass(CmpLogRoutines()); }); @@ -720,19 +743,33 @@ bool CmpLogRoutines::hookRtns(Module &M) { } +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ +PreservedAnalyses CmpLogRoutines::run(Module &M, ModuleAnalysisManager &MAM) { + +#else bool CmpLogRoutines::runOnModule(Module &M) { +#endif + if (getenv("AFL_QUIET") == NULL) printf("Running cmplog-routines-pass by andreafioraldi@gmail.com\n"); else be_quiet = 1; hookRtns(M); +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ + auto PA = PreservedAnalyses::all(); +#endif verifyModule(M); +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ + return PA; +#else return true; +#endif } +#if LLVM_VERSION_MAJOR < 11 /* use old pass manager */ static void registerCmpLogRoutinesPass(const PassManagerBuilder &, legacy::PassManagerBase &PM) { @@ -747,9 +784,10 @@ static RegisterStandardPasses RegisterCmpLogRoutinesPass( static RegisterStandardPasses RegisterCmpLogRoutinesPass0( PassManagerBuilder::EP_EnabledOnOptLevel0, registerCmpLogRoutinesPass); -#if LLVM_VERSION_MAJOR >= 11 + #if LLVM_VERSION_MAJOR >= 11 static RegisterStandardPasses RegisterCmpLogRoutinesPassLTO( PassManagerBuilder::EP_FullLinkTimeOptimizationLast, registerCmpLogRoutinesPass); + #endif #endif From 33e43b11f8981ea97070a1f8b9a75e33b9fc1057 Mon Sep 17 00:00:00 2001 From: vanhauser-thc Date: Thu, 3 Mar 2022 18:24:26 +0100 Subject: [PATCH 06/11] port instrumentation/afl-llvm-dict2file --- instrumentation/afl-llvm-dict2file.so.cc | 113 +++++++++++++++++------ 1 file changed, 86 insertions(+), 27 deletions(-) diff --git a/instrumentation/afl-llvm-dict2file.so.cc b/instrumentation/afl-llvm-dict2file.so.cc index a554c40e..37cd8ad0 100644 --- a/instrumentation/afl-llvm-dict2file.so.cc +++ b/instrumentation/afl-llvm-dict2file.so.cc @@ -39,7 +39,14 @@ #include "llvm/Config/llvm-config.h" #include "llvm/ADT/Statistic.h" #include "llvm/IR/IRBuilder.h" -#include "llvm/IR/LegacyPassManager.h" +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ + #include "llvm/Passes/PassPlugin.h" + #include "llvm/Passes/PassBuilder.h" + #include "llvm/IR/PassManager.h" +#else + #include "llvm/IR/LegacyPassManager.h" + #include "llvm/Transforms/IPO/PassManagerBuilder.h" +#endif #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Module.h" #include "llvm/IR/DebugInfo.h" @@ -60,31 +67,9 @@ #define O_DSYNC O_SYNC #endif -using namespace llvm; +std::ofstream of; -namespace { - -class AFLdict2filePass : public ModulePass { - - std::ofstream of; - void dict2file(u8 *, u32); - - public: - static char ID; - - AFLdict2filePass() : ModulePass(ID) { - - if (getenv("AFL_DEBUG")) debug = 1; - - } - - bool runOnModule(Module &M) override; - -}; - -} // namespace - -void AFLdict2filePass::dict2file(u8 *mem, u32 len) { +void dict2file(u8 *mem, u32 len) { u32 i, j, binary = 0; char line[MAX_AUTO_EXTRA * 8], tmp[8]; @@ -123,8 +108,74 @@ void AFLdict2filePass::dict2file(u8 *mem, u32 len) { } +using namespace llvm; + +namespace { + +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ +class AFLdict2filePass : public PassInfoMixin { + + public: + AFLdict2filePass() { + +#else +class AFLdict2filePass : public ModulePass { + + public: + bool runOnModule(Module &M) override; + AFLdict2filePass() : ModulePass(ID) { + +#endif + + if (getenv("AFL_DEBUG")) debug = 1; + + } + +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ + PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM); +#endif + +}; + +} // namespace + +#if LLVM_MAJOR >= 11 +extern "C" ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK +llvmGetPassPluginInfo() { + + return {LLVM_PLUGIN_API_VERSION, "dict2file", "v0.1", + /* lambda to insert our pass into the pass pipeline. */ + [](PassBuilder &PB) { + + #if LLVM_VERSION_MAJOR <= 13 + using OptimizationLevel = typename PassBuilder::OptimizationLevel; + #endif + PB.registerOptimizerLastEPCallback( + [](ModulePassManager &MPM, OptimizationLevel OL) { + + MPM.addPass(AFLdict2filePass()); + + }); + + }}; + +} + +#else + +char AFLdict2filePass::ID = 0; + +#endif + +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ +PreservedAnalyses AFLdict2filePass::run(Module &M, ModuleAnalysisManager &MAM) { + +#else + bool AFLdict2filePass::runOnModule(Module &M) { +#endif + DenseMap valueMap; char * ptr; int found = 0; @@ -663,12 +714,18 @@ bool AFLdict2filePass::runOnModule(Module &M) { } +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ + auto PA = PreservedAnalyses::all(); +#endif +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ + return PA; +#else return true; +#endif } -char AFLdict2filePass::ID = 0; - +#if LLVM_VERSION_MAJOR < 11 /* use old pass manager */ static void registerAFLdict2filePass(const PassManagerBuilder &, legacy::PassManagerBase &PM) { @@ -686,3 +743,5 @@ static RegisterStandardPasses RegisterAFLdict2filePass( static RegisterStandardPasses RegisterAFLdict2filePass0( PassManagerBuilder::EP_EnabledOnOptLevel0, registerAFLdict2filePass); +#endif + From 5385cc7618c387dfbfb6a0a06cfa63ed45b50d15 Mon Sep 17 00:00:00 2001 From: vanhauser-thc Date: Fri, 4 Mar 2022 15:03:26 +0100 Subject: [PATCH 07/11] sancov will be only for llvm11+ --- .../SanitizerCoveragePCGUARD.so.cc | 37 +++---------------- 1 file changed, 5 insertions(+), 32 deletions(-) diff --git a/instrumentation/SanitizerCoveragePCGUARD.so.cc b/instrumentation/SanitizerCoveragePCGUARD.so.cc index 48bb5a2c..d3529fbc 100644 --- a/instrumentation/SanitizerCoveragePCGUARD.so.cc +++ b/instrumentation/SanitizerCoveragePCGUARD.so.cc @@ -37,10 +37,7 @@ #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/SpecialCaseList.h" -#if LLVM_VERSION_MAJOR >= 11 || \ - (LLVM_VERSION_MAJOR == 10 && LLVM_VERSION_MINOR >= 1) - #include "llvm/Support/VirtualFileSystem.h" -#endif +#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Instrumentation.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" @@ -1487,7 +1484,6 @@ std::string ModuleSanitizerCoverage::getSectionEnd( } char ModuleSanitizerCoverageLegacyPass::ID = 0; - INITIALIZE_PASS_BEGIN(ModuleSanitizerCoverageLegacyPass, "sancov", "Pass for instrumenting coverage on functions", false, false) @@ -1496,36 +1492,13 @@ INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) INITIALIZE_PASS_END(ModuleSanitizerCoverageLegacyPass, "sancov", "Pass for instrumenting coverage on functions", false, false) - ModulePass *llvm::createModuleSanitizerCoverageLegacyPassPass( - const SanitizerCoverageOptions &Options -#if (LLVM_VERSION_MAJOR >= 11) - , + const SanitizerCoverageOptions &Options, const std::vector &AllowlistFiles, - const std::vector &BlocklistFiles -#endif -) { + const std::vector &BlocklistFiles) { - return new ModuleSanitizerCoverageLegacyPass(Options -#if (LLVM_VERSION_MAJOR >= 11) - , - AllowlistFiles, BlocklistFiles -#endif - ); + return new ModuleSanitizerCoverageLegacyPass(Options, AllowlistFiles, + BlocklistFiles); } -void registerPCGUARDPass(const PassManagerBuilder &, - legacy::PassManagerBase &PM) { - - auto p = new ModuleSanitizerCoverageLegacyPass(); - PM.add(p); - -} - -RegisterStandardPasses RegisterCompTransPass( - PassManagerBuilder::EP_OptimizerLast, registerPCGUARDPass); - -RegisterStandardPasses RegisterCompTransPass0( - PassManagerBuilder::EP_EnabledOnOptLevel0, registerPCGUARDPass); - From 2b8fea083e6071fe0934e4a939ab651b44118208 Mon Sep 17 00:00:00 2001 From: vanhauser-thc Date: Tue, 15 Mar 2022 07:35:37 +0100 Subject: [PATCH 08/11] test --- ...SanitizerCoveragePCGUARD-alternative.so.cc | 1514 +++++++++++++++++ .../SanitizerCoveragePCGUARD.so.cc | 6 +- 2 files changed, 1518 insertions(+), 2 deletions(-) create mode 100644 instrumentation/SanitizerCoveragePCGUARD-alternative.so.cc diff --git a/instrumentation/SanitizerCoveragePCGUARD-alternative.so.cc b/instrumentation/SanitizerCoveragePCGUARD-alternative.so.cc new file mode 100644 index 00000000..982f610a --- /dev/null +++ b/instrumentation/SanitizerCoveragePCGUARD-alternative.so.cc @@ -0,0 +1,1514 @@ +//===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Coverage instrumentation done on LLVM IR level, works with Sanitizers. +// +//===----------------------------------------------------------------------===// + +#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/Triple.h" +#include "llvm/Analysis/EHPersonalities.h" +#include "llvm/Analysis/PostDominators.h" +#include "llvm/IR/CFG.h" +#include "llvm/IR/Constant.h" +#include "llvm/IR/DataLayout.h" +#include "llvm/IR/DebugInfo.h" +#include "llvm/IR/Dominators.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/GlobalVariable.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/InlineAsm.h" +#include "llvm/IR/IntrinsicInst.h" +#include "llvm/IR/Intrinsics.h" +#include "llvm/IR/LLVMContext.h" +#include "llvm/IR/MDBuilder.h" +#include "llvm/IR/Mangler.h" +#include "llvm/IR/Module.h" +#include "llvm/IR/PassManager.h" +#include "llvm/IR/Type.h" +#include "llvm/InitializePasses.h" +#include "llvm/Support/CommandLine.h" +#include "llvm/Support/Debug.h" +#include "llvm/Support/SpecialCaseList.h" +#include "llvm/Support/VirtualFileSystem.h" +#include "llvm/Support/raw_ostream.h" +#include "llvm/Transforms/Instrumentation.h" +#include "llvm/Transforms/Utils/BasicBlockUtils.h" +#include "llvm/Transforms/Utils/ModuleUtils.h" +#include "llvm/Passes/PassPlugin.h" +#include "llvm/Passes/PassBuilder.h" +#include "llvm/IR/PassManager.h" + +#include "config.h" +#include "debug.h" +#include "afl-llvm-common.h" + +using namespace llvm; + +#define DEBUG_TYPE "sancov" + +const char SanCovTracePCIndirName[] = "__sanitizer_cov_trace_pc_indir"; +const char SanCovTracePCName[] = "__sanitizer_cov_trace_pc"; +const char SanCovTraceCmp1[] = "__sanitizer_cov_trace_cmp1"; +const char SanCovTraceCmp2[] = "__sanitizer_cov_trace_cmp2"; +const char SanCovTraceCmp4[] = "__sanitizer_cov_trace_cmp4"; +const char SanCovTraceCmp8[] = "__sanitizer_cov_trace_cmp8"; +const char SanCovTraceConstCmp1[] = "__sanitizer_cov_trace_const_cmp1"; +const char SanCovTraceConstCmp2[] = "__sanitizer_cov_trace_const_cmp2"; +const char SanCovTraceConstCmp4[] = "__sanitizer_cov_trace_const_cmp4"; +const char SanCovTraceConstCmp8[] = "__sanitizer_cov_trace_const_cmp8"; +const char SanCovTraceDiv4[] = "__sanitizer_cov_trace_div4"; +const char SanCovTraceDiv8[] = "__sanitizer_cov_trace_div8"; +const char SanCovTraceGep[] = "__sanitizer_cov_trace_gep"; +const char SanCovTraceSwitchName[] = "__sanitizer_cov_trace_switch"; +const char SanCovModuleCtorTracePcGuardName[] = + "sancov.module_ctor_trace_pc_guard"; +const char SanCovModuleCtor8bitCountersName[] = + "sancov.module_ctor_8bit_counters"; +const char SanCovModuleCtorBoolFlagName[] = "sancov.module_ctor_bool_flag"; +static const uint64_t SanCtorAndDtorPriority = 2; + +const char SanCovTracePCGuardName[] = "__sanitizer_cov_trace_pc_guard"; +const char SanCovTracePCGuardInitName[] = "__sanitizer_cov_trace_pc_guard_init"; +const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init"; +const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init"; +const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init"; + +const char SanCovGuardsSectionName[] = "sancov_guards"; +const char SanCovCountersSectionName[] = "sancov_cntrs"; +const char SanCovBoolFlagSectionName[] = "sancov_bools"; +const char SanCovPCsSectionName[] = "sancov_pcs"; + +const char SanCovLowestStackName[] = "__sancov_lowest_stack"; + +static const char *skip_nozero; +static const char *use_threadsafe_counters; + +namespace { + +SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) { + + // Sets CoverageType and IndirectCalls. + // SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel); + Options.CoverageType = + SanitizerCoverageOptions::SCK_Edge; // std::max(Options.CoverageType, + // CLOpts.CoverageType); + Options.IndirectCalls = false; // CLOpts.IndirectCalls; + Options.TraceCmp = false; //|= ClCMPTracing; + Options.TraceDiv = false; //|= ClDIVTracing; + Options.TraceGep = false; //|= ClGEPTracing; + Options.TracePC = false; //|= ClTracePC; + Options.TracePCGuard = true; // |= ClTracePCGuard; + Options.Inline8bitCounters = 0; //|= ClInline8bitCounters; + // Options.InlineBoolFlag = 0; //|= ClInlineBoolFlag; + Options.PCTable = false; //|= ClCreatePCTable; + Options.NoPrune = false; //|= !ClPruneBlocks; + Options.StackDepth = false; //|= ClStackDepth; + if (!Options.TracePCGuard && !Options.TracePC && + !Options.Inline8bitCounters && !Options.StackDepth /*&& + !Options.InlineBoolFlag*/) + Options.TracePCGuard = true; // TracePCGuard is default. + + return Options; + +} + +using DomTreeCallback = function_ref; +using PostDomTreeCallback = + function_ref; + +class ModuleSanitizerCoverageAFL + : public PassInfoMixin { + + public: + ModuleSanitizerCoverageAFL( + const SanitizerCoverageOptions &Options = SanitizerCoverageOptions()) + : Options(OverrideFromCL(Options)) { + + } + + PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM); + + bool instrumentModule(Module &M, DomTreeCallback DTCallback, + PostDomTreeCallback PDTCallback); + + private: + void instrumentFunction(Function &F, DomTreeCallback DTCallback, + PostDomTreeCallback PDTCallback); + void InjectCoverageForIndirectCalls(Function & F, + ArrayRef IndirCalls); + void InjectTraceForCmp(Function &F, ArrayRef CmpTraceTargets); + void InjectTraceForDiv(Function & F, + ArrayRef DivTraceTargets); + void InjectTraceForGep(Function & F, + ArrayRef GepTraceTargets); + void InjectTraceForSwitch(Function & F, + ArrayRef SwitchTraceTargets); + bool InjectCoverage(Function &F, ArrayRef AllBlocks, + bool IsLeafFunc = true); + GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements, + Function &F, Type *Ty, + const char *Section); + GlobalVariable *CreatePCArray(Function &F, ArrayRef AllBlocks); + void CreateFunctionLocalArrays(Function &F, ArrayRef AllBlocks, + uint32_t special); + void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx, + bool IsLeafFunc = true); + Function *CreateInitCallsForSections(Module &M, const char *CtorName, + const char *InitFunctionName, Type *Ty, + const char *Section); + std::pair CreateSecStartEnd(Module &M, const char *Section, + Type *Ty); + + void SetNoSanitizeMetadata(Instruction *I) { + + I->setMetadata(I->getModule()->getMDKindID("nosanitize"), + MDNode::get(*C, None)); + + } + + std::string getSectionName(const std::string &Section) const; + std::string getSectionStart(const std::string &Section) const; + std::string getSectionEnd(const std::string &Section) const; + FunctionCallee SanCovTracePCIndir; + FunctionCallee SanCovTracePC, SanCovTracePCGuard; + FunctionCallee SanCovTraceCmpFunction[4]; + FunctionCallee SanCovTraceConstCmpFunction[4]; + FunctionCallee SanCovTraceDivFunction[2]; + FunctionCallee SanCovTraceGepFunction; + FunctionCallee SanCovTraceSwitchFunction; + GlobalVariable *SanCovLowestStack; + Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy, + *Int16Ty, *Int8Ty, *Int8PtrTy, *Int1Ty, *Int1PtrTy; + Module * CurModule; + std::string CurModuleUniqueId; + Triple TargetTriple; + LLVMContext * C; + const DataLayout *DL; + + GlobalVariable *FunctionGuardArray; // for trace-pc-guard. + GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters. + GlobalVariable *FunctionBoolArray; // for inline-bool-flag. + GlobalVariable *FunctionPCsArray; // for pc-table. + SmallVector GlobalsToAppendToUsed; + SmallVector GlobalsToAppendToCompilerUsed; + + SanitizerCoverageOptions Options; + + uint32_t instr = 0, selects = 0, unhandled = 0; + GlobalVariable *AFLMapPtr = NULL; + ConstantInt * One = NULL; + ConstantInt * Zero = NULL; + +}; + +class ModuleSanitizerCoverageLegacyPass : public ModulePass { + + public: + ModuleSanitizerCoverageLegacyPass( + const SanitizerCoverageOptions &Options = SanitizerCoverageOptions()) + : ModulePass(ID), Options(Options) { + + initializeModuleSanitizerCoverageLegacyPassPass( + *PassRegistry::getPassRegistry()); + + } + + bool runOnModule(Module &M) override { + + ModuleSanitizerCoverageAFL ModuleSancov(Options); + auto DTCallback = [this](Function &F) -> const DominatorTree * { + + return &this->getAnalysis(F).getDomTree(); + + }; + + auto PDTCallback = [this](Function &F) -> const PostDominatorTree * { + + return &this->getAnalysis(F) + .getPostDomTree(); + + }; + + return ModuleSancov.instrumentModule(M, DTCallback, PDTCallback); + + } + + static char ID; // Pass identification, replacement for typeid + StringRef getPassName() const override { + + return "ModuleSanitizerCoverage"; + + } + + void getAnalysisUsage(AnalysisUsage &AU) const override { + + AU.addRequired(); + AU.addRequired(); + + } + + private: + SanitizerCoverageOptions Options; + +}; + +} // namespace + +#if 1 + +extern "C" ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK +llvmGetPassPluginInfo() { + + return {LLVM_PLUGIN_API_VERSION, "SanitizerCoveragePCGUARD", "v0.1", + /* lambda to insert our pass into the pass pipeline. */ + [](PassBuilder &PB) { + + #if LLVM_VERSION_MAJOR <= 13 + using OptimizationLevel = typename PassBuilder::OptimizationLevel; + #endif + PB.registerOptimizerLastEPCallback( + [](ModulePassManager &MPM, OptimizationLevel OL) { + + MPM.addPass(ModuleSanitizerCoverageAFL()); + + }); + + }}; + +} + +#endif + +PreservedAnalyses ModuleSanitizerCoverageAFL::run(Module & M, + ModuleAnalysisManager &MAM) { + + fprintf(stderr, "IS CALLED!\n"); + + ModuleSanitizerCoverageAFL ModuleSancov(Options); + auto &FAM = MAM.getResult(M).getManager(); + auto DTCallback = [&FAM](Function &F) -> const DominatorTree * { + + return &FAM.getResult(F); + + }; + + auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree * { + + return &FAM.getResult(F); + + }; + + if (ModuleSancov.instrumentModule(M, DTCallback, PDTCallback)) + return PreservedAnalyses::none(); + return PreservedAnalyses::all(); + +} + +std::pair ModuleSanitizerCoverageAFL::CreateSecStartEnd( + Module &M, const char *Section, Type *Ty) { + + GlobalVariable *SecStart = new GlobalVariable( + M, Ty->getPointerElementType(), false, + GlobalVariable::ExternalWeakLinkage, nullptr, getSectionStart(Section)); + SecStart->setVisibility(GlobalValue::HiddenVisibility); + GlobalVariable *SecEnd = new GlobalVariable( + M, Ty->getPointerElementType(), false, + GlobalVariable::ExternalWeakLinkage, nullptr, getSectionEnd(Section)); + SecEnd->setVisibility(GlobalValue::HiddenVisibility); + IRBuilder<> IRB(M.getContext()); + if (!TargetTriple.isOSBinFormatCOFF()) + return std::make_pair(SecStart, SecEnd); + + // Account for the fact that on windows-msvc __start_* symbols actually + // point to a uint64_t before the start of the array. + auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy); + auto GEP = IRB.CreateGEP(Int8Ty, SecStartI8Ptr, + ConstantInt::get(IntptrTy, sizeof(uint64_t))); + return std::make_pair(IRB.CreatePointerCast(GEP, Ty), SecEnd); + +} + +Function *ModuleSanitizerCoverageAFL::CreateInitCallsForSections( + Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty, + const char *Section) { + + auto SecStartEnd = CreateSecStartEnd(M, Section, Ty); + auto SecStart = SecStartEnd.first; + auto SecEnd = SecStartEnd.second; + Function *CtorFunc; + std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions( + M, CtorName, InitFunctionName, {Ty, Ty}, {SecStart, SecEnd}); + assert(CtorFunc->getName() == CtorName); + + if (TargetTriple.supportsCOMDAT()) { + + // Use comdat to dedup CtorFunc. + CtorFunc->setComdat(M.getOrInsertComdat(CtorName)); + appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc); + + } else { + + appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority); + + } + + if (TargetTriple.isOSBinFormatCOFF()) { + + // In COFF files, if the contructors are set as COMDAT (they are because + // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced + // functions and data) is used, the constructors get stripped. To prevent + // this, give the constructors weak ODR linkage and ensure the linker knows + // to include the sancov constructor. This way the linker can deduplicate + // the constructors but always leave one copy. + CtorFunc->setLinkage(GlobalValue::WeakODRLinkage); + appendToUsed(M, CtorFunc); + + } + + return CtorFunc; + +} + +bool ModuleSanitizerCoverageAFL::instrumentModule( + Module &M, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) { + + setvbuf(stdout, NULL, _IONBF, 0); + if (getenv("AFL_DEBUG")) debug = 1; + + if ((isatty(2) && !getenv("AFL_QUIET")) || debug) { + + SAYF(cCYA "SanitizerCoveragePCGUARD" VERSION cRST "\n"); + + } else + + be_quiet = 1; + + skip_nozero = getenv("AFL_LLVM_SKIP_NEVERZERO"); + use_threadsafe_counters = getenv("AFL_LLVM_THREADSAFE_INST"); + + initInstrumentList(); + scanForDangerousFunctions(&M); + + if (debug) { + + fprintf(stderr, + "SANCOV: covtype:%u indirect:%d stack:%d noprune:%d " + "createtable:%d tracepcguard:%d tracepc:%d\n", + Options.CoverageType, Options.IndirectCalls == true ? 1 : 0, + Options.StackDepth == true ? 1 : 0, Options.NoPrune == true ? 1 : 0, + // Options.InlineBoolFlag == true ? 1 : 0, + Options.PCTable == true ? 1 : 0, + Options.TracePCGuard == true ? 1 : 0, + Options.TracePC == true ? 1 : 0); + + } + + if (Options.CoverageType == SanitizerCoverageOptions::SCK_None) return false; + C = &(M.getContext()); + DL = &M.getDataLayout(); + CurModule = &M; + CurModuleUniqueId = getUniqueModuleId(CurModule); + TargetTriple = Triple(M.getTargetTriple()); + FunctionGuardArray = nullptr; + Function8bitCounterArray = nullptr; + FunctionBoolArray = nullptr; + FunctionPCsArray = nullptr; + IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits()); + IntptrPtrTy = PointerType::getUnqual(IntptrTy); + Type * VoidTy = Type::getVoidTy(*C); + IRBuilder<> IRB(*C); + Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty()); + Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty()); + Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty()); + Int1PtrTy = PointerType::getUnqual(IRB.getInt1Ty()); + Int64Ty = IRB.getInt64Ty(); + Int32Ty = IRB.getInt32Ty(); + Int16Ty = IRB.getInt16Ty(); + Int8Ty = IRB.getInt8Ty(); + Int1Ty = IRB.getInt1Ty(); + LLVMContext &Ctx = M.getContext(); + + AFLMapPtr = + new GlobalVariable(M, PointerType::get(Int8Ty, 0), false, + GlobalValue::ExternalLinkage, 0, "__afl_area_ptr"); + One = ConstantInt::get(IntegerType::getInt8Ty(Ctx), 1); + Zero = ConstantInt::get(IntegerType::getInt8Ty(Ctx), 0); + + SanCovTracePCIndir = + M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy); + // Make sure smaller parameters are zero-extended to i64 if required by the + // target ABI. + AttributeList SanCovTraceCmpZeroExtAL; + SanCovTraceCmpZeroExtAL = + SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt); + SanCovTraceCmpZeroExtAL = + SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt); + + SanCovTraceCmpFunction[0] = + M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy, + IRB.getInt8Ty(), IRB.getInt8Ty()); + SanCovTraceCmpFunction[1] = + M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy, + IRB.getInt16Ty(), IRB.getInt16Ty()); + SanCovTraceCmpFunction[2] = + M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy, + IRB.getInt32Ty(), IRB.getInt32Ty()); + SanCovTraceCmpFunction[3] = + M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty); + + SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction( + SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty); + SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction( + SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty); + SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction( + SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty); + SanCovTraceConstCmpFunction[3] = + M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty); + + { + + AttributeList AL; + AL = AL.addParamAttribute(*C, 0, Attribute::ZExt); + SanCovTraceDivFunction[0] = + M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty()); + + } + + SanCovTraceDivFunction[1] = + M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty); + SanCovTraceGepFunction = + M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy); + SanCovTraceSwitchFunction = + M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy); + + Constant *SanCovLowestStackConstant = + M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy); + SanCovLowestStack = dyn_cast(SanCovLowestStackConstant); + if (!SanCovLowestStack) { + + C->emitError(StringRef("'") + SanCovLowestStackName + + "' should not be declared by the user"); + return true; + + } + + SanCovLowestStack->setThreadLocalMode( + GlobalValue::ThreadLocalMode::InitialExecTLSModel); + if (Options.StackDepth && !SanCovLowestStack->isDeclaration()) + SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy)); + + SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy); + SanCovTracePCGuard = + M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy); + + for (auto &F : M) + instrumentFunction(F, DTCallback, PDTCallback); + + Function *Ctor = nullptr; + + if (FunctionGuardArray) + Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName, + SanCovTracePCGuardInitName, Int32PtrTy, + SanCovGuardsSectionName); + if (Function8bitCounterArray) + Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName, + SanCov8bitCountersInitName, Int8PtrTy, + SanCovCountersSectionName); + if (FunctionBoolArray) { + + Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName, + SanCovBoolFlagInitName, Int1PtrTy, + SanCovBoolFlagSectionName); + + } + + if (Ctor && Options.PCTable) { + + auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy); + FunctionCallee InitFunction = declareSanitizerInitFunction( + M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy}); + IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator()); + IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second}); + + } + + // We don't reference these arrays directly in any of our runtime functions, + // so we need to prevent them from being dead stripped. + if (TargetTriple.isOSBinFormatMachO()) appendToUsed(M, GlobalsToAppendToUsed); + appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed); + + if (!be_quiet) { + + if (!instr) + WARNF("No instrumentation targets found."); + else { + + char modeline[100]; + snprintf(modeline, sizeof(modeline), "%s%s%s%s%s%s", + getenv("AFL_HARDEN") ? "hardened" : "non-hardened", + getenv("AFL_USE_ASAN") ? ", ASAN" : "", + getenv("AFL_USE_MSAN") ? ", MSAN" : "", + getenv("AFL_USE_TSAN") ? ", TSAN" : "", + getenv("AFL_USE_CFISAN") ? ", CFISAN" : "", + getenv("AFL_USE_UBSAN") ? ", UBSAN" : ""); + OKF("Instrumented %u locations with no collisions (%s mode) of which are " + "%u handled and %u unhandled selects.", + instr, modeline, selects, unhandled); + + } + + } + + return true; + +} + +// True if block has successors and it dominates all of them. +bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) { + + if (succ_begin(BB) == succ_end(BB)) return false; + + for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) { + + if (!DT->dominates(BB, SUCC)) return false; + + } + + return true; + +} + +// True if block has predecessors and it postdominates all of them. +bool isFullPostDominator(const BasicBlock *BB, const PostDominatorTree *PDT) { + + if (pred_begin(BB) == pred_end(BB)) return false; + + for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) { + + if (!PDT->dominates(BB, PRED)) return false; + + } + + return true; + +} + +bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB, + const DominatorTree * DT, + const PostDominatorTree * PDT, + const SanitizerCoverageOptions &Options) { + + // Don't insert coverage for blocks containing nothing but unreachable: we + // will never call __sanitizer_cov() for them, so counting them in + // NumberOfInstrumentedBlocks() might complicate calculation of code coverage + // percentage. Also, unreachable instructions frequently have no debug + // locations. + if (isa(BB->getFirstNonPHIOrDbgOrLifetime())) return false; + + // Don't insert coverage into blocks without a valid insertion point + // (catchswitch blocks). + if (BB->getFirstInsertionPt() == BB->end()) return false; + + if (Options.NoPrune || &F.getEntryBlock() == BB) return true; + + if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function && + &F.getEntryBlock() != BB) + return false; + + // Do not instrument full dominators, or full post-dominators with multiple + // predecessors. + return !isFullDominator(BB, DT) && + !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor()); + +} + +// Returns true iff From->To is a backedge. +// A twist here is that we treat From->To as a backedge if +// * To dominates From or +// * To->UniqueSuccessor dominates From +bool IsBackEdge(BasicBlock *From, BasicBlock *To, const DominatorTree *DT) { + + if (DT->dominates(To, From)) return true; + if (auto Next = To->getUniqueSuccessor()) + if (DT->dominates(Next, From)) return true; + return false; + +} + +// Prunes uninteresting Cmp instrumentation: +// * CMP instructions that feed into loop backedge branch. +// +// Note that Cmp pruning is controlled by the same flag as the +// BB pruning. +bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT, + const SanitizerCoverageOptions &Options) { + + if (!Options.NoPrune) + if (CMP->hasOneUse()) + if (auto BR = dyn_cast(CMP->user_back())) + for (BasicBlock *B : BR->successors()) + if (IsBackEdge(BR->getParent(), B, DT)) return false; + return true; + +} + +void ModuleSanitizerCoverageAFL::instrumentFunction( + Function &F, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) { + + if (F.empty()) return; + if (!isInInstrumentList(&F, FMNAME)) return; + + if (F.getName().find(".module_ctor") != std::string::npos) + return; // Should not instrument sanitizer init functions. + if (F.getName().startswith("__sanitizer_")) + return; // Don't instrument __sanitizer_* callbacks. + // Don't touch available_externally functions, their actual body is elewhere. + if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return; + // Don't instrument MSVC CRT configuration helpers. They may run before normal + // initialization. + if (F.getName() == "__local_stdio_printf_options" || + F.getName() == "__local_stdio_scanf_options") + return; + if (isa(F.getEntryBlock().getTerminator())) return; + // Don't instrument functions using SEH for now. Splitting basic blocks like + // we do for coverage breaks WinEHPrepare. + // FIXME: Remove this when SEH no longer uses landingpad pattern matching. + if (F.hasPersonalityFn() && + isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn()))) + return; + if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge) + SplitAllCriticalEdges( + F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests()); + SmallVector IndirCalls; + SmallVector BlocksToInstrument; + SmallVector CmpTraceTargets; + SmallVector SwitchTraceTargets; + SmallVector DivTraceTargets; + SmallVector GepTraceTargets; + + const DominatorTree * DT = DTCallback(F); + const PostDominatorTree *PDT = PDTCallback(F); + bool IsLeafFunc = true; + + for (auto &BB : F) { + + if (shouldInstrumentBlock(F, &BB, DT, PDT, Options)) + BlocksToInstrument.push_back(&BB); + for (auto &Inst : BB) { + + if (Options.IndirectCalls) { + + CallBase *CB = dyn_cast(&Inst); + if (CB && !CB->getCalledFunction()) IndirCalls.push_back(&Inst); + + } + + if (Options.TraceCmp) { + + if (ICmpInst *CMP = dyn_cast(&Inst)) + if (IsInterestingCmp(CMP, DT, Options)) + CmpTraceTargets.push_back(&Inst); + if (isa(&Inst)) SwitchTraceTargets.push_back(&Inst); + + } + + if (Options.TraceDiv) + if (BinaryOperator *BO = dyn_cast(&Inst)) + if (BO->getOpcode() == Instruction::SDiv || + BO->getOpcode() == Instruction::UDiv) + DivTraceTargets.push_back(BO); + if (Options.TraceGep) + if (GetElementPtrInst *GEP = dyn_cast(&Inst)) + GepTraceTargets.push_back(GEP); + if (Options.StackDepth) + if (isa(Inst) || + (isa(Inst) && !isa(Inst))) + IsLeafFunc = false; + + } + + } + + InjectCoverage(F, BlocksToInstrument, IsLeafFunc); + InjectCoverageForIndirectCalls(F, IndirCalls); + InjectTraceForCmp(F, CmpTraceTargets); + InjectTraceForSwitch(F, SwitchTraceTargets); + InjectTraceForDiv(F, DivTraceTargets); + InjectTraceForGep(F, GepTraceTargets); + +} + +GlobalVariable *ModuleSanitizerCoverageAFL::CreateFunctionLocalArrayInSection( + size_t NumElements, Function &F, Type *Ty, const char *Section) { + + ArrayType *ArrayTy = ArrayType::get(Ty, NumElements); + auto Array = new GlobalVariable( + *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage, + Constant::getNullValue(ArrayTy), "__sancov_gen_"); + +#if LLVM_VERSION_MAJOR >= 13 + if (TargetTriple.supportsCOMDAT() && + (TargetTriple.isOSBinFormatELF() || !F.isInterposable())) + if (auto Comdat = getOrCreateFunctionComdat(F, TargetTriple)) + Array->setComdat(Comdat); +#else + if (TargetTriple.supportsCOMDAT() && !F.isInterposable()) + if (auto Comdat = + GetOrCreateFunctionComdat(F, TargetTriple, CurModuleUniqueId)) + Array->setComdat(Comdat); +#endif + + Array->setSection(getSectionName(Section)); +#if (LLVM_VERSION_MAJOR >= 11) || \ + (LLVM_VERSION_MAJOR == 10 && LLVM_VERSION_MINOR >= 1) + Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedSize())); +#else + Array->setAlignment(Align(4)); // cheating +#endif + GlobalsToAppendToUsed.push_back(Array); + GlobalsToAppendToCompilerUsed.push_back(Array); + MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F)); + Array->addMetadata(LLVMContext::MD_associated, *MD); + + return Array; + +} + +GlobalVariable *ModuleSanitizerCoverageAFL::CreatePCArray( + Function &F, ArrayRef AllBlocks) { + + size_t N = AllBlocks.size(); + assert(N); + SmallVector PCs; + IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt()); + for (size_t i = 0; i < N; i++) { + + if (&F.getEntryBlock() == AllBlocks[i]) { + + PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy)); + PCs.push_back((Constant *)IRB.CreateIntToPtr( + ConstantInt::get(IntptrTy, 1), IntptrPtrTy)); + + } else { + + PCs.push_back((Constant *)IRB.CreatePointerCast( + BlockAddress::get(AllBlocks[i]), IntptrPtrTy)); + PCs.push_back((Constant *)IRB.CreateIntToPtr( + ConstantInt::get(IntptrTy, 0), IntptrPtrTy)); + + } + + } + + auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy, + SanCovPCsSectionName); + PCArray->setInitializer( + ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs)); + PCArray->setConstant(true); + + return PCArray; + +} + +void ModuleSanitizerCoverageAFL::CreateFunctionLocalArrays( + Function &F, ArrayRef AllBlocks, uint32_t special) { + + if (Options.TracePCGuard) + FunctionGuardArray = CreateFunctionLocalArrayInSection( + AllBlocks.size() + special, F, Int32Ty, SanCovGuardsSectionName); + + if (Options.Inline8bitCounters) + Function8bitCounterArray = CreateFunctionLocalArrayInSection( + AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName); + /* + if (Options.InlineBoolFlag) + FunctionBoolArray = CreateFunctionLocalArrayInSection( + AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName); + */ + if (Options.PCTable) FunctionPCsArray = CreatePCArray(F, AllBlocks); + +} + +bool ModuleSanitizerCoverageAFL::InjectCoverage( + Function &F, ArrayRef AllBlocks, bool IsLeafFunc) { + + uint32_t cnt_cov = 0, cnt_sel = 0, cnt_sel_inc = 0; + + for (auto &BB : F) { + + for (auto &IN : BB) { + + CallInst *callInst = nullptr; + + if ((callInst = dyn_cast(&IN))) { + + Function *Callee = callInst->getCalledFunction(); + if (!Callee) continue; + if (callInst->getCallingConv() != llvm::CallingConv::C) continue; + StringRef FuncName = Callee->getName(); + if (!FuncName.compare(StringRef("dlopen")) || + !FuncName.compare(StringRef("_dlopen"))) { + + fprintf(stderr, + "WARNING: dlopen() detected. To have coverage for a library " + "that your target dlopen()'s this must either happen before " + "__AFL_INIT() or you must use AFL_PRELOAD to preload all " + "dlopen()'ed libraries!\n"); + continue; + + } + + if (FuncName.compare(StringRef("__afl_coverage_interesting"))) continue; + + cnt_cov++; + + } + + SelectInst *selectInst = nullptr; + + if ((selectInst = dyn_cast(&IN))) { + + Value *c = selectInst->getCondition(); + auto t = c->getType(); + if (t->getTypeID() == llvm::Type::IntegerTyID) { + + cnt_sel++; + cnt_sel_inc += 2; + + } + +#if (LLVM_VERSION_MAJOR >= 12) + else if (t->getTypeID() == llvm::Type::FixedVectorTyID) { + + FixedVectorType *tt = dyn_cast(t); + if (tt) { + + cnt_sel++; + cnt_sel_inc += tt->getElementCount().getKnownMinValue(); + + } + + } + +#endif + + } + + } + + } + + /* Create PCGUARD array */ + CreateFunctionLocalArrays(F, AllBlocks, cnt_cov + cnt_sel_inc); + selects += cnt_sel; + + uint32_t special = 0, local_selects = 0, skip_next = 0; + + for (auto &BB : F) { + + for (auto &IN : BB) { + + CallInst *callInst = nullptr; + + /* + std::string errMsg; + raw_string_ostream os(errMsg); + IN.print(os); + fprintf(stderr, "X: %s\n", os.str().c_str()); + */ + if ((callInst = dyn_cast(&IN))) { + + Function *Callee = callInst->getCalledFunction(); + if (!Callee) continue; + if (callInst->getCallingConv() != llvm::CallingConv::C) continue; + StringRef FuncName = Callee->getName(); + if (FuncName.compare(StringRef("__afl_coverage_interesting"))) continue; + + IRBuilder<> IRB(callInst); + + Value *GuardPtr = IRB.CreateIntToPtr( + IRB.CreateAdd( + IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), + ConstantInt::get(IntptrTy, (++special + AllBlocks.size()) * 4)), + Int32PtrTy); + + LoadInst *Idx = IRB.CreateLoad(IRB.getInt32Ty(), GuardPtr); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(Idx); + + callInst->setOperand(1, Idx); + + } + + SelectInst *selectInst = nullptr; + + if (!skip_next && (selectInst = dyn_cast(&IN))) { + + uint32_t vector_cnt = 0; + Value * condition = selectInst->getCondition(); + Value * result; + auto t = condition->getType(); + IRBuilder<> IRB(selectInst->getNextNode()); + + if (t->getTypeID() == llvm::Type::IntegerTyID) { + + auto GuardPtr1 = IRB.CreateIntToPtr( + IRB.CreateAdd( + IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), + ConstantInt::get( + IntptrTy, + (cnt_cov + ++local_selects + AllBlocks.size()) * 4)), + Int32PtrTy); + + auto GuardPtr2 = IRB.CreateIntToPtr( + IRB.CreateAdd( + IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), + ConstantInt::get( + IntptrTy, + (cnt_cov + ++local_selects + AllBlocks.size()) * 4)), + Int32PtrTy); + + result = IRB.CreateSelect(condition, GuardPtr1, GuardPtr2); + + } else + +#if LLVM_VERSION_MAJOR >= 14 + if (t->getTypeID() == llvm::Type::FixedVectorTyID) { + + FixedVectorType *tt = dyn_cast(t); + if (tt) { + + uint32_t elements = tt->getElementCount().getFixedValue(); + vector_cnt = elements; + if (elements) { + + FixedVectorType *GuardPtr1 = + FixedVectorType::get(Int32PtrTy, elements); + FixedVectorType *GuardPtr2 = + FixedVectorType::get(Int32PtrTy, elements); + Value *x, *y; + + Value *val1 = IRB.CreateIntToPtr( + IRB.CreateAdd( + IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), + ConstantInt::get( + IntptrTy, + (cnt_cov + ++local_selects + AllBlocks.size()) * 4)), + Int32PtrTy); + x = IRB.CreateInsertElement(GuardPtr1, val1, (uint64_t)0); + + Value *val2 = IRB.CreateIntToPtr( + IRB.CreateAdd( + IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), + ConstantInt::get( + IntptrTy, + (cnt_cov + ++local_selects + AllBlocks.size()) * 4)), + Int32PtrTy); + y = IRB.CreateInsertElement(GuardPtr2, val2, (uint64_t)0); + + for (uint64_t i = 1; i < elements; i++) { + + val1 = IRB.CreateIntToPtr( + IRB.CreateAdd( + IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), + ConstantInt::get(IntptrTy, (cnt_cov + ++local_selects + + AllBlocks.size()) * + 4)), + Int32PtrTy); + x = IRB.CreateInsertElement(x, val1, i); + + val2 = IRB.CreateIntToPtr( + IRB.CreateAdd( + IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), + ConstantInt::get(IntptrTy, (cnt_cov + ++local_selects + + AllBlocks.size()) * + 4)), + Int32PtrTy); + y = IRB.CreateInsertElement(y, val2, i); + + } + + /* + std::string errMsg; + raw_string_ostream os(errMsg); + x->print(os); + fprintf(stderr, "X: %s\n", os.str().c_str()); + */ + result = IRB.CreateSelect(condition, x, y); + + } + + } + + } else + +#endif + { + + unhandled++; + continue; + + } + + uint32_t vector_cur = 0; + + /* Load SHM pointer */ + + LoadInst *MapPtr = + IRB.CreateLoad(PointerType::get(Int8Ty, 0), AFLMapPtr); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(MapPtr); + + /* + std::string errMsg; + raw_string_ostream os(errMsg); + result->print(os); + fprintf(stderr, "X: %s\n", os.str().c_str()); + */ + + while (1) { + + /* Get CurLoc */ + LoadInst *CurLoc = nullptr; + Value * MapPtrIdx = nullptr; + + /* Load counter for CurLoc */ + if (!vector_cnt) { + + CurLoc = IRB.CreateLoad(IRB.getInt32Ty(), result); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(CurLoc); + MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, CurLoc); + + } else { + + auto element = IRB.CreateExtractElement(result, vector_cur++); + auto elementptr = IRB.CreateIntToPtr(element, Int32PtrTy); + auto elementld = IRB.CreateLoad(IRB.getInt32Ty(), elementptr); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(elementld); + MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, elementld); + + } + + if (use_threadsafe_counters) { + + IRB.CreateAtomicRMW(llvm::AtomicRMWInst::BinOp::Add, MapPtrIdx, One, +#if LLVM_VERSION_MAJOR >= 13 + llvm::MaybeAlign(1), +#endif + llvm::AtomicOrdering::Monotonic); + + } else { + + LoadInst *Counter = IRB.CreateLoad(IRB.getInt8Ty(), MapPtrIdx); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(Counter); + + /* Update bitmap */ + + Value *Incr = IRB.CreateAdd(Counter, One); + + if (skip_nozero == NULL) { + + auto cf = IRB.CreateICmpEQ(Incr, Zero); + auto carry = IRB.CreateZExt(cf, Int8Ty); + Incr = IRB.CreateAdd(Incr, carry); + + } + + StoreInst *StoreCtx = IRB.CreateStore(Incr, MapPtrIdx); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(StoreCtx); + + } + + if (!vector_cnt) { + + vector_cnt = 2; + break; + + } else if (vector_cnt == vector_cur) { + + break; + + } + + } + + skip_next = 1; + instr += vector_cnt; + + } else { + + skip_next = 0; + + } + + } + + } + + if (AllBlocks.empty() && !special && !local_selects) return false; + + if (!AllBlocks.empty()) + for (size_t i = 0, N = AllBlocks.size(); i < N; i++) + InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc); + + return true; + +} + +// On every indirect call we call a run-time function +// __sanitizer_cov_indir_call* with two parameters: +// - callee address, +// - global cache array that contains CacheSize pointers (zero-initialized). +// The cache is used to speed up recording the caller-callee pairs. +// The address of the caller is passed implicitly via caller PC. +// CacheSize is encoded in the name of the run-time function. +void ModuleSanitizerCoverageAFL::InjectCoverageForIndirectCalls( + Function &F, ArrayRef IndirCalls) { + + if (IndirCalls.empty()) return; + for (auto I : IndirCalls) { + + IRBuilder<> IRB(I); + CallBase & CB = cast(*I); + Value * Callee = CB.getCalledOperand(); + if (isa(Callee)) continue; + IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy)); + + } + +} + +// For every switch statement we insert a call: +// __sanitizer_cov_trace_switch(CondValue, +// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... }) + +void ModuleSanitizerCoverageAFL::InjectTraceForSwitch( + Function &, ArrayRef SwitchTraceTargets) { + + for (auto I : SwitchTraceTargets) { + + if (SwitchInst *SI = dyn_cast(I)) { + + IRBuilder<> IRB(I); + SmallVector Initializers; + Value * Cond = SI->getCondition(); + if (Cond->getType()->getScalarSizeInBits() > + Int64Ty->getScalarSizeInBits()) + continue; + Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases())); + Initializers.push_back( + ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits())); + if (Cond->getType()->getScalarSizeInBits() < + Int64Ty->getScalarSizeInBits()) + Cond = IRB.CreateIntCast(Cond, Int64Ty, false); + for (auto It : SI->cases()) { + + Constant *C = It.getCaseValue(); + if (C->getType()->getScalarSizeInBits() < + Int64Ty->getScalarSizeInBits()) + C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty); + Initializers.push_back(C); + + } + + llvm::sort(drop_begin(Initializers, 2), + [](const Constant *A, const Constant *B) { + + return cast(A)->getLimitedValue() < + cast(B)->getLimitedValue(); + + }); + + ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size()); + GlobalVariable *GV = new GlobalVariable( + *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage, + ConstantArray::get(ArrayOfInt64Ty, Initializers), + "__sancov_gen_cov_switch_values"); + IRB.CreateCall(SanCovTraceSwitchFunction, + {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)}); + + } + + } + +} + +void ModuleSanitizerCoverageAFL::InjectTraceForDiv( + Function &, ArrayRef DivTraceTargets) { + + for (auto BO : DivTraceTargets) { + + IRBuilder<> IRB(BO); + Value * A1 = BO->getOperand(1); + if (isa(A1)) continue; + if (!A1->getType()->isIntegerTy()) continue; + uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType()); + int CallbackIdx = TypeSize == 32 ? 0 : TypeSize == 64 ? 1 : -1; + if (CallbackIdx < 0) continue; + auto Ty = Type::getIntNTy(*C, TypeSize); + IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx], + {IRB.CreateIntCast(A1, Ty, true)}); + + } + +} + +void ModuleSanitizerCoverageAFL::InjectTraceForGep( + Function &, ArrayRef GepTraceTargets) { + + for (auto GEP : GepTraceTargets) { + + IRBuilder<> IRB(GEP); + for (Use &Idx : GEP->indices()) + if (!isa(Idx) && Idx->getType()->isIntegerTy()) + IRB.CreateCall(SanCovTraceGepFunction, + {IRB.CreateIntCast(Idx, IntptrTy, true)}); + + } + +} + +void ModuleSanitizerCoverageAFL::InjectTraceForCmp( + Function &, ArrayRef CmpTraceTargets) { + + for (auto I : CmpTraceTargets) { + + if (ICmpInst *ICMP = dyn_cast(I)) { + + IRBuilder<> IRB(ICMP); + Value * A0 = ICMP->getOperand(0); + Value * A1 = ICMP->getOperand(1); + if (!A0->getType()->isIntegerTy()) continue; + uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType()); + int CallbackIdx = TypeSize == 8 ? 0 + : TypeSize == 16 ? 1 + : TypeSize == 32 ? 2 + : TypeSize == 64 ? 3 + : -1; + if (CallbackIdx < 0) continue; + // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1); + auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx]; + bool FirstIsConst = isa(A0); + bool SecondIsConst = isa(A1); + // If both are const, then we don't need such a comparison. + if (FirstIsConst && SecondIsConst) continue; + // If only one is const, then make it the first callback argument. + if (FirstIsConst || SecondIsConst) { + + CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx]; + if (SecondIsConst) std::swap(A0, A1); + + } + + auto Ty = Type::getIntNTy(*C, TypeSize); + IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true), + IRB.CreateIntCast(A1, Ty, true)}); + + } + + } + +} + +void ModuleSanitizerCoverageAFL::InjectCoverageAtBlock(Function & F, + BasicBlock &BB, + size_t Idx, + bool IsLeafFunc) { + + BasicBlock::iterator IP = BB.getFirstInsertionPt(); + bool IsEntryBB = &BB == &F.getEntryBlock(); + + if (IsEntryBB) { + + // Keep allocas and llvm.localescape calls in the entry block. Even + // if we aren't splitting the block, it's nice for allocas to be before + // calls. + IP = PrepareToSplitEntryBlock(BB, IP); + + } + + IRBuilder<> IRB(&*IP); + + if (Options.TracePC) { + + IRB.CreateCall(SanCovTracePC); + // ->setCannotMerge(); // gets the PC using GET_CALLER_PC. + + } + + if (Options.TracePCGuard) { + + /* Get CurLoc */ + + Value *GuardPtr = IRB.CreateIntToPtr( + IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), + ConstantInt::get(IntptrTy, Idx * 4)), + Int32PtrTy); + + LoadInst *CurLoc = IRB.CreateLoad(IRB.getInt32Ty(), GuardPtr); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(CurLoc); + + /* Load SHM pointer */ + + LoadInst *MapPtr = IRB.CreateLoad(PointerType::get(Int8Ty, 0), AFLMapPtr); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(MapPtr); + + /* Load counter for CurLoc */ + + Value *MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, CurLoc); + + if (use_threadsafe_counters) { + + IRB.CreateAtomicRMW(llvm::AtomicRMWInst::BinOp::Add, MapPtrIdx, One, +#if LLVM_VERSION_MAJOR >= 13 + llvm::MaybeAlign(1), +#endif + llvm::AtomicOrdering::Monotonic); + + } else { + + LoadInst *Counter = IRB.CreateLoad(IRB.getInt8Ty(), MapPtrIdx); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(Counter); + + /* Update bitmap */ + + Value *Incr = IRB.CreateAdd(Counter, One); + + if (skip_nozero == NULL) { + + auto cf = IRB.CreateICmpEQ(Incr, Zero); + auto carry = IRB.CreateZExt(cf, Int8Ty); + Incr = IRB.CreateAdd(Incr, carry); + + } + + StoreInst *StoreCtx = IRB.CreateStore(Incr, MapPtrIdx); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(StoreCtx); + + } + + // done :) + + // IRB.CreateCall(SanCovTracePCGuard, Offset)->setCannotMerge(); + // IRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge(); + ++instr; + + } + + if (Options.Inline8bitCounters) { + + auto CounterPtr = IRB.CreateGEP( + Function8bitCounterArray->getValueType(), Function8bitCounterArray, + {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)}); + auto Load = IRB.CreateLoad(Int8Ty, CounterPtr); + auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1)); + auto Store = IRB.CreateStore(Inc, CounterPtr); + SetNoSanitizeMetadata(Load); + SetNoSanitizeMetadata(Store); + + } + + /* + if (Options.InlineBoolFlag) { + + auto FlagPtr = IRB.CreateGEP( + FunctionBoolArray->getValueType(), FunctionBoolArray, + {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)}); + auto Load = IRB.CreateLoad(Int1Ty, FlagPtr); + auto ThenTerm = + SplitBlockAndInsertIfThen(IRB.CreateIsNull(Load), &*IP, false); + IRBuilder<> ThenIRB(ThenTerm); + auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr); + SetNoSanitizeMetadata(Load); + SetNoSanitizeMetadata(Store); + + } + + */ + + if (Options.StackDepth && IsEntryBB && !IsLeafFunc) { + + // Check stack depth. If it's the deepest so far, record it. + Module * M = F.getParent(); + Function *GetFrameAddr = Intrinsic::getDeclaration( + M, Intrinsic::frameaddress, + IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace())); + auto FrameAddrPtr = + IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)}); + auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy); + auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack); + auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack); + auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false); + IRBuilder<> ThenIRB(ThenTerm); + auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack); + SetNoSanitizeMetadata(LowestStack); + SetNoSanitizeMetadata(Store); + + } + +} + +std::string ModuleSanitizerCoverageAFL::getSectionName( + const std::string &Section) const { + + if (TargetTriple.isOSBinFormatCOFF()) { + + if (Section == SanCovCountersSectionName) return ".SCOV$CM"; + if (Section == SanCovBoolFlagSectionName) return ".SCOV$BM"; + if (Section == SanCovPCsSectionName) return ".SCOVP$M"; + return ".SCOV$GM"; // For SanCovGuardsSectionName. + + } + + if (TargetTriple.isOSBinFormatMachO()) return "__DATA,__" + Section; + return "__" + Section; + +} + +std::string ModuleSanitizerCoverageAFL::getSectionStart( + const std::string &Section) const { + + if (TargetTriple.isOSBinFormatMachO()) + return "\1section$start$__DATA$__" + Section; + return "__start___" + Section; + +} + +std::string ModuleSanitizerCoverageAFL::getSectionEnd( + const std::string &Section) const { + + if (TargetTriple.isOSBinFormatMachO()) + return "\1section$end$__DATA$__" + Section; + return "__stop___" + Section; + +} + +#if 0 + +char ModuleSanitizerCoverageLegacyPass::ID = 0; +INITIALIZE_PASS_BEGIN(ModuleSanitizerCoverageLegacyPass, "sancov", + "Pass for instrumenting coverage on functions", false, + false) +INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) +INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) +INITIALIZE_PASS_END(ModuleSanitizerCoverageLegacyPass, "sancov", + "Pass for instrumenting coverage on functions", false, + false) +ModulePass *llvm::createModuleSanitizerCoverageLegacyPassPass( + const SanitizerCoverageOptions &Options, + const std::vector &AllowlistFiles, + const std::vector &BlocklistFiles) { + + return new ModuleSanitizerCoverageLegacyPass(Options, AllowlistFiles, + BlocklistFiles); + +} + +#endif + diff --git a/instrumentation/SanitizerCoveragePCGUARD.so.cc b/instrumentation/SanitizerCoveragePCGUARD.so.cc index d3529fbc..f87bc068 100644 --- a/instrumentation/SanitizerCoveragePCGUARD.so.cc +++ b/instrumentation/SanitizerCoveragePCGUARD.so.cc @@ -281,6 +281,8 @@ class ModuleSanitizerCoverageLegacyPass : public ModulePass { PreservedAnalyses ModuleSanitizerCoveragePass::run(Module & M, ModuleAnalysisManager &MAM) { + fprintf(stderr, "ModuleSanitizerCoveragePass::run is called!\n"); + ModuleSanitizerCoverage ModuleSancov(Options #if (LLVM_VERSION_MAJOR >= 11) , @@ -1484,12 +1486,12 @@ std::string ModuleSanitizerCoverage::getSectionEnd( } char ModuleSanitizerCoverageLegacyPass::ID = 0; -INITIALIZE_PASS_BEGIN(ModuleSanitizerCoverageLegacyPass, "sancov", +INITIALIZE_PASS_BEGIN(ModuleSanitizerCoverageLegacyPass, "sancovAFL", "Pass for instrumenting coverage on functions", false, false) INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) -INITIALIZE_PASS_END(ModuleSanitizerCoverageLegacyPass, "sancov", +INITIALIZE_PASS_END(ModuleSanitizerCoverageLegacyPass, "sancovAFL", "Pass for instrumenting coverage on functions", false, false) ModulePass *llvm::createModuleSanitizerCoverageLegacyPassPass( From 59eaed2f70cd495092d747fd872d429e14f4d6a9 Mon Sep 17 00:00:00 2001 From: vanhauser-thc Date: Thu, 17 Mar 2022 13:52:48 +0100 Subject: [PATCH 09/11] make pcguard work --- ...SanitizerCoveragePCGUARD-alternative.so.cc | 1514 ----------------- .../SanitizerCoveragePCGUARD.so.cc | 142 +- src/afl-cc.c | 6 + 3 files changed, 80 insertions(+), 1582 deletions(-) delete mode 100644 instrumentation/SanitizerCoveragePCGUARD-alternative.so.cc diff --git a/instrumentation/SanitizerCoveragePCGUARD-alternative.so.cc b/instrumentation/SanitizerCoveragePCGUARD-alternative.so.cc deleted file mode 100644 index 982f610a..00000000 --- a/instrumentation/SanitizerCoveragePCGUARD-alternative.so.cc +++ /dev/null @@ -1,1514 +0,0 @@ -//===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// Coverage instrumentation done on LLVM IR level, works with Sanitizers. -// -//===----------------------------------------------------------------------===// - -#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h" -#include "llvm/ADT/ArrayRef.h" -#include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/Triple.h" -#include "llvm/Analysis/EHPersonalities.h" -#include "llvm/Analysis/PostDominators.h" -#include "llvm/IR/CFG.h" -#include "llvm/IR/Constant.h" -#include "llvm/IR/DataLayout.h" -#include "llvm/IR/DebugInfo.h" -#include "llvm/IR/Dominators.h" -#include "llvm/IR/Function.h" -#include "llvm/IR/GlobalVariable.h" -#include "llvm/IR/IRBuilder.h" -#include "llvm/IR/InlineAsm.h" -#include "llvm/IR/IntrinsicInst.h" -#include "llvm/IR/Intrinsics.h" -#include "llvm/IR/LLVMContext.h" -#include "llvm/IR/MDBuilder.h" -#include "llvm/IR/Mangler.h" -#include "llvm/IR/Module.h" -#include "llvm/IR/PassManager.h" -#include "llvm/IR/Type.h" -#include "llvm/InitializePasses.h" -#include "llvm/Support/CommandLine.h" -#include "llvm/Support/Debug.h" -#include "llvm/Support/SpecialCaseList.h" -#include "llvm/Support/VirtualFileSystem.h" -#include "llvm/Support/raw_ostream.h" -#include "llvm/Transforms/Instrumentation.h" -#include "llvm/Transforms/Utils/BasicBlockUtils.h" -#include "llvm/Transforms/Utils/ModuleUtils.h" -#include "llvm/Passes/PassPlugin.h" -#include "llvm/Passes/PassBuilder.h" -#include "llvm/IR/PassManager.h" - -#include "config.h" -#include "debug.h" -#include "afl-llvm-common.h" - -using namespace llvm; - -#define DEBUG_TYPE "sancov" - -const char SanCovTracePCIndirName[] = "__sanitizer_cov_trace_pc_indir"; -const char SanCovTracePCName[] = "__sanitizer_cov_trace_pc"; -const char SanCovTraceCmp1[] = "__sanitizer_cov_trace_cmp1"; -const char SanCovTraceCmp2[] = "__sanitizer_cov_trace_cmp2"; -const char SanCovTraceCmp4[] = "__sanitizer_cov_trace_cmp4"; -const char SanCovTraceCmp8[] = "__sanitizer_cov_trace_cmp8"; -const char SanCovTraceConstCmp1[] = "__sanitizer_cov_trace_const_cmp1"; -const char SanCovTraceConstCmp2[] = "__sanitizer_cov_trace_const_cmp2"; -const char SanCovTraceConstCmp4[] = "__sanitizer_cov_trace_const_cmp4"; -const char SanCovTraceConstCmp8[] = "__sanitizer_cov_trace_const_cmp8"; -const char SanCovTraceDiv4[] = "__sanitizer_cov_trace_div4"; -const char SanCovTraceDiv8[] = "__sanitizer_cov_trace_div8"; -const char SanCovTraceGep[] = "__sanitizer_cov_trace_gep"; -const char SanCovTraceSwitchName[] = "__sanitizer_cov_trace_switch"; -const char SanCovModuleCtorTracePcGuardName[] = - "sancov.module_ctor_trace_pc_guard"; -const char SanCovModuleCtor8bitCountersName[] = - "sancov.module_ctor_8bit_counters"; -const char SanCovModuleCtorBoolFlagName[] = "sancov.module_ctor_bool_flag"; -static const uint64_t SanCtorAndDtorPriority = 2; - -const char SanCovTracePCGuardName[] = "__sanitizer_cov_trace_pc_guard"; -const char SanCovTracePCGuardInitName[] = "__sanitizer_cov_trace_pc_guard_init"; -const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init"; -const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init"; -const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init"; - -const char SanCovGuardsSectionName[] = "sancov_guards"; -const char SanCovCountersSectionName[] = "sancov_cntrs"; -const char SanCovBoolFlagSectionName[] = "sancov_bools"; -const char SanCovPCsSectionName[] = "sancov_pcs"; - -const char SanCovLowestStackName[] = "__sancov_lowest_stack"; - -static const char *skip_nozero; -static const char *use_threadsafe_counters; - -namespace { - -SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) { - - // Sets CoverageType and IndirectCalls. - // SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel); - Options.CoverageType = - SanitizerCoverageOptions::SCK_Edge; // std::max(Options.CoverageType, - // CLOpts.CoverageType); - Options.IndirectCalls = false; // CLOpts.IndirectCalls; - Options.TraceCmp = false; //|= ClCMPTracing; - Options.TraceDiv = false; //|= ClDIVTracing; - Options.TraceGep = false; //|= ClGEPTracing; - Options.TracePC = false; //|= ClTracePC; - Options.TracePCGuard = true; // |= ClTracePCGuard; - Options.Inline8bitCounters = 0; //|= ClInline8bitCounters; - // Options.InlineBoolFlag = 0; //|= ClInlineBoolFlag; - Options.PCTable = false; //|= ClCreatePCTable; - Options.NoPrune = false; //|= !ClPruneBlocks; - Options.StackDepth = false; //|= ClStackDepth; - if (!Options.TracePCGuard && !Options.TracePC && - !Options.Inline8bitCounters && !Options.StackDepth /*&& - !Options.InlineBoolFlag*/) - Options.TracePCGuard = true; // TracePCGuard is default. - - return Options; - -} - -using DomTreeCallback = function_ref; -using PostDomTreeCallback = - function_ref; - -class ModuleSanitizerCoverageAFL - : public PassInfoMixin { - - public: - ModuleSanitizerCoverageAFL( - const SanitizerCoverageOptions &Options = SanitizerCoverageOptions()) - : Options(OverrideFromCL(Options)) { - - } - - PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM); - - bool instrumentModule(Module &M, DomTreeCallback DTCallback, - PostDomTreeCallback PDTCallback); - - private: - void instrumentFunction(Function &F, DomTreeCallback DTCallback, - PostDomTreeCallback PDTCallback); - void InjectCoverageForIndirectCalls(Function & F, - ArrayRef IndirCalls); - void InjectTraceForCmp(Function &F, ArrayRef CmpTraceTargets); - void InjectTraceForDiv(Function & F, - ArrayRef DivTraceTargets); - void InjectTraceForGep(Function & F, - ArrayRef GepTraceTargets); - void InjectTraceForSwitch(Function & F, - ArrayRef SwitchTraceTargets); - bool InjectCoverage(Function &F, ArrayRef AllBlocks, - bool IsLeafFunc = true); - GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements, - Function &F, Type *Ty, - const char *Section); - GlobalVariable *CreatePCArray(Function &F, ArrayRef AllBlocks); - void CreateFunctionLocalArrays(Function &F, ArrayRef AllBlocks, - uint32_t special); - void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx, - bool IsLeafFunc = true); - Function *CreateInitCallsForSections(Module &M, const char *CtorName, - const char *InitFunctionName, Type *Ty, - const char *Section); - std::pair CreateSecStartEnd(Module &M, const char *Section, - Type *Ty); - - void SetNoSanitizeMetadata(Instruction *I) { - - I->setMetadata(I->getModule()->getMDKindID("nosanitize"), - MDNode::get(*C, None)); - - } - - std::string getSectionName(const std::string &Section) const; - std::string getSectionStart(const std::string &Section) const; - std::string getSectionEnd(const std::string &Section) const; - FunctionCallee SanCovTracePCIndir; - FunctionCallee SanCovTracePC, SanCovTracePCGuard; - FunctionCallee SanCovTraceCmpFunction[4]; - FunctionCallee SanCovTraceConstCmpFunction[4]; - FunctionCallee SanCovTraceDivFunction[2]; - FunctionCallee SanCovTraceGepFunction; - FunctionCallee SanCovTraceSwitchFunction; - GlobalVariable *SanCovLowestStack; - Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy, - *Int16Ty, *Int8Ty, *Int8PtrTy, *Int1Ty, *Int1PtrTy; - Module * CurModule; - std::string CurModuleUniqueId; - Triple TargetTriple; - LLVMContext * C; - const DataLayout *DL; - - GlobalVariable *FunctionGuardArray; // for trace-pc-guard. - GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters. - GlobalVariable *FunctionBoolArray; // for inline-bool-flag. - GlobalVariable *FunctionPCsArray; // for pc-table. - SmallVector GlobalsToAppendToUsed; - SmallVector GlobalsToAppendToCompilerUsed; - - SanitizerCoverageOptions Options; - - uint32_t instr = 0, selects = 0, unhandled = 0; - GlobalVariable *AFLMapPtr = NULL; - ConstantInt * One = NULL; - ConstantInt * Zero = NULL; - -}; - -class ModuleSanitizerCoverageLegacyPass : public ModulePass { - - public: - ModuleSanitizerCoverageLegacyPass( - const SanitizerCoverageOptions &Options = SanitizerCoverageOptions()) - : ModulePass(ID), Options(Options) { - - initializeModuleSanitizerCoverageLegacyPassPass( - *PassRegistry::getPassRegistry()); - - } - - bool runOnModule(Module &M) override { - - ModuleSanitizerCoverageAFL ModuleSancov(Options); - auto DTCallback = [this](Function &F) -> const DominatorTree * { - - return &this->getAnalysis(F).getDomTree(); - - }; - - auto PDTCallback = [this](Function &F) -> const PostDominatorTree * { - - return &this->getAnalysis(F) - .getPostDomTree(); - - }; - - return ModuleSancov.instrumentModule(M, DTCallback, PDTCallback); - - } - - static char ID; // Pass identification, replacement for typeid - StringRef getPassName() const override { - - return "ModuleSanitizerCoverage"; - - } - - void getAnalysisUsage(AnalysisUsage &AU) const override { - - AU.addRequired(); - AU.addRequired(); - - } - - private: - SanitizerCoverageOptions Options; - -}; - -} // namespace - -#if 1 - -extern "C" ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK -llvmGetPassPluginInfo() { - - return {LLVM_PLUGIN_API_VERSION, "SanitizerCoveragePCGUARD", "v0.1", - /* lambda to insert our pass into the pass pipeline. */ - [](PassBuilder &PB) { - - #if LLVM_VERSION_MAJOR <= 13 - using OptimizationLevel = typename PassBuilder::OptimizationLevel; - #endif - PB.registerOptimizerLastEPCallback( - [](ModulePassManager &MPM, OptimizationLevel OL) { - - MPM.addPass(ModuleSanitizerCoverageAFL()); - - }); - - }}; - -} - -#endif - -PreservedAnalyses ModuleSanitizerCoverageAFL::run(Module & M, - ModuleAnalysisManager &MAM) { - - fprintf(stderr, "IS CALLED!\n"); - - ModuleSanitizerCoverageAFL ModuleSancov(Options); - auto &FAM = MAM.getResult(M).getManager(); - auto DTCallback = [&FAM](Function &F) -> const DominatorTree * { - - return &FAM.getResult(F); - - }; - - auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree * { - - return &FAM.getResult(F); - - }; - - if (ModuleSancov.instrumentModule(M, DTCallback, PDTCallback)) - return PreservedAnalyses::none(); - return PreservedAnalyses::all(); - -} - -std::pair ModuleSanitizerCoverageAFL::CreateSecStartEnd( - Module &M, const char *Section, Type *Ty) { - - GlobalVariable *SecStart = new GlobalVariable( - M, Ty->getPointerElementType(), false, - GlobalVariable::ExternalWeakLinkage, nullptr, getSectionStart(Section)); - SecStart->setVisibility(GlobalValue::HiddenVisibility); - GlobalVariable *SecEnd = new GlobalVariable( - M, Ty->getPointerElementType(), false, - GlobalVariable::ExternalWeakLinkage, nullptr, getSectionEnd(Section)); - SecEnd->setVisibility(GlobalValue::HiddenVisibility); - IRBuilder<> IRB(M.getContext()); - if (!TargetTriple.isOSBinFormatCOFF()) - return std::make_pair(SecStart, SecEnd); - - // Account for the fact that on windows-msvc __start_* symbols actually - // point to a uint64_t before the start of the array. - auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy); - auto GEP = IRB.CreateGEP(Int8Ty, SecStartI8Ptr, - ConstantInt::get(IntptrTy, sizeof(uint64_t))); - return std::make_pair(IRB.CreatePointerCast(GEP, Ty), SecEnd); - -} - -Function *ModuleSanitizerCoverageAFL::CreateInitCallsForSections( - Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty, - const char *Section) { - - auto SecStartEnd = CreateSecStartEnd(M, Section, Ty); - auto SecStart = SecStartEnd.first; - auto SecEnd = SecStartEnd.second; - Function *CtorFunc; - std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions( - M, CtorName, InitFunctionName, {Ty, Ty}, {SecStart, SecEnd}); - assert(CtorFunc->getName() == CtorName); - - if (TargetTriple.supportsCOMDAT()) { - - // Use comdat to dedup CtorFunc. - CtorFunc->setComdat(M.getOrInsertComdat(CtorName)); - appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc); - - } else { - - appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority); - - } - - if (TargetTriple.isOSBinFormatCOFF()) { - - // In COFF files, if the contructors are set as COMDAT (they are because - // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced - // functions and data) is used, the constructors get stripped. To prevent - // this, give the constructors weak ODR linkage and ensure the linker knows - // to include the sancov constructor. This way the linker can deduplicate - // the constructors but always leave one copy. - CtorFunc->setLinkage(GlobalValue::WeakODRLinkage); - appendToUsed(M, CtorFunc); - - } - - return CtorFunc; - -} - -bool ModuleSanitizerCoverageAFL::instrumentModule( - Module &M, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) { - - setvbuf(stdout, NULL, _IONBF, 0); - if (getenv("AFL_DEBUG")) debug = 1; - - if ((isatty(2) && !getenv("AFL_QUIET")) || debug) { - - SAYF(cCYA "SanitizerCoveragePCGUARD" VERSION cRST "\n"); - - } else - - be_quiet = 1; - - skip_nozero = getenv("AFL_LLVM_SKIP_NEVERZERO"); - use_threadsafe_counters = getenv("AFL_LLVM_THREADSAFE_INST"); - - initInstrumentList(); - scanForDangerousFunctions(&M); - - if (debug) { - - fprintf(stderr, - "SANCOV: covtype:%u indirect:%d stack:%d noprune:%d " - "createtable:%d tracepcguard:%d tracepc:%d\n", - Options.CoverageType, Options.IndirectCalls == true ? 1 : 0, - Options.StackDepth == true ? 1 : 0, Options.NoPrune == true ? 1 : 0, - // Options.InlineBoolFlag == true ? 1 : 0, - Options.PCTable == true ? 1 : 0, - Options.TracePCGuard == true ? 1 : 0, - Options.TracePC == true ? 1 : 0); - - } - - if (Options.CoverageType == SanitizerCoverageOptions::SCK_None) return false; - C = &(M.getContext()); - DL = &M.getDataLayout(); - CurModule = &M; - CurModuleUniqueId = getUniqueModuleId(CurModule); - TargetTriple = Triple(M.getTargetTriple()); - FunctionGuardArray = nullptr; - Function8bitCounterArray = nullptr; - FunctionBoolArray = nullptr; - FunctionPCsArray = nullptr; - IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits()); - IntptrPtrTy = PointerType::getUnqual(IntptrTy); - Type * VoidTy = Type::getVoidTy(*C); - IRBuilder<> IRB(*C); - Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty()); - Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty()); - Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty()); - Int1PtrTy = PointerType::getUnqual(IRB.getInt1Ty()); - Int64Ty = IRB.getInt64Ty(); - Int32Ty = IRB.getInt32Ty(); - Int16Ty = IRB.getInt16Ty(); - Int8Ty = IRB.getInt8Ty(); - Int1Ty = IRB.getInt1Ty(); - LLVMContext &Ctx = M.getContext(); - - AFLMapPtr = - new GlobalVariable(M, PointerType::get(Int8Ty, 0), false, - GlobalValue::ExternalLinkage, 0, "__afl_area_ptr"); - One = ConstantInt::get(IntegerType::getInt8Ty(Ctx), 1); - Zero = ConstantInt::get(IntegerType::getInt8Ty(Ctx), 0); - - SanCovTracePCIndir = - M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy); - // Make sure smaller parameters are zero-extended to i64 if required by the - // target ABI. - AttributeList SanCovTraceCmpZeroExtAL; - SanCovTraceCmpZeroExtAL = - SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt); - SanCovTraceCmpZeroExtAL = - SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt); - - SanCovTraceCmpFunction[0] = - M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy, - IRB.getInt8Ty(), IRB.getInt8Ty()); - SanCovTraceCmpFunction[1] = - M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy, - IRB.getInt16Ty(), IRB.getInt16Ty()); - SanCovTraceCmpFunction[2] = - M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy, - IRB.getInt32Ty(), IRB.getInt32Ty()); - SanCovTraceCmpFunction[3] = - M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty); - - SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction( - SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty); - SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction( - SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty); - SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction( - SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty); - SanCovTraceConstCmpFunction[3] = - M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty); - - { - - AttributeList AL; - AL = AL.addParamAttribute(*C, 0, Attribute::ZExt); - SanCovTraceDivFunction[0] = - M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty()); - - } - - SanCovTraceDivFunction[1] = - M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty); - SanCovTraceGepFunction = - M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy); - SanCovTraceSwitchFunction = - M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy); - - Constant *SanCovLowestStackConstant = - M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy); - SanCovLowestStack = dyn_cast(SanCovLowestStackConstant); - if (!SanCovLowestStack) { - - C->emitError(StringRef("'") + SanCovLowestStackName + - "' should not be declared by the user"); - return true; - - } - - SanCovLowestStack->setThreadLocalMode( - GlobalValue::ThreadLocalMode::InitialExecTLSModel); - if (Options.StackDepth && !SanCovLowestStack->isDeclaration()) - SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy)); - - SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy); - SanCovTracePCGuard = - M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy); - - for (auto &F : M) - instrumentFunction(F, DTCallback, PDTCallback); - - Function *Ctor = nullptr; - - if (FunctionGuardArray) - Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName, - SanCovTracePCGuardInitName, Int32PtrTy, - SanCovGuardsSectionName); - if (Function8bitCounterArray) - Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName, - SanCov8bitCountersInitName, Int8PtrTy, - SanCovCountersSectionName); - if (FunctionBoolArray) { - - Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName, - SanCovBoolFlagInitName, Int1PtrTy, - SanCovBoolFlagSectionName); - - } - - if (Ctor && Options.PCTable) { - - auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy); - FunctionCallee InitFunction = declareSanitizerInitFunction( - M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy}); - IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator()); - IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second}); - - } - - // We don't reference these arrays directly in any of our runtime functions, - // so we need to prevent them from being dead stripped. - if (TargetTriple.isOSBinFormatMachO()) appendToUsed(M, GlobalsToAppendToUsed); - appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed); - - if (!be_quiet) { - - if (!instr) - WARNF("No instrumentation targets found."); - else { - - char modeline[100]; - snprintf(modeline, sizeof(modeline), "%s%s%s%s%s%s", - getenv("AFL_HARDEN") ? "hardened" : "non-hardened", - getenv("AFL_USE_ASAN") ? ", ASAN" : "", - getenv("AFL_USE_MSAN") ? ", MSAN" : "", - getenv("AFL_USE_TSAN") ? ", TSAN" : "", - getenv("AFL_USE_CFISAN") ? ", CFISAN" : "", - getenv("AFL_USE_UBSAN") ? ", UBSAN" : ""); - OKF("Instrumented %u locations with no collisions (%s mode) of which are " - "%u handled and %u unhandled selects.", - instr, modeline, selects, unhandled); - - } - - } - - return true; - -} - -// True if block has successors and it dominates all of them. -bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) { - - if (succ_begin(BB) == succ_end(BB)) return false; - - for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) { - - if (!DT->dominates(BB, SUCC)) return false; - - } - - return true; - -} - -// True if block has predecessors and it postdominates all of them. -bool isFullPostDominator(const BasicBlock *BB, const PostDominatorTree *PDT) { - - if (pred_begin(BB) == pred_end(BB)) return false; - - for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) { - - if (!PDT->dominates(BB, PRED)) return false; - - } - - return true; - -} - -bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB, - const DominatorTree * DT, - const PostDominatorTree * PDT, - const SanitizerCoverageOptions &Options) { - - // Don't insert coverage for blocks containing nothing but unreachable: we - // will never call __sanitizer_cov() for them, so counting them in - // NumberOfInstrumentedBlocks() might complicate calculation of code coverage - // percentage. Also, unreachable instructions frequently have no debug - // locations. - if (isa(BB->getFirstNonPHIOrDbgOrLifetime())) return false; - - // Don't insert coverage into blocks without a valid insertion point - // (catchswitch blocks). - if (BB->getFirstInsertionPt() == BB->end()) return false; - - if (Options.NoPrune || &F.getEntryBlock() == BB) return true; - - if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function && - &F.getEntryBlock() != BB) - return false; - - // Do not instrument full dominators, or full post-dominators with multiple - // predecessors. - return !isFullDominator(BB, DT) && - !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor()); - -} - -// Returns true iff From->To is a backedge. -// A twist here is that we treat From->To as a backedge if -// * To dominates From or -// * To->UniqueSuccessor dominates From -bool IsBackEdge(BasicBlock *From, BasicBlock *To, const DominatorTree *DT) { - - if (DT->dominates(To, From)) return true; - if (auto Next = To->getUniqueSuccessor()) - if (DT->dominates(Next, From)) return true; - return false; - -} - -// Prunes uninteresting Cmp instrumentation: -// * CMP instructions that feed into loop backedge branch. -// -// Note that Cmp pruning is controlled by the same flag as the -// BB pruning. -bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT, - const SanitizerCoverageOptions &Options) { - - if (!Options.NoPrune) - if (CMP->hasOneUse()) - if (auto BR = dyn_cast(CMP->user_back())) - for (BasicBlock *B : BR->successors()) - if (IsBackEdge(BR->getParent(), B, DT)) return false; - return true; - -} - -void ModuleSanitizerCoverageAFL::instrumentFunction( - Function &F, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) { - - if (F.empty()) return; - if (!isInInstrumentList(&F, FMNAME)) return; - - if (F.getName().find(".module_ctor") != std::string::npos) - return; // Should not instrument sanitizer init functions. - if (F.getName().startswith("__sanitizer_")) - return; // Don't instrument __sanitizer_* callbacks. - // Don't touch available_externally functions, their actual body is elewhere. - if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return; - // Don't instrument MSVC CRT configuration helpers. They may run before normal - // initialization. - if (F.getName() == "__local_stdio_printf_options" || - F.getName() == "__local_stdio_scanf_options") - return; - if (isa(F.getEntryBlock().getTerminator())) return; - // Don't instrument functions using SEH for now. Splitting basic blocks like - // we do for coverage breaks WinEHPrepare. - // FIXME: Remove this when SEH no longer uses landingpad pattern matching. - if (F.hasPersonalityFn() && - isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn()))) - return; - if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge) - SplitAllCriticalEdges( - F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests()); - SmallVector IndirCalls; - SmallVector BlocksToInstrument; - SmallVector CmpTraceTargets; - SmallVector SwitchTraceTargets; - SmallVector DivTraceTargets; - SmallVector GepTraceTargets; - - const DominatorTree * DT = DTCallback(F); - const PostDominatorTree *PDT = PDTCallback(F); - bool IsLeafFunc = true; - - for (auto &BB : F) { - - if (shouldInstrumentBlock(F, &BB, DT, PDT, Options)) - BlocksToInstrument.push_back(&BB); - for (auto &Inst : BB) { - - if (Options.IndirectCalls) { - - CallBase *CB = dyn_cast(&Inst); - if (CB && !CB->getCalledFunction()) IndirCalls.push_back(&Inst); - - } - - if (Options.TraceCmp) { - - if (ICmpInst *CMP = dyn_cast(&Inst)) - if (IsInterestingCmp(CMP, DT, Options)) - CmpTraceTargets.push_back(&Inst); - if (isa(&Inst)) SwitchTraceTargets.push_back(&Inst); - - } - - if (Options.TraceDiv) - if (BinaryOperator *BO = dyn_cast(&Inst)) - if (BO->getOpcode() == Instruction::SDiv || - BO->getOpcode() == Instruction::UDiv) - DivTraceTargets.push_back(BO); - if (Options.TraceGep) - if (GetElementPtrInst *GEP = dyn_cast(&Inst)) - GepTraceTargets.push_back(GEP); - if (Options.StackDepth) - if (isa(Inst) || - (isa(Inst) && !isa(Inst))) - IsLeafFunc = false; - - } - - } - - InjectCoverage(F, BlocksToInstrument, IsLeafFunc); - InjectCoverageForIndirectCalls(F, IndirCalls); - InjectTraceForCmp(F, CmpTraceTargets); - InjectTraceForSwitch(F, SwitchTraceTargets); - InjectTraceForDiv(F, DivTraceTargets); - InjectTraceForGep(F, GepTraceTargets); - -} - -GlobalVariable *ModuleSanitizerCoverageAFL::CreateFunctionLocalArrayInSection( - size_t NumElements, Function &F, Type *Ty, const char *Section) { - - ArrayType *ArrayTy = ArrayType::get(Ty, NumElements); - auto Array = new GlobalVariable( - *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage, - Constant::getNullValue(ArrayTy), "__sancov_gen_"); - -#if LLVM_VERSION_MAJOR >= 13 - if (TargetTriple.supportsCOMDAT() && - (TargetTriple.isOSBinFormatELF() || !F.isInterposable())) - if (auto Comdat = getOrCreateFunctionComdat(F, TargetTriple)) - Array->setComdat(Comdat); -#else - if (TargetTriple.supportsCOMDAT() && !F.isInterposable()) - if (auto Comdat = - GetOrCreateFunctionComdat(F, TargetTriple, CurModuleUniqueId)) - Array->setComdat(Comdat); -#endif - - Array->setSection(getSectionName(Section)); -#if (LLVM_VERSION_MAJOR >= 11) || \ - (LLVM_VERSION_MAJOR == 10 && LLVM_VERSION_MINOR >= 1) - Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedSize())); -#else - Array->setAlignment(Align(4)); // cheating -#endif - GlobalsToAppendToUsed.push_back(Array); - GlobalsToAppendToCompilerUsed.push_back(Array); - MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F)); - Array->addMetadata(LLVMContext::MD_associated, *MD); - - return Array; - -} - -GlobalVariable *ModuleSanitizerCoverageAFL::CreatePCArray( - Function &F, ArrayRef AllBlocks) { - - size_t N = AllBlocks.size(); - assert(N); - SmallVector PCs; - IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt()); - for (size_t i = 0; i < N; i++) { - - if (&F.getEntryBlock() == AllBlocks[i]) { - - PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy)); - PCs.push_back((Constant *)IRB.CreateIntToPtr( - ConstantInt::get(IntptrTy, 1), IntptrPtrTy)); - - } else { - - PCs.push_back((Constant *)IRB.CreatePointerCast( - BlockAddress::get(AllBlocks[i]), IntptrPtrTy)); - PCs.push_back((Constant *)IRB.CreateIntToPtr( - ConstantInt::get(IntptrTy, 0), IntptrPtrTy)); - - } - - } - - auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy, - SanCovPCsSectionName); - PCArray->setInitializer( - ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs)); - PCArray->setConstant(true); - - return PCArray; - -} - -void ModuleSanitizerCoverageAFL::CreateFunctionLocalArrays( - Function &F, ArrayRef AllBlocks, uint32_t special) { - - if (Options.TracePCGuard) - FunctionGuardArray = CreateFunctionLocalArrayInSection( - AllBlocks.size() + special, F, Int32Ty, SanCovGuardsSectionName); - - if (Options.Inline8bitCounters) - Function8bitCounterArray = CreateFunctionLocalArrayInSection( - AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName); - /* - if (Options.InlineBoolFlag) - FunctionBoolArray = CreateFunctionLocalArrayInSection( - AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName); - */ - if (Options.PCTable) FunctionPCsArray = CreatePCArray(F, AllBlocks); - -} - -bool ModuleSanitizerCoverageAFL::InjectCoverage( - Function &F, ArrayRef AllBlocks, bool IsLeafFunc) { - - uint32_t cnt_cov = 0, cnt_sel = 0, cnt_sel_inc = 0; - - for (auto &BB : F) { - - for (auto &IN : BB) { - - CallInst *callInst = nullptr; - - if ((callInst = dyn_cast(&IN))) { - - Function *Callee = callInst->getCalledFunction(); - if (!Callee) continue; - if (callInst->getCallingConv() != llvm::CallingConv::C) continue; - StringRef FuncName = Callee->getName(); - if (!FuncName.compare(StringRef("dlopen")) || - !FuncName.compare(StringRef("_dlopen"))) { - - fprintf(stderr, - "WARNING: dlopen() detected. To have coverage for a library " - "that your target dlopen()'s this must either happen before " - "__AFL_INIT() or you must use AFL_PRELOAD to preload all " - "dlopen()'ed libraries!\n"); - continue; - - } - - if (FuncName.compare(StringRef("__afl_coverage_interesting"))) continue; - - cnt_cov++; - - } - - SelectInst *selectInst = nullptr; - - if ((selectInst = dyn_cast(&IN))) { - - Value *c = selectInst->getCondition(); - auto t = c->getType(); - if (t->getTypeID() == llvm::Type::IntegerTyID) { - - cnt_sel++; - cnt_sel_inc += 2; - - } - -#if (LLVM_VERSION_MAJOR >= 12) - else if (t->getTypeID() == llvm::Type::FixedVectorTyID) { - - FixedVectorType *tt = dyn_cast(t); - if (tt) { - - cnt_sel++; - cnt_sel_inc += tt->getElementCount().getKnownMinValue(); - - } - - } - -#endif - - } - - } - - } - - /* Create PCGUARD array */ - CreateFunctionLocalArrays(F, AllBlocks, cnt_cov + cnt_sel_inc); - selects += cnt_sel; - - uint32_t special = 0, local_selects = 0, skip_next = 0; - - for (auto &BB : F) { - - for (auto &IN : BB) { - - CallInst *callInst = nullptr; - - /* - std::string errMsg; - raw_string_ostream os(errMsg); - IN.print(os); - fprintf(stderr, "X: %s\n", os.str().c_str()); - */ - if ((callInst = dyn_cast(&IN))) { - - Function *Callee = callInst->getCalledFunction(); - if (!Callee) continue; - if (callInst->getCallingConv() != llvm::CallingConv::C) continue; - StringRef FuncName = Callee->getName(); - if (FuncName.compare(StringRef("__afl_coverage_interesting"))) continue; - - IRBuilder<> IRB(callInst); - - Value *GuardPtr = IRB.CreateIntToPtr( - IRB.CreateAdd( - IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), - ConstantInt::get(IntptrTy, (++special + AllBlocks.size()) * 4)), - Int32PtrTy); - - LoadInst *Idx = IRB.CreateLoad(IRB.getInt32Ty(), GuardPtr); - ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(Idx); - - callInst->setOperand(1, Idx); - - } - - SelectInst *selectInst = nullptr; - - if (!skip_next && (selectInst = dyn_cast(&IN))) { - - uint32_t vector_cnt = 0; - Value * condition = selectInst->getCondition(); - Value * result; - auto t = condition->getType(); - IRBuilder<> IRB(selectInst->getNextNode()); - - if (t->getTypeID() == llvm::Type::IntegerTyID) { - - auto GuardPtr1 = IRB.CreateIntToPtr( - IRB.CreateAdd( - IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), - ConstantInt::get( - IntptrTy, - (cnt_cov + ++local_selects + AllBlocks.size()) * 4)), - Int32PtrTy); - - auto GuardPtr2 = IRB.CreateIntToPtr( - IRB.CreateAdd( - IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), - ConstantInt::get( - IntptrTy, - (cnt_cov + ++local_selects + AllBlocks.size()) * 4)), - Int32PtrTy); - - result = IRB.CreateSelect(condition, GuardPtr1, GuardPtr2); - - } else - -#if LLVM_VERSION_MAJOR >= 14 - if (t->getTypeID() == llvm::Type::FixedVectorTyID) { - - FixedVectorType *tt = dyn_cast(t); - if (tt) { - - uint32_t elements = tt->getElementCount().getFixedValue(); - vector_cnt = elements; - if (elements) { - - FixedVectorType *GuardPtr1 = - FixedVectorType::get(Int32PtrTy, elements); - FixedVectorType *GuardPtr2 = - FixedVectorType::get(Int32PtrTy, elements); - Value *x, *y; - - Value *val1 = IRB.CreateIntToPtr( - IRB.CreateAdd( - IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), - ConstantInt::get( - IntptrTy, - (cnt_cov + ++local_selects + AllBlocks.size()) * 4)), - Int32PtrTy); - x = IRB.CreateInsertElement(GuardPtr1, val1, (uint64_t)0); - - Value *val2 = IRB.CreateIntToPtr( - IRB.CreateAdd( - IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), - ConstantInt::get( - IntptrTy, - (cnt_cov + ++local_selects + AllBlocks.size()) * 4)), - Int32PtrTy); - y = IRB.CreateInsertElement(GuardPtr2, val2, (uint64_t)0); - - for (uint64_t i = 1; i < elements; i++) { - - val1 = IRB.CreateIntToPtr( - IRB.CreateAdd( - IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), - ConstantInt::get(IntptrTy, (cnt_cov + ++local_selects + - AllBlocks.size()) * - 4)), - Int32PtrTy); - x = IRB.CreateInsertElement(x, val1, i); - - val2 = IRB.CreateIntToPtr( - IRB.CreateAdd( - IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), - ConstantInt::get(IntptrTy, (cnt_cov + ++local_selects + - AllBlocks.size()) * - 4)), - Int32PtrTy); - y = IRB.CreateInsertElement(y, val2, i); - - } - - /* - std::string errMsg; - raw_string_ostream os(errMsg); - x->print(os); - fprintf(stderr, "X: %s\n", os.str().c_str()); - */ - result = IRB.CreateSelect(condition, x, y); - - } - - } - - } else - -#endif - { - - unhandled++; - continue; - - } - - uint32_t vector_cur = 0; - - /* Load SHM pointer */ - - LoadInst *MapPtr = - IRB.CreateLoad(PointerType::get(Int8Ty, 0), AFLMapPtr); - ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(MapPtr); - - /* - std::string errMsg; - raw_string_ostream os(errMsg); - result->print(os); - fprintf(stderr, "X: %s\n", os.str().c_str()); - */ - - while (1) { - - /* Get CurLoc */ - LoadInst *CurLoc = nullptr; - Value * MapPtrIdx = nullptr; - - /* Load counter for CurLoc */ - if (!vector_cnt) { - - CurLoc = IRB.CreateLoad(IRB.getInt32Ty(), result); - ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(CurLoc); - MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, CurLoc); - - } else { - - auto element = IRB.CreateExtractElement(result, vector_cur++); - auto elementptr = IRB.CreateIntToPtr(element, Int32PtrTy); - auto elementld = IRB.CreateLoad(IRB.getInt32Ty(), elementptr); - ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(elementld); - MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, elementld); - - } - - if (use_threadsafe_counters) { - - IRB.CreateAtomicRMW(llvm::AtomicRMWInst::BinOp::Add, MapPtrIdx, One, -#if LLVM_VERSION_MAJOR >= 13 - llvm::MaybeAlign(1), -#endif - llvm::AtomicOrdering::Monotonic); - - } else { - - LoadInst *Counter = IRB.CreateLoad(IRB.getInt8Ty(), MapPtrIdx); - ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(Counter); - - /* Update bitmap */ - - Value *Incr = IRB.CreateAdd(Counter, One); - - if (skip_nozero == NULL) { - - auto cf = IRB.CreateICmpEQ(Incr, Zero); - auto carry = IRB.CreateZExt(cf, Int8Ty); - Incr = IRB.CreateAdd(Incr, carry); - - } - - StoreInst *StoreCtx = IRB.CreateStore(Incr, MapPtrIdx); - ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(StoreCtx); - - } - - if (!vector_cnt) { - - vector_cnt = 2; - break; - - } else if (vector_cnt == vector_cur) { - - break; - - } - - } - - skip_next = 1; - instr += vector_cnt; - - } else { - - skip_next = 0; - - } - - } - - } - - if (AllBlocks.empty() && !special && !local_selects) return false; - - if (!AllBlocks.empty()) - for (size_t i = 0, N = AllBlocks.size(); i < N; i++) - InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc); - - return true; - -} - -// On every indirect call we call a run-time function -// __sanitizer_cov_indir_call* with two parameters: -// - callee address, -// - global cache array that contains CacheSize pointers (zero-initialized). -// The cache is used to speed up recording the caller-callee pairs. -// The address of the caller is passed implicitly via caller PC. -// CacheSize is encoded in the name of the run-time function. -void ModuleSanitizerCoverageAFL::InjectCoverageForIndirectCalls( - Function &F, ArrayRef IndirCalls) { - - if (IndirCalls.empty()) return; - for (auto I : IndirCalls) { - - IRBuilder<> IRB(I); - CallBase & CB = cast(*I); - Value * Callee = CB.getCalledOperand(); - if (isa(Callee)) continue; - IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy)); - - } - -} - -// For every switch statement we insert a call: -// __sanitizer_cov_trace_switch(CondValue, -// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... }) - -void ModuleSanitizerCoverageAFL::InjectTraceForSwitch( - Function &, ArrayRef SwitchTraceTargets) { - - for (auto I : SwitchTraceTargets) { - - if (SwitchInst *SI = dyn_cast(I)) { - - IRBuilder<> IRB(I); - SmallVector Initializers; - Value * Cond = SI->getCondition(); - if (Cond->getType()->getScalarSizeInBits() > - Int64Ty->getScalarSizeInBits()) - continue; - Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases())); - Initializers.push_back( - ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits())); - if (Cond->getType()->getScalarSizeInBits() < - Int64Ty->getScalarSizeInBits()) - Cond = IRB.CreateIntCast(Cond, Int64Ty, false); - for (auto It : SI->cases()) { - - Constant *C = It.getCaseValue(); - if (C->getType()->getScalarSizeInBits() < - Int64Ty->getScalarSizeInBits()) - C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty); - Initializers.push_back(C); - - } - - llvm::sort(drop_begin(Initializers, 2), - [](const Constant *A, const Constant *B) { - - return cast(A)->getLimitedValue() < - cast(B)->getLimitedValue(); - - }); - - ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size()); - GlobalVariable *GV = new GlobalVariable( - *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage, - ConstantArray::get(ArrayOfInt64Ty, Initializers), - "__sancov_gen_cov_switch_values"); - IRB.CreateCall(SanCovTraceSwitchFunction, - {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)}); - - } - - } - -} - -void ModuleSanitizerCoverageAFL::InjectTraceForDiv( - Function &, ArrayRef DivTraceTargets) { - - for (auto BO : DivTraceTargets) { - - IRBuilder<> IRB(BO); - Value * A1 = BO->getOperand(1); - if (isa(A1)) continue; - if (!A1->getType()->isIntegerTy()) continue; - uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType()); - int CallbackIdx = TypeSize == 32 ? 0 : TypeSize == 64 ? 1 : -1; - if (CallbackIdx < 0) continue; - auto Ty = Type::getIntNTy(*C, TypeSize); - IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx], - {IRB.CreateIntCast(A1, Ty, true)}); - - } - -} - -void ModuleSanitizerCoverageAFL::InjectTraceForGep( - Function &, ArrayRef GepTraceTargets) { - - for (auto GEP : GepTraceTargets) { - - IRBuilder<> IRB(GEP); - for (Use &Idx : GEP->indices()) - if (!isa(Idx) && Idx->getType()->isIntegerTy()) - IRB.CreateCall(SanCovTraceGepFunction, - {IRB.CreateIntCast(Idx, IntptrTy, true)}); - - } - -} - -void ModuleSanitizerCoverageAFL::InjectTraceForCmp( - Function &, ArrayRef CmpTraceTargets) { - - for (auto I : CmpTraceTargets) { - - if (ICmpInst *ICMP = dyn_cast(I)) { - - IRBuilder<> IRB(ICMP); - Value * A0 = ICMP->getOperand(0); - Value * A1 = ICMP->getOperand(1); - if (!A0->getType()->isIntegerTy()) continue; - uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType()); - int CallbackIdx = TypeSize == 8 ? 0 - : TypeSize == 16 ? 1 - : TypeSize == 32 ? 2 - : TypeSize == 64 ? 3 - : -1; - if (CallbackIdx < 0) continue; - // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1); - auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx]; - bool FirstIsConst = isa(A0); - bool SecondIsConst = isa(A1); - // If both are const, then we don't need such a comparison. - if (FirstIsConst && SecondIsConst) continue; - // If only one is const, then make it the first callback argument. - if (FirstIsConst || SecondIsConst) { - - CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx]; - if (SecondIsConst) std::swap(A0, A1); - - } - - auto Ty = Type::getIntNTy(*C, TypeSize); - IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true), - IRB.CreateIntCast(A1, Ty, true)}); - - } - - } - -} - -void ModuleSanitizerCoverageAFL::InjectCoverageAtBlock(Function & F, - BasicBlock &BB, - size_t Idx, - bool IsLeafFunc) { - - BasicBlock::iterator IP = BB.getFirstInsertionPt(); - bool IsEntryBB = &BB == &F.getEntryBlock(); - - if (IsEntryBB) { - - // Keep allocas and llvm.localescape calls in the entry block. Even - // if we aren't splitting the block, it's nice for allocas to be before - // calls. - IP = PrepareToSplitEntryBlock(BB, IP); - - } - - IRBuilder<> IRB(&*IP); - - if (Options.TracePC) { - - IRB.CreateCall(SanCovTracePC); - // ->setCannotMerge(); // gets the PC using GET_CALLER_PC. - - } - - if (Options.TracePCGuard) { - - /* Get CurLoc */ - - Value *GuardPtr = IRB.CreateIntToPtr( - IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), - ConstantInt::get(IntptrTy, Idx * 4)), - Int32PtrTy); - - LoadInst *CurLoc = IRB.CreateLoad(IRB.getInt32Ty(), GuardPtr); - ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(CurLoc); - - /* Load SHM pointer */ - - LoadInst *MapPtr = IRB.CreateLoad(PointerType::get(Int8Ty, 0), AFLMapPtr); - ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(MapPtr); - - /* Load counter for CurLoc */ - - Value *MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, CurLoc); - - if (use_threadsafe_counters) { - - IRB.CreateAtomicRMW(llvm::AtomicRMWInst::BinOp::Add, MapPtrIdx, One, -#if LLVM_VERSION_MAJOR >= 13 - llvm::MaybeAlign(1), -#endif - llvm::AtomicOrdering::Monotonic); - - } else { - - LoadInst *Counter = IRB.CreateLoad(IRB.getInt8Ty(), MapPtrIdx); - ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(Counter); - - /* Update bitmap */ - - Value *Incr = IRB.CreateAdd(Counter, One); - - if (skip_nozero == NULL) { - - auto cf = IRB.CreateICmpEQ(Incr, Zero); - auto carry = IRB.CreateZExt(cf, Int8Ty); - Incr = IRB.CreateAdd(Incr, carry); - - } - - StoreInst *StoreCtx = IRB.CreateStore(Incr, MapPtrIdx); - ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(StoreCtx); - - } - - // done :) - - // IRB.CreateCall(SanCovTracePCGuard, Offset)->setCannotMerge(); - // IRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge(); - ++instr; - - } - - if (Options.Inline8bitCounters) { - - auto CounterPtr = IRB.CreateGEP( - Function8bitCounterArray->getValueType(), Function8bitCounterArray, - {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)}); - auto Load = IRB.CreateLoad(Int8Ty, CounterPtr); - auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1)); - auto Store = IRB.CreateStore(Inc, CounterPtr); - SetNoSanitizeMetadata(Load); - SetNoSanitizeMetadata(Store); - - } - - /* - if (Options.InlineBoolFlag) { - - auto FlagPtr = IRB.CreateGEP( - FunctionBoolArray->getValueType(), FunctionBoolArray, - {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)}); - auto Load = IRB.CreateLoad(Int1Ty, FlagPtr); - auto ThenTerm = - SplitBlockAndInsertIfThen(IRB.CreateIsNull(Load), &*IP, false); - IRBuilder<> ThenIRB(ThenTerm); - auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr); - SetNoSanitizeMetadata(Load); - SetNoSanitizeMetadata(Store); - - } - - */ - - if (Options.StackDepth && IsEntryBB && !IsLeafFunc) { - - // Check stack depth. If it's the deepest so far, record it. - Module * M = F.getParent(); - Function *GetFrameAddr = Intrinsic::getDeclaration( - M, Intrinsic::frameaddress, - IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace())); - auto FrameAddrPtr = - IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)}); - auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy); - auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack); - auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack); - auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false); - IRBuilder<> ThenIRB(ThenTerm); - auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack); - SetNoSanitizeMetadata(LowestStack); - SetNoSanitizeMetadata(Store); - - } - -} - -std::string ModuleSanitizerCoverageAFL::getSectionName( - const std::string &Section) const { - - if (TargetTriple.isOSBinFormatCOFF()) { - - if (Section == SanCovCountersSectionName) return ".SCOV$CM"; - if (Section == SanCovBoolFlagSectionName) return ".SCOV$BM"; - if (Section == SanCovPCsSectionName) return ".SCOVP$M"; - return ".SCOV$GM"; // For SanCovGuardsSectionName. - - } - - if (TargetTriple.isOSBinFormatMachO()) return "__DATA,__" + Section; - return "__" + Section; - -} - -std::string ModuleSanitizerCoverageAFL::getSectionStart( - const std::string &Section) const { - - if (TargetTriple.isOSBinFormatMachO()) - return "\1section$start$__DATA$__" + Section; - return "__start___" + Section; - -} - -std::string ModuleSanitizerCoverageAFL::getSectionEnd( - const std::string &Section) const { - - if (TargetTriple.isOSBinFormatMachO()) - return "\1section$end$__DATA$__" + Section; - return "__stop___" + Section; - -} - -#if 0 - -char ModuleSanitizerCoverageLegacyPass::ID = 0; -INITIALIZE_PASS_BEGIN(ModuleSanitizerCoverageLegacyPass, "sancov", - "Pass for instrumenting coverage on functions", false, - false) -INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) -INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) -INITIALIZE_PASS_END(ModuleSanitizerCoverageLegacyPass, "sancov", - "Pass for instrumenting coverage on functions", false, - false) -ModulePass *llvm::createModuleSanitizerCoverageLegacyPassPass( - const SanitizerCoverageOptions &Options, - const std::vector &AllowlistFiles, - const std::vector &BlocklistFiles) { - - return new ModuleSanitizerCoverageLegacyPass(Options, AllowlistFiles, - BlocklistFiles); - -} - -#endif - diff --git a/instrumentation/SanitizerCoveragePCGUARD.so.cc b/instrumentation/SanitizerCoveragePCGUARD.so.cc index f87bc068..b837a033 100644 --- a/instrumentation/SanitizerCoveragePCGUARD.so.cc +++ b/instrumentation/SanitizerCoveragePCGUARD.so.cc @@ -42,6 +42,9 @@ #include "llvm/Transforms/Instrumentation.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Transforms/Utils/ModuleUtils.h" +#include "llvm/Passes/PassPlugin.h" +#include "llvm/Passes/PassBuilder.h" +#include "llvm/IR/PassManager.h" #include "config.h" #include "debug.h" @@ -121,21 +124,18 @@ using DomTreeCallback = function_ref; using PostDomTreeCallback = function_ref; -class ModuleSanitizerCoverage { +class ModuleSanitizerCoverageAFL + : public PassInfoMixin { public: - ModuleSanitizerCoverage( - const SanitizerCoverageOptions &Options = SanitizerCoverageOptions() -#if (LLVM_VERSION_MAJOR >= 11) - , - const SpecialCaseList *Allowlist = nullptr, - const SpecialCaseList *Blocklist = nullptr -#endif - ) + ModuleSanitizerCoverageAFL( + const SanitizerCoverageOptions &Options = SanitizerCoverageOptions()) : Options(OverrideFromCL(Options)) { } + PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM); + bool instrumentModule(Module &M, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback); @@ -213,15 +213,7 @@ class ModuleSanitizerCoverageLegacyPass : public ModulePass { public: ModuleSanitizerCoverageLegacyPass( - const SanitizerCoverageOptions &Options = SanitizerCoverageOptions() -#if LLVM_VERSION_MAJOR >= 11 - , - const std::vector &AllowlistFiles = - std::vector(), - const std::vector &BlocklistFiles = - std::vector() -#endif - ) + const SanitizerCoverageOptions &Options = SanitizerCoverageOptions()) : ModulePass(ID), Options(Options) { initializeModuleSanitizerCoverageLegacyPassPass( @@ -231,12 +223,7 @@ class ModuleSanitizerCoverageLegacyPass : public ModulePass { bool runOnModule(Module &M) override { - ModuleSanitizerCoverage ModuleSancov(Options -#if (LLVM_VERSION_MAJOR >= 11) - , - Allowlist.get(), Blocklist.get() -#endif - ); + ModuleSanitizerCoverageAFL ModuleSancov(Options); auto DTCallback = [this](Function &F) -> const DominatorTree * { return &this->getAnalysis(F).getDomTree(); @@ -271,24 +258,39 @@ class ModuleSanitizerCoverageLegacyPass : public ModulePass { private: SanitizerCoverageOptions Options; - std::unique_ptr Allowlist; - std::unique_ptr Blocklist; - }; } // namespace -PreservedAnalyses ModuleSanitizerCoveragePass::run(Module & M, - ModuleAnalysisManager &MAM) { +#if 1 - fprintf(stderr, "ModuleSanitizerCoveragePass::run is called!\n"); +extern "C" ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK +llvmGetPassPluginInfo() { + + return {LLVM_PLUGIN_API_VERSION, "SanitizerCoveragePCGUARD", "v0.1", + /* lambda to insert our pass into the pass pipeline. */ + [](PassBuilder &PB) { + + #if LLVM_VERSION_MAJOR <= 13 + using OptimizationLevel = typename PassBuilder::OptimizationLevel; + #endif + PB.registerOptimizerLastEPCallback( + [](ModulePassManager &MPM, OptimizationLevel OL) { + + MPM.addPass(ModuleSanitizerCoverageAFL()); + + }); + + }}; + +} - ModuleSanitizerCoverage ModuleSancov(Options -#if (LLVM_VERSION_MAJOR >= 11) - , - Allowlist.get(), Blocklist.get() #endif - ); + +PreservedAnalyses ModuleSanitizerCoverageAFL::run(Module & M, + ModuleAnalysisManager &MAM) { + + ModuleSanitizerCoverageAFL ModuleSancov(Options); auto &FAM = MAM.getResult(M).getManager(); auto DTCallback = [&FAM](Function &F) -> const DominatorTree * { @@ -308,7 +310,7 @@ PreservedAnalyses ModuleSanitizerCoveragePass::run(Module & M, } -std::pair ModuleSanitizerCoverage::CreateSecStartEnd( +std::pair ModuleSanitizerCoverageAFL::CreateSecStartEnd( Module &M, const char *Section, Type *Ty) { GlobalVariable *SecStart = new GlobalVariable( @@ -332,7 +334,7 @@ std::pair ModuleSanitizerCoverage::CreateSecStartEnd( } -Function *ModuleSanitizerCoverage::CreateInitCallsForSections( +Function *ModuleSanitizerCoverageAFL::CreateInitCallsForSections( Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty, const char *Section) { @@ -373,7 +375,7 @@ Function *ModuleSanitizerCoverage::CreateInitCallsForSections( } -bool ModuleSanitizerCoverage::instrumentModule( +bool ModuleSanitizerCoverageAFL::instrumentModule( Module &M, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) { setvbuf(stdout, NULL, _IONBF, 0); @@ -656,7 +658,7 @@ bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT, } -void ModuleSanitizerCoverage::instrumentFunction( +void ModuleSanitizerCoverageAFL::instrumentFunction( Function &F, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) { if (F.empty()) return; @@ -742,7 +744,7 @@ void ModuleSanitizerCoverage::instrumentFunction( } -GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection( +GlobalVariable *ModuleSanitizerCoverageAFL::CreateFunctionLocalArrayInSection( size_t NumElements, Function &F, Type *Ty, const char *Section) { ArrayType *ArrayTy = ArrayType::get(Ty, NumElements); @@ -778,7 +780,7 @@ GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection( } -GlobalVariable *ModuleSanitizerCoverage::CreatePCArray( +GlobalVariable *ModuleSanitizerCoverageAFL::CreatePCArray( Function &F, ArrayRef AllBlocks) { size_t N = AllBlocks.size(); @@ -814,7 +816,7 @@ GlobalVariable *ModuleSanitizerCoverage::CreatePCArray( } -void ModuleSanitizerCoverage::CreateFunctionLocalArrays( +void ModuleSanitizerCoverageAFL::CreateFunctionLocalArrays( Function &F, ArrayRef AllBlocks, uint32_t special) { if (Options.TracePCGuard) @@ -833,9 +835,8 @@ void ModuleSanitizerCoverage::CreateFunctionLocalArrays( } -bool ModuleSanitizerCoverage::InjectCoverage(Function & F, - ArrayRef AllBlocks, - bool IsLeafFunc) { +bool ModuleSanitizerCoverageAFL::InjectCoverage( + Function &F, ArrayRef AllBlocks, bool IsLeafFunc) { uint32_t cnt_cov = 0, cnt_sel = 0, cnt_sel_inc = 0; @@ -938,7 +939,7 @@ bool ModuleSanitizerCoverage::InjectCoverage(Function & F, Int32PtrTy); LoadInst *Idx = IRB.CreateLoad(IRB.getInt32Ty(), GuardPtr); - ModuleSanitizerCoverage::SetNoSanitizeMetadata(Idx); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(Idx); callInst->setOperand(1, Idx); @@ -1060,7 +1061,7 @@ bool ModuleSanitizerCoverage::InjectCoverage(Function & F, LoadInst *MapPtr = IRB.CreateLoad(PointerType::get(Int8Ty, 0), AFLMapPtr); - ModuleSanitizerCoverage::SetNoSanitizeMetadata(MapPtr); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(MapPtr); /* std::string errMsg; @@ -1079,7 +1080,7 @@ bool ModuleSanitizerCoverage::InjectCoverage(Function & F, if (!vector_cnt) { CurLoc = IRB.CreateLoad(IRB.getInt32Ty(), result); - ModuleSanitizerCoverage::SetNoSanitizeMetadata(CurLoc); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(CurLoc); MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, CurLoc); } else { @@ -1087,7 +1088,7 @@ bool ModuleSanitizerCoverage::InjectCoverage(Function & F, auto element = IRB.CreateExtractElement(result, vector_cur++); auto elementptr = IRB.CreateIntToPtr(element, Int32PtrTy); auto elementld = IRB.CreateLoad(IRB.getInt32Ty(), elementptr); - ModuleSanitizerCoverage::SetNoSanitizeMetadata(elementld); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(elementld); MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, elementld); } @@ -1103,7 +1104,7 @@ bool ModuleSanitizerCoverage::InjectCoverage(Function & F, } else { LoadInst *Counter = IRB.CreateLoad(IRB.getInt8Ty(), MapPtrIdx); - ModuleSanitizerCoverage::SetNoSanitizeMetadata(Counter); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(Counter); /* Update bitmap */ @@ -1118,7 +1119,7 @@ bool ModuleSanitizerCoverage::InjectCoverage(Function & F, } StoreInst *StoreCtx = IRB.CreateStore(Incr, MapPtrIdx); - ModuleSanitizerCoverage::SetNoSanitizeMetadata(StoreCtx); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(StoreCtx); } @@ -1165,7 +1166,7 @@ bool ModuleSanitizerCoverage::InjectCoverage(Function & F, // The cache is used to speed up recording the caller-callee pairs. // The address of the caller is passed implicitly via caller PC. // CacheSize is encoded in the name of the run-time function. -void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls( +void ModuleSanitizerCoverageAFL::InjectCoverageForIndirectCalls( Function &F, ArrayRef IndirCalls) { if (IndirCalls.empty()) return; @@ -1185,7 +1186,7 @@ void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls( // __sanitizer_cov_trace_switch(CondValue, // {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... }) -void ModuleSanitizerCoverage::InjectTraceForSwitch( +void ModuleSanitizerCoverageAFL::InjectTraceForSwitch( Function &, ArrayRef SwitchTraceTargets) { for (auto I : SwitchTraceTargets) { @@ -1236,7 +1237,7 @@ void ModuleSanitizerCoverage::InjectTraceForSwitch( } -void ModuleSanitizerCoverage::InjectTraceForDiv( +void ModuleSanitizerCoverageAFL::InjectTraceForDiv( Function &, ArrayRef DivTraceTargets) { for (auto BO : DivTraceTargets) { @@ -1256,7 +1257,7 @@ void ModuleSanitizerCoverage::InjectTraceForDiv( } -void ModuleSanitizerCoverage::InjectTraceForGep( +void ModuleSanitizerCoverageAFL::InjectTraceForGep( Function &, ArrayRef GepTraceTargets) { for (auto GEP : GepTraceTargets) { @@ -1271,7 +1272,7 @@ void ModuleSanitizerCoverage::InjectTraceForGep( } -void ModuleSanitizerCoverage::InjectTraceForCmp( +void ModuleSanitizerCoverageAFL::InjectTraceForCmp( Function &, ArrayRef CmpTraceTargets) { for (auto I : CmpTraceTargets) { @@ -1313,9 +1314,10 @@ void ModuleSanitizerCoverage::InjectTraceForCmp( } -void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB, - size_t Idx, - bool IsLeafFunc) { +void ModuleSanitizerCoverageAFL::InjectCoverageAtBlock(Function & F, + BasicBlock &BB, + size_t Idx, + bool IsLeafFunc) { BasicBlock::iterator IP = BB.getFirstInsertionPt(); bool IsEntryBB = &BB == &F.getEntryBlock(); @@ -1348,12 +1350,12 @@ void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB, Int32PtrTy); LoadInst *CurLoc = IRB.CreateLoad(IRB.getInt32Ty(), GuardPtr); - ModuleSanitizerCoverage::SetNoSanitizeMetadata(CurLoc); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(CurLoc); /* Load SHM pointer */ LoadInst *MapPtr = IRB.CreateLoad(PointerType::get(Int8Ty, 0), AFLMapPtr); - ModuleSanitizerCoverage::SetNoSanitizeMetadata(MapPtr); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(MapPtr); /* Load counter for CurLoc */ @@ -1370,7 +1372,7 @@ void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB, } else { LoadInst *Counter = IRB.CreateLoad(IRB.getInt8Ty(), MapPtrIdx); - ModuleSanitizerCoverage::SetNoSanitizeMetadata(Counter); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(Counter); /* Update bitmap */ @@ -1385,7 +1387,7 @@ void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB, } StoreInst *StoreCtx = IRB.CreateStore(Incr, MapPtrIdx); - ModuleSanitizerCoverage::SetNoSanitizeMetadata(StoreCtx); + ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(StoreCtx); } @@ -1450,7 +1452,7 @@ void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB, } -std::string ModuleSanitizerCoverage::getSectionName( +std::string ModuleSanitizerCoverageAFL::getSectionName( const std::string &Section) const { if (TargetTriple.isOSBinFormatCOFF()) { @@ -1467,7 +1469,7 @@ std::string ModuleSanitizerCoverage::getSectionName( } -std::string ModuleSanitizerCoverage::getSectionStart( +std::string ModuleSanitizerCoverageAFL::getSectionStart( const std::string &Section) const { if (TargetTriple.isOSBinFormatMachO()) @@ -1476,7 +1478,7 @@ std::string ModuleSanitizerCoverage::getSectionStart( } -std::string ModuleSanitizerCoverage::getSectionEnd( +std::string ModuleSanitizerCoverageAFL::getSectionEnd( const std::string &Section) const { if (TargetTriple.isOSBinFormatMachO()) @@ -1485,13 +1487,15 @@ std::string ModuleSanitizerCoverage::getSectionEnd( } +#if 0 + char ModuleSanitizerCoverageLegacyPass::ID = 0; -INITIALIZE_PASS_BEGIN(ModuleSanitizerCoverageLegacyPass, "sancovAFL", +INITIALIZE_PASS_BEGIN(ModuleSanitizerCoverageLegacyPass, "sancov", "Pass for instrumenting coverage on functions", false, false) INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) -INITIALIZE_PASS_END(ModuleSanitizerCoverageLegacyPass, "sancovAFL", +INITIALIZE_PASS_END(ModuleSanitizerCoverageLegacyPass, "sancov", "Pass for instrumenting coverage on functions", false, false) ModulePass *llvm::createModuleSanitizerCoverageLegacyPassPass( @@ -1504,3 +1508,5 @@ ModulePass *llvm::createModuleSanitizerCoverageLegacyPassPass( } +#endif + diff --git a/src/afl-cc.c b/src/afl-cc.c index fae572f6..a7248325 100644 --- a/src/afl-cc.c +++ b/src/afl-cc.c @@ -624,11 +624,17 @@ static void edit_params(u32 argc, char **argv, char **envp) { } else { + #if LLVM_MAJOR >= 11 /* use new pass manager */ + cc_params[cc_par_cnt++] = "-fexperimental-new-pass-manager"; + cc_params[cc_par_cnt++] = alloc_printf( + "-fpass-plugin=%s/SanitizerCoveragePCGUARD.so", obj_path); + #else cc_params[cc_par_cnt++] = "-Xclang"; cc_params[cc_par_cnt++] = "-load"; cc_params[cc_par_cnt++] = "-Xclang"; cc_params[cc_par_cnt++] = alloc_printf("%s/SanitizerCoveragePCGUARD.so", obj_path); + #endif } From e4f201707fdfbf9a36b6a48c16f75b0fef2c9e75 Mon Sep 17 00:00:00 2001 From: vanhauser-thc Date: Thu, 17 Mar 2022 14:35:15 +0100 Subject: [PATCH 10/11] make LTO pass work too plus some fixes --- GNUmakefile | 2 +- GNUmakefile.gcc_plugin | 4 ++-- GNUmakefile.llvm | 14 +++++++------- instrumentation/SanitizerCoveragePCGUARD.so.cc | 2 +- src/afl-cc.c | 3 +++ src/afl-ld-lto.c | 4 ++-- 6 files changed, 16 insertions(+), 13 deletions(-) diff --git a/GNUmakefile b/GNUmakefile index 6392fceb..48dc6ddf 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -570,7 +570,7 @@ all_done: test_build .PHONY: clean clean: - rm -rf $(PROGS) afl-fuzz-document afl-as as afl-g++ afl-clang afl-clang++ *.o src/*.o *~ a.out core core.[1-9][0-9]* *.stackdump .test .test1 .test2 test-instr .test-instr0 .test-instr1 afl-cs-proxy afl-qemu-trace afl-gcc-fast afl-g++-fast ld *.so *.8 test/unittests/*.o test/unittests/unit_maybe_alloc test/unittests/preallocable .afl-* afl-gcc afl-g++ afl-clang afl-clang++ test/unittests/unit_hash test/unittests/unit_rand *.dSYM + rm -rf $(PROGS) afl-fuzz-document afl-as as afl-g++ afl-clang afl-clang++ *.o src/*.o *~ a.out core core.[1-9][0-9]* *.stackdump .test .test1 .test2 test-instr .test-instr0 .test-instr1 afl-cs-proxy afl-qemu-trace afl-gcc-fast afl-g++-fast ld *.so *.8 test/unittests/*.o test/unittests/unit_maybe_alloc test/unittests/preallocable .afl-* afl-gcc afl-g++ afl-clang afl-clang++ test/unittests/unit_hash test/unittests/unit_rand *.dSYM lib*.a -$(MAKE) -f GNUmakefile.llvm clean -$(MAKE) -f GNUmakefile.gcc_plugin clean -$(MAKE) -C utils/libdislocator clean diff --git a/GNUmakefile.gcc_plugin b/GNUmakefile.gcc_plugin index 63b22017..e21203ae 100644 --- a/GNUmakefile.gcc_plugin +++ b/GNUmakefile.gcc_plugin @@ -135,11 +135,11 @@ afl-common.o: ./src/afl-common.c ./afl-compiler-rt-32.o: instrumentation/afl-compiler-rt.o.c @printf "[*] Building 32-bit variant of the runtime (-m32)... " - @$(CC) $(CFLAGS_SAFE) $(CPPFLAGS) -O3 -Wno-unused-result -m32 -fPIC -c $< -o $@ 2>/dev/null; if [ "$$?" = "0" ]; then echo "success!"; ln -sf afl-compiler-rt-32.o afl-llvm-rt-32.o; else echo "failed (that's fine)"; fi + @$(CC) $(CFLAGS_SAFE) $(CPPFLAGS) -O3 -Wno-unused-result -m32 -fPIC -c $< -o $@ 2>/dev/null; if [ "$$?" = "0" ]; then echo "success!"; else echo "failed (that's fine)"; fi ./afl-compiler-rt-64.o: instrumentation/afl-compiler-rt.o.c @printf "[*] Building 64-bit variant of the runtime (-m64)... " - @$(CC) $(CFLAGS_SAFE) $(CPPFLAGS) -O3 -Wno-unused-result -m64 -fPIC -c $< -o $@ 2>/dev/null; if [ "$$?" = "0" ]; then echo "success!"; ln -sf afl-compiler-rt-64.o afl-llvm-rt-64.o; else echo "failed (that's fine)"; fi + @$(CC) $(CFLAGS_SAFE) $(CPPFLAGS) -O3 -Wno-unused-result -m64 -fPIC -c $< -o $@ 2>/dev/null; if [ "$$?" = "0" ]; then echo "success!"; else echo "failed (that's fine)"; fi ./afl-gcc-pass.so: instrumentation/afl-gcc-pass.so.cc | test_deps $(CXX) $(CXXEFLAGS) $(PLUGIN_FLAGS) -shared $< -o $@ diff --git a/GNUmakefile.llvm b/GNUmakefile.llvm index f1de28a4..a8f019c6 100644 --- a/GNUmakefile.llvm +++ b/GNUmakefile.llvm @@ -394,7 +394,7 @@ endif ./SanitizerCoveragePCGUARD.so: instrumentation/SanitizerCoveragePCGUARD.so.cc instrumentation/afl-llvm-common.o | test_deps ifeq "$(LLVM_10_OK)" "1" - -$(CXX) $(CLANG_CPPFL) -Wdeprecated -fno-rtti -fPIC -std=$(LLVM_STDCXX) -shared $< -o $@ $(CLANG_LFL) instrumentation/afl-llvm-common.o + -$(CXX) $(CLANG_CPPFL) -fno-rtti -fPIC -std=$(LLVM_STDCXX) -shared $< -o $@ $(CLANG_LFL) -Wno-deprecated-copy-with-dtor -Wdeprecated instrumentation/afl-llvm-common.o endif ./afl-llvm-lto-instrumentlist.so: instrumentation/afl-llvm-lto-instrumentlist.so.cc instrumentation/afl-llvm-common.o @@ -447,11 +447,11 @@ document: ./afl-compiler-rt-32.o: instrumentation/afl-compiler-rt.o.c @printf "[*] Building 32-bit variant of the runtime (-m32)... " - @$(CC) $(CLANG_CFL) $(CFLAGS_SAFE) $(CPPFLAGS) -O3 -Wno-unused-result -m32 -fPIC -c $< -o $@ 2>/dev/null; if [ "$$?" = "0" ]; then echo "success!"; ln -sf afl-compiler-rt-32.o afl-llvm-rt-32.o; else echo "failed (that's fine)"; fi + @$(CC) $(CLANG_CFL) $(CFLAGS_SAFE) $(CPPFLAGS) -O3 -Wno-unused-result -m32 -fPIC -c $< -o $@ 2>/dev/null; if [ "$$?" = "0" ]; then echo "success!"; else echo "failed (that's fine)"; fi ./afl-compiler-rt-64.o: instrumentation/afl-compiler-rt.o.c @printf "[*] Building 64-bit variant of the runtime (-m64)... " - @$(CC) $(CLANG_CFL) $(CFLAGS_SAFE) $(CPPFLAGS) -O3 -Wno-unused-result -m64 -fPIC -c $< -o $@ 2>/dev/null; if [ "$$?" = "0" ]; then echo "success!"; ln -sf afl-compiler-rt-64.o afl-llvm-rt-64.o; else echo "failed (that's fine)"; fi + @$(CC) $(CLANG_CFL) $(CFLAGS_SAFE) $(CPPFLAGS) -O3 -Wno-unused-result -m64 -fPIC -c $< -o $@ 2>/dev/null; if [ "$$?" = "0" ]; then echo "success!"; else echo "failed (that's fine)"; fi .PHONY: test_build test_build: $(PROGS) @@ -474,11 +474,11 @@ install: all @install -d -m 755 $${DESTDIR}$(BIN_PATH) $${DESTDIR}$(HELPER_PATH) $${DESTDIR}$(DOC_PATH) $${DESTDIR}$(MISC_PATH) @if [ -f ./afl-cc ]; then set -e; install -m 755 ./afl-cc $${DESTDIR}$(BIN_PATH); ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-c++; fi @rm -f $${DESTDIR}$(HELPER_PATH)/afl-llvm-rt*.o $${DESTDIR}$(HELPER_PATH)/afl-gcc-rt*.o - @if [ -f ./afl-compiler-rt.o ]; then set -e; install -m 755 ./afl-compiler-rt.o $${DESTDIR}$(HELPER_PATH); ln -sf afl-compiler-rt.o $${DESTDIR}$(HELPER_PATH)/afl-llvm-rt.o ;fi + @if [ -f ./afl-compiler-rt.o ]; then set -e; install -m 755 ./afl-compiler-rt.o $${DESTDIR}$(HELPER_PATH); ln -sf afl-compiler-rt.o $${DESTDIR}$(HELPER_PATH)/afl-compiler-rt.o ;fi @if [ -f ./afl-lto ]; then set -e; ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-lto; ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-lto++; ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-clang-lto; ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-clang-lto++; install -m 755 ./afl-llvm-rt-lto*.o ./afl-llvm-lto-instrumentlist.so $${DESTDIR}$(HELPER_PATH); fi @if [ -f ./afl-ld-lto ]; then set -e; install -m 755 ./afl-ld-lto $${DESTDIR}$(BIN_PATH); fi - @if [ -f ./afl-compiler-rt-32.o ]; then set -e; install -m 755 ./afl-compiler-rt-32.o $${DESTDIR}$(HELPER_PATH); ln -sf afl-compiler-rt-32.o $${DESTDIR}$(HELPER_PATH)/afl-llvm-rt-32.o ;fi - @if [ -f ./afl-compiler-rt-64.o ]; then set -e; install -m 755 ./afl-compiler-rt-64.o $${DESTDIR}$(HELPER_PATH); ln -sf afl-compiler-rt-64.o $${DESTDIR}$(HELPER_PATH)/afl-llvm-rt-64.o ; fi + @if [ -f ./afl-compiler-rt-32.o ]; then set -e; install -m 755 ./afl-compiler-rt-32.o $${DESTDIR}$(HELPER_PATH); ln -sf afl-compiler-rt-32.o $${DESTDIR}$(HELPER_PATH)/afl-compiler-rt-32.o ;fi + @if [ -f ./afl-compiler-rt-64.o ]; then set -e; install -m 755 ./afl-compiler-rt-64.o $${DESTDIR}$(HELPER_PATH); ln -sf afl-compiler-rt-64.o $${DESTDIR}$(HELPER_PATH)/afl-compiler-rt-64.o ; fi @if [ -f ./compare-transform-pass.so ]; then set -e; install -m 755 ./*.so $${DESTDIR}$(HELPER_PATH); fi @if [ -f ./compare-transform-pass.so ]; then set -e; ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-clang-fast ; ln -sf ./afl-c++ $${DESTDIR}$(BIN_PATH)/afl-clang-fast++ ; ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-clang ; ln -sf ./afl-c++ $${DESTDIR}$(BIN_PATH)/afl-clang++ ; fi @if [ -f ./SanitizerCoverageLTO.so ]; then set -e; ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-clang-lto ; ln -sf ./afl-c++ $${DESTDIR}$(BIN_PATH)/afl-clang-lto++ ; fi @@ -520,4 +520,4 @@ endif .PHONY: clean clean: rm -f *.o *.so *~ a.out core core.[1-9][0-9]* .test2 test-instr .test-instr0 .test-instr1 *.dwo - rm -f $(PROGS) afl-common.o ./afl-c++ ./afl-lto ./afl-lto++ ./afl-clang-lto* ./afl-clang-fast* ./afl-clang*.8 ./ld ./afl-ld ./afl-llvm-rt*.o instrumentation/*.o + rm -f $(PROGS) afl-common.o ./afl-c++ ./afl-lto ./afl-lto++ ./afl-clang-lto* ./afl-clang-fast* ./afl-clang*.8 ./ld ./afl-ld ./afl-compiler-rt*.o ./afl-llvm-rt*.o instrumentation/*.o diff --git a/instrumentation/SanitizerCoveragePCGUARD.so.cc b/instrumentation/SanitizerCoveragePCGUARD.so.cc index b837a033..a5d8f895 100644 --- a/instrumentation/SanitizerCoveragePCGUARD.so.cc +++ b/instrumentation/SanitizerCoveragePCGUARD.so.cc @@ -241,7 +241,7 @@ class ModuleSanitizerCoverageLegacyPass : public ModulePass { } - static char ID; // Pass identification, replacement for typeid + /*static*/ char ID; // Pass identification, replacement for typeid StringRef getPassName() const override { return "ModuleSanitizerCoverage"; diff --git a/src/afl-cc.c b/src/afl-cc.c index a7248325..4c977303 100644 --- a/src/afl-cc.c +++ b/src/afl-cc.c @@ -599,6 +599,9 @@ static void edit_params(u32 argc, char **argv, char **envp) { free(ld_path); cc_params[cc_par_cnt++] = "-Wl,--allow-multiple-definition"; +#if defined(AFL_CLANG_LDPATH) && LLVM_MAJOR >= 15 + cc_params[cc_par_cnt++] = "-Wl,--lto-legacy-pass-manager"; +#endif cc_params[cc_par_cnt++] = alloc_printf("-Wl,-mllvm=-load=%s/SanitizerCoverageLTO.so", obj_path); cc_params[cc_par_cnt++] = lto_flag; diff --git a/src/afl-ld-lto.c b/src/afl-ld-lto.c index 9b58125f..f2f95fd7 100644 --- a/src/afl-ld-lto.c +++ b/src/afl-ld-lto.c @@ -86,7 +86,7 @@ static void edit_params(int argc, char **argv) { for (i = 1; i < (u32)argc; i++) { if (strstr(argv[i], "/afl-llvm-rt-lto.o") != NULL) rt_lto_present = 1; - if (strstr(argv[i], "/afl-llvm-rt.o") != NULL) rt_present = 1; + if (strstr(argv[i], "/afl-compiler-rt.o") != NULL) rt_present = 1; if (strstr(argv[i], "/afl-llvm-lto-instr") != NULL) inst_present = 1; } @@ -237,7 +237,7 @@ static void edit_params(int argc, char **argv) { } if (!rt_present) - ld_params[ld_param_cnt++] = alloc_printf("%s/afl-llvm-rt.o", afl_path); + ld_params[ld_param_cnt++] = alloc_printf("%s/afl-compiler-rt.o", afl_path); if (!rt_lto_present) ld_params[ld_param_cnt++] = alloc_printf("%s/afl-llvm-rt-lto.o", afl_path); From 3c11a377570512efeb3a197148ff1b7dddbd8e32 Mon Sep 17 00:00:00 2001 From: vanhauser-thc Date: Thu, 17 Mar 2022 15:48:06 +0100 Subject: [PATCH 11/11] fixes for llvm < 11 --- .../SanitizerCoveragePCGUARD.so.cc | 2 +- instrumentation/afl-llvm-dict2file.so.cc | 143 +++++++++--------- instrumentation/compare-transform-pass.so.cc | 19 ++- src/afl-ld-lto.c | 3 +- 4 files changed, 85 insertions(+), 82 deletions(-) diff --git a/instrumentation/SanitizerCoveragePCGUARD.so.cc b/instrumentation/SanitizerCoveragePCGUARD.so.cc index a5d8f895..e234cf57 100644 --- a/instrumentation/SanitizerCoveragePCGUARD.so.cc +++ b/instrumentation/SanitizerCoveragePCGUARD.so.cc @@ -242,7 +242,7 @@ class ModuleSanitizerCoverageLegacyPass : public ModulePass { } /*static*/ char ID; // Pass identification, replacement for typeid - StringRef getPassName() const override { + StringRef getPassName() const override { return "ModuleSanitizerCoverage"; diff --git a/instrumentation/afl-llvm-dict2file.so.cc b/instrumentation/afl-llvm-dict2file.so.cc index 37cd8ad0..79cdf491 100644 --- a/instrumentation/afl-llvm-dict2file.so.cc +++ b/instrumentation/afl-llvm-dict2file.so.cc @@ -45,7 +45,6 @@ #include "llvm/IR/PassManager.h" #else #include "llvm/IR/LegacyPassManager.h" - #include "llvm/Transforms/IPO/PassManagerBuilder.h" #endif #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Module.h" @@ -67,9 +66,74 @@ #define O_DSYNC O_SYNC #endif -std::ofstream of; +using namespace llvm; -void dict2file(u8 *mem, u32 len) { +namespace { + +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ +class AFLdict2filePass : public PassInfoMixin { + + std::ofstream of; + void dict2file(u8 *, u32); + + public: + AFLdict2filePass() { + +#else + +class AFLdict2filePass : public ModulePass { + + std::ofstream of; + void dict2file(u8 *, u32); + + public: + static char ID; + + AFLdict2filePass() : ModulePass(ID) { + +#endif + + if (getenv("AFL_DEBUG")) debug = 1; + + } + +#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ + PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM); +#else + bool runOnModule(Module &M) override; +#endif + +}; + +} // namespace + +#if LLVM_MAJOR >= 11 +extern "C" ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK +llvmGetPassPluginInfo() { + + return {LLVM_PLUGIN_API_VERSION, "AFLdict2filePass", "v0.1", + /* lambda to insert our pass into the pass pipeline. */ + [](PassBuilder &PB) { + + #if LLVM_VERSION_MAJOR <= 13 + using OptimizationLevel = typename PassBuilder::OptimizationLevel; + #endif + PB.registerOptimizerLastEPCallback( + [](ModulePassManager &MPM, OptimizationLevel OL) { + + MPM.addPass(AFLdict2filePass()); + + }); + + }}; + +} + +#else +char AFLdict2filePass::ID = 0; +#endif + +void AFLdict2filePass::dict2file(u8 *mem, u32 len) { u32 i, j, binary = 0; char line[MAX_AUTO_EXTRA * 8], tmp[8]; @@ -108,70 +172,10 @@ void dict2file(u8 *mem, u32 len) { } -using namespace llvm; - -namespace { - -#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ -class AFLdict2filePass : public PassInfoMixin { - - public: - AFLdict2filePass() { - -#else -class AFLdict2filePass : public ModulePass { - - public: - bool runOnModule(Module &M) override; - AFLdict2filePass() : ModulePass(ID) { - -#endif - - if (getenv("AFL_DEBUG")) debug = 1; - - } - -#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ - PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM); -#endif - -}; - -} // namespace - -#if LLVM_MAJOR >= 11 -extern "C" ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK -llvmGetPassPluginInfo() { - - return {LLVM_PLUGIN_API_VERSION, "dict2file", "v0.1", - /* lambda to insert our pass into the pass pipeline. */ - [](PassBuilder &PB) { - - #if LLVM_VERSION_MAJOR <= 13 - using OptimizationLevel = typename PassBuilder::OptimizationLevel; - #endif - PB.registerOptimizerLastEPCallback( - [](ModulePassManager &MPM, OptimizationLevel OL) { - - MPM.addPass(AFLdict2filePass()); - - }); - - }}; - -} - -#else - -char AFLdict2filePass::ID = 0; - -#endif - #if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ PreservedAnalyses AFLdict2filePass::run(Module &M, ModuleAnalysisManager &MAM) { #else - bool AFLdict2filePass::runOnModule(Module &M) { #endif @@ -640,6 +644,7 @@ bool AFLdict2filePass::runOnModule(Module &M) { if (optLen < 2) { continue; } if (literalLength + 1 == optLen) { // add null byte + thestring.append("\0", 1); } @@ -662,17 +667,11 @@ bool AFLdict2filePass::runOnModule(Module &M) { } */ - - if (!isStdString) { + if (!isStdString && thestring.find('\0', 0) != std::string::npos) { // ensure we do not have garbage size_t offset = thestring.find('\0', 0); - if (offset && offset < optLen && offset + 1 < optLen) { - - optLen = offset + 1; - - } - + if (offset + 1 < optLen) optLen = offset + 1; thestring = thestring.substr(0, optLen); } @@ -716,8 +715,6 @@ bool AFLdict2filePass::runOnModule(Module &M) { #if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ auto PA = PreservedAnalyses::all(); -#endif -#if LLVM_VERSION_MAJOR >= 11 /* use new pass manager */ return PA; #else return true; diff --git a/instrumentation/compare-transform-pass.so.cc b/instrumentation/compare-transform-pass.so.cc index 4e471ea3..34c88735 100644 --- a/instrumentation/compare-transform-pass.so.cc +++ b/instrumentation/compare-transform-pass.so.cc @@ -88,21 +88,26 @@ class CompareTransform : public ModulePass { const char *getPassName() const override { #endif + + return "cmplog transform"; + + } + #endif #if LLVM_MAJOR >= 11 /* use new pass manager */ - PreservedAnalyses run(Module & M, ModuleAnalysisManager & MAM); + PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM); #else bool runOnModule(Module &M) override; #endif - private: - bool transformCmps(Module & M, const bool processStrcmp, - const bool processMemcmp, const bool processStrncmp, - const bool processStrcasecmp, - const bool processStrncasecmp); + private: + bool transformCmps(Module &M, const bool processStrcmp, + const bool processMemcmp, const bool processStrncmp, + const bool processStrcasecmp, + const bool processStrncasecmp); - }; +}; } // namespace diff --git a/src/afl-ld-lto.c b/src/afl-ld-lto.c index f2f95fd7..5797def8 100644 --- a/src/afl-ld-lto.c +++ b/src/afl-ld-lto.c @@ -237,7 +237,8 @@ static void edit_params(int argc, char **argv) { } if (!rt_present) - ld_params[ld_param_cnt++] = alloc_printf("%s/afl-compiler-rt.o", afl_path); + ld_params[ld_param_cnt++] = + alloc_printf("%s/afl-compiler-rt.o", afl_path); if (!rt_lto_present) ld_params[ld_param_cnt++] = alloc_printf("%s/afl-llvm-rt-lto.o", afl_path);