diff options
Diffstat (limited to 'instrumentation')
-rw-r--r-- | instrumentation/README.persistent_mode.md | 32 | ||||
-rw-r--r-- | instrumentation/SanitizerCoverageLTO.so.cc | 778 | ||||
-rw-r--r-- | instrumentation/afl-compiler-rt.o.c | 561 | ||||
-rw-r--r-- | instrumentation/afl-gcc-cmptrs-pass.so.cc | 15 |
4 files changed, 883 insertions, 503 deletions
diff --git a/instrumentation/README.persistent_mode.md b/instrumentation/README.persistent_mode.md index 14e59f4a..8e4f6ae4 100644 --- a/instrumentation/README.persistent_mode.md +++ b/instrumentation/README.persistent_mode.md @@ -195,4 +195,34 @@ Then as first line after the `__AFL_LOOP` while loop: int len = __AFL_FUZZ_TESTCASE_LEN; ``` -And that is all! \ No newline at end of file +And that is all! + +## 6) Persistent record, and replay + +If your software under test requires keeping a state between persistent loop iterations (i.e., a stateful network stack), you can use the `AFL_PERSISTENT_RECORD` variable as described in the [environment variables documentation](../docs/env_variables.md). + +When `AFL_PERSISTENT_RECORD` is enabled, replay functionality is also included in the compiler-rt library. To replay a specific record, assign the record number to the AFL_PERSISTENT_REPLAY environment variable (i.e., `RECORD:XXXXX`` -> `AFL_PERSISTENT_REPLAY=XXXXX`), and run the test binary as you would normally do. +The directory where the record files live can be specified via the `AFL_PERSISTENT_DIR` environment varilable, otherwise by default it will be considered the current directory (`./`). + +If your harness reads the input files from arguments using the special `@@` argument you will need to include support by enabling `AFL_PERSISTENT_ARGPARSE` in `config.h`. + +In order to offer transparent support to harnesses using the `@@` command line argument, arguments are parsed by the `__afl_record_replay_init` init function. Since not all systems support passing arguments to initializers, this functionality is disabled by default, it's recommendable to use the `__AFL_FUZZ_TESTCASE_BUF/__AFL_FUZZ_TESTCASE_LEN` shared memory mechanism instead. + +## 7) Drop-in persistent loop replay replacement + +To use the replay functionality without having to use `afl-cc`, include the [include/record_compat.h](../include/afl-record_compat.h) header file. Together with the [include/afl-persistent-replay.h](../include/afl-persistent-replay.h) header included in it, `afl-record-compat.h` provides a drop-in replacement for the persistent loop mechanism. + +```c +#ifndef __AFL_FUZZ_TESTCASE_LEN + // #define AFL_PERSISTENT_REPLAY_ARGPARSE + #include "afl-record-compat.h" +#endif + +__AFL_FUZZ_INIT(); +``` + +A simple example is provided in [persistent_demo_replay.c](../utils/replay_record/persistent_demo_replay.c). + +Be aware that the [afl-record-compat.h](../include/afl-record-compat.h) header should only be included in a single compilation unit, or you will end up with clobbered functions and variables. + +If you need a cleaner solution, you'll have to move the functions and variables defined in [include/record_compat.h](../include/afl-record-compat.h) and [include/afl-persistent-replay.h](../include/afl-persistent-replay.h) in a C file, and add the relevant declarations to a header file. After including the new header file, the compilation unit resulting from compiling the C file can then be linked with your program. \ No newline at end of file diff --git a/instrumentation/SanitizerCoverageLTO.so.cc b/instrumentation/SanitizerCoverageLTO.so.cc index 68423029..43c6ca40 100644 --- a/instrumentation/SanitizerCoverageLTO.so.cc +++ b/instrumentation/SanitizerCoverageLTO.so.cc @@ -192,12 +192,15 @@ class ModuleSanitizerCoverageLTO PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM); private: - void instrumentFunction(Function &F, DomTreeCallback DTCallback, - PostDomTreeCallback PDTCallback); - void InjectCoverageForIndirectCalls(Function &F, - ArrayRef<Instruction *> IndirCalls); - bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks, - bool IsLeafFunc = true); + void instrumentFunction(Function &F, DomTreeCallback DTCallback, + PostDomTreeCallback PDTCallback); + /* void InjectCoverageForIndirectCalls(Function &F, + ArrayRef<Instruction *> + IndirCalls);*/ + bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks, + bool IsLeafFunc = true); + bool Fake_InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks, + bool IsLeafFunc = true); GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements, Function &F, Type *Ty, const char *Section); @@ -247,6 +250,9 @@ class ModuleSanitizerCoverageLTO uint32_t afl_global_id = 0; uint32_t unhandled = 0; uint32_t select_cnt = 0; + uint32_t instrument_ctx = 0; + uint32_t instrument_ctx_max_depth = 0; + uint32_t extra_ctx_inst = 0; uint64_t map_addr = 0; const char *skip_nozero = NULL; const char *use_threadsafe_counters = nullptr; @@ -257,11 +263,14 @@ class ModuleSanitizerCoverageLTO IntegerType *Int32Tyi = NULL; IntegerType *Int64Tyi = NULL; ConstantInt *Zero = NULL; + ConstantInt *Zero32 = NULL; ConstantInt *One = NULL; LLVMContext *Ct = NULL; Module *Mo = NULL; + GlobalVariable *AFLContext = NULL; GlobalVariable *AFLMapPtr = NULL; Value *MapPtrFixed = NULL; + AllocaInst *CTX_add = NULL; std::ofstream dFile; size_t found = 0; // AFL++ END @@ -420,16 +429,51 @@ bool ModuleSanitizerCoverageLTO::instrumentModule( setvbuf(stdout, NULL, _IONBF, 0); if (getenv("AFL_DEBUG")) { debug = 1; } if (getenv("AFL_LLVM_DICT2FILE_NO_MAIN")) { autodictionary_no_main = 1; } + if (getenv("AFL_LLVM_CALLER") || getenv("AFL_LLVM_CTX") || + getenv("AFL_LLVM_LTO_CALLER") || getenv("AFL_LLVM_LTO_CTX")) { + + instrument_ctx = 1; + + } + + if (getenv("AFL_LLVM_LTO_CALLER_DEPTH")) { + + instrument_ctx_max_depth = atoi(getenv("AFL_LLVM_LTO_CALLER_DEPTH")); + + } else if (getenv("AFL_LLVM_LTO_CTX_DEPTH")) { + + instrument_ctx_max_depth = atoi(getenv("AFL_LLVM_LTO_CTX_DEPTH")); + + } else if (getenv("AFL_LLVM_CALLER_DEPTH")) { + + instrument_ctx_max_depth = atoi(getenv("AFL_LLVM_CALLER_DEPTH")); + + } else if (getenv("AFL_LLVM_CTX_DEPTH")) { + + instrument_ctx_max_depth = atoi(getenv("AFL_LLVM_CTX_DEPTH")); + + } if ((isatty(2) && !getenv("AFL_QUIET")) || debug) { + char buf[64] = {}; + if (instrument_ctx) { + + snprintf(buf, sizeof(buf), " (CTX mode, depth %u)\n", + instrument_ctx_max_depth); + + } + SAYF(cCYA "afl-llvm-lto" VERSION cRST - " by Marc \"vanHauser\" Heuse <mh@mh-sec.de>\n"); + "%s by Marc \"vanHauser\" Heuse <mh@mh-sec.de>\n", + buf); - } else + } else { be_quiet = 1; + } + skip_nozero = getenv("AFL_LLVM_SKIP_NEVERZERO"); use_threadsafe_counters = getenv("AFL_LLVM_THREADSAFE_INST"); @@ -500,7 +544,12 @@ bool ModuleSanitizerCoverageLTO::instrumentModule( } + AFLContext = new GlobalVariable( + M, Int32Ty, false, GlobalValue::ExternalLinkage, 0, "__afl_prev_ctx", 0, + GlobalVariable::GeneralDynamicTLSModel, 0, false); + Zero = ConstantInt::get(Int8Tyi, 0); + Zero32 = ConstantInt::get(Int32Tyi, 0); One = ConstantInt::get(Int8Tyi, 1); initInstrumentList(); @@ -597,12 +646,12 @@ bool ModuleSanitizerCoverageLTO::instrumentModule( } dictionary.push_back(std::string((char *)&val, len)); - found++; + ++found; if (val2) { dictionary.push_back(std::string((char *)&val2, len)); - found++; + ++found; } @@ -750,12 +799,12 @@ bool ModuleSanitizerCoverageLTO::instrumentModule( else Str2 = TmpStr.str(); - if (debug) + /*if (debug) fprintf(stderr, "F:%s %p(%s)->\"%s\"(%s) %p(%s)->\"%s\"(%s)\n", FuncName.c_str(), Str1P, Str1P->getName().str().c_str(), Str1.c_str(), HasStr1 == true ? "true" : "false", Str2P, Str2P->getName().str().c_str(), Str2.c_str(), - HasStr2 == true ? "true" : "false"); + HasStr2 == true ? "true" : "false");*/ // we handle the 2nd parameter first because of llvm memcpy if (!HasStr2) { @@ -929,7 +978,7 @@ bool ModuleSanitizerCoverageLTO::instrumentModule( '\0') { thestring.append("\0", 1); // add null byte - optLen++; + ++optLen; } @@ -1080,7 +1129,7 @@ bool ModuleSanitizerCoverageLTO::instrumentModule( for (auto token : dictionary) { memlen += token.length(); - count++; + ++count; } @@ -1101,7 +1150,7 @@ bool ModuleSanitizerCoverageLTO::instrumentModule( ptrhld.get()[offset++] = (uint8_t)token.length(); memcpy(ptrhld.get() + offset, token.c_str(), token.length()); offset += token.length(); - count++; + ++count; } @@ -1148,7 +1197,7 @@ bool ModuleSanitizerCoverageLTO::instrumentModule( WARNF("No instrumentation targets found."); else { - char modeline[100]; + char modeline[128]; snprintf(modeline, sizeof(modeline), "%s%s%s%s%s%s", getenv("AFL_HARDEN") ? "hardened" : "non-hardened", getenv("AFL_USE_ASAN") ? ", ASAN" : "", @@ -1156,9 +1205,16 @@ bool ModuleSanitizerCoverageLTO::instrumentModule( getenv("AFL_USE_TSAN") ? ", TSAN" : "", getenv("AFL_USE_CFISAN") ? ", CFISAN" : "", getenv("AFL_USE_UBSAN") ? ", UBSAN" : ""); - OKF("Instrumented %u locations (%u selects) without collisions (%llu " - "collisions have been avoided) (%s mode).", - inst, select_cnt, calculateCollisions(inst), modeline); + char buf[64] = {}; + if (instrument_ctx) { + + snprintf(buf, sizeof(buf), " with %u extra map entries for CTX", + extra_ctx_inst); + + } + + OKF("Instrumented %u locations (%u selects)%s (%s mode).", inst, + select_cnt, buf, modeline); } @@ -1239,6 +1295,52 @@ static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB, } +/// return the number of calls to this function +u32 countCallers(Function *F) { + + u32 callers = 0; + + if (!F) { return 0; } + + for (auto *U : F->users()) { + + if (auto *CI = dyn_cast<CallInst>(U)) { ++callers; } + + } + + return callers; + +} + +/// return the calling function of a function - only if there is a single caller +Function *returnOnlyCaller(Function *F) { + + Function *caller = NULL; + + if (!F) { return NULL; } + + for (auto *U : F->users()) { + + if (auto *CI = dyn_cast<CallInst>(U)) { + + if (caller == NULL) { + + caller = CI->getParent()->getParent(); + + } else { + + return NULL; + + } + + } + + } + + return caller; + +} + void ModuleSanitizerCoverageLTO::instrumentFunction( Function &F, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) { @@ -1272,6 +1374,37 @@ void ModuleSanitizerCoverageLTO::instrumentFunction( // AFL++ START if (!F.size()) return; + + LLVMContext &Context = F.getContext(); + MDNode *N = MDNode::get(Context, MDString::get(Context, "nosanitize")); + + if (instrument_ctx) { + + // we have to set __afl_ctx 0 for all indirect calls in all functions, even + // those not to be instrumented. + for (auto &BB : F) { + + for (auto &IN : BB) { + + if (auto *Call = dyn_cast<CallInst>(&IN)) { + + if (Call->isIndirectCall()) { + + IRBuilder<> Builder(IN.getContext()); + Builder.SetInsertPoint(IN.getParent(), IN.getIterator()); + StoreInst *StoreCtx = Builder.CreateStore(Zero32, AFLContext); + StoreCtx->setMetadata("nosanitize", N); + + } + + } + + } + + } + + } + if (!isInInstrumentList(&F, FMNAME)) return; // AFL++ END @@ -1285,11 +1418,297 @@ void ModuleSanitizerCoverageLTO::instrumentFunction( const PostDominatorTree *PDT = PDTCallback(F); bool IsLeafFunc = true; uint32_t skip_next = 0; + uint32_t call_counter = 0, call_depth = 0; + uint32_t inst_save = inst, save_global = afl_global_id; + uint32_t inst_in_this_func = 0; + Function *caller = NULL; + LoadInst *PrevCtxLoad = NULL; + + CTX_add = NULL; + + if (debug) fprintf(stderr, "Function: %s\n", F.getName().str().c_str()); + + if (instrument_ctx) { + + caller = &F; + call_counter = countCallers(caller); + Function *callee = caller; + + if (call_counter == 1 && instrument_ctx_max_depth) { + + ++call_depth; + + while (instrument_ctx_max_depth >= call_depth && + ((caller = returnOnlyCaller(callee)) || 1 == 1) && + (call_counter = countCallers(callee)) == 1) { + + if (debug && caller && callee) + fprintf(stderr, "DEBUG: another depth: %s <- %s [%u]\n", + callee->getName().str().c_str(), + caller->getName().str().c_str(), call_depth); + ++call_depth; + callee = caller; + + } + + if (!caller && callee) { + + caller = callee; + if (debug) + fprintf(stderr, "DEBUG: depth found: %s <- %s [count=%u, depth=%u]\n", + caller->getName().str().c_str(), F.getName().str().c_str(), + call_counter, call_depth); + + } + + } + + if (debug && call_counter < 2) { + + fprintf(stderr, "Function %s only %u (%s)\n", F.getName().str().c_str(), + call_counter, caller->getName().str().c_str()); + + } + + if (call_counter == 1) { + + call_counter = 0; + caller = NULL; + + } + + if (debug) { + + fprintf(stderr, "DEBUG: result: Function=%s callers=%u depth=%u\n", + F.getName().str().c_str(), call_counter, call_depth); + + } + + if (call_counter > 1) { + + // Fake instrumentation so we can count how many instrumentations there + // will be in this function + for (auto &BB : F) { + + for (auto &IN : BB) { + + CallInst *callInst = nullptr; + + if ((callInst = dyn_cast<CallInst>(&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; + + ++inst; + + } + + SelectInst *selectInst = nullptr; + + if ((selectInst = dyn_cast<SelectInst>(&IN))) { + + Value *condition = selectInst->getCondition(); + auto t = condition->getType(); + + if (t->getTypeID() == llvm::Type::IntegerTyID) { + + inst += 2; + + } else + +#if LLVM_VERSION_MAJOR >= 14 + if (t->getTypeID() == llvm::Type::FixedVectorTyID) { + + FixedVectorType *tt = dyn_cast<FixedVectorType>(t); + if (tt) { + + uint32_t elements = tt->getElementCount().getFixedValue(); + inst += elements * 2; + + } + + } else + +#endif + { + + continue; + + } + + } + + } + + if (shouldInstrumentBlock(F, &BB, DT, PDT, Options)) + BlocksToInstrument.push_back(&BB); + + } + + Fake_InjectCoverage(F, BlocksToInstrument, IsLeafFunc); + + if (debug) + fprintf(stderr, "DEBUG: CTX: %u instrumentations\n", inst - inst_save); + + // we only instrument functions that have more than one instrumented block + if (inst > inst_save + 1) { + + inst_in_this_func = inst - inst_save; + bool done = false; + + // in rare occasions there can be multiple entry points per function + for (auto &BB : F) { + + if (&BB == &F.getEntryBlock() && done == false) { + + // we insert a CTX value in all our callers: + IRBuilder<> Builder(Context); + CallInst *CI = NULL; + Function *F2 = NULL; + uint32_t instrumented_calls = 0; + + for (auto *U : caller->users()) { + + if ((CI = dyn_cast<CallInst>(U))) { + + F2 = CI->getParent()->getParent(); + if (debug) + fprintf(stderr, + "DEBUG: CTX call insert %s [%u/%u] -> %s/%s\n", + F2->getName().str().c_str(), instrumented_calls + 1, + call_counter, caller->getName().str().c_str(), + F.getName().str().c_str()); + + Builder.SetInsertPoint(CI); + StoreInst *StoreCtx = Builder.CreateStore( + ConstantInt::get(Type::getInt32Ty(Context), + instrumented_calls++), + AFLContext); + StoreCtx->setMetadata("nosanitize", N); + + } + + } + + if (instrumented_calls != call_counter) { + + fprintf(stderr, "BUG! %s/%s <=> %u vs %u\n", + caller->getName().str().c_str(), + F.getName().str().c_str(), instrumented_calls, + call_counter); + exit(-1); + + } + + done = true; + + } + + // in all entrypoints we have to load the CTX value + if (&BB == &F.getEntryBlock()) { + + Value *CTX_offset; + BasicBlock::iterator IP = BB.getFirstInsertionPt(); + IRBuilder<> IRB(&(*IP)); + + PrevCtxLoad = IRB.CreateLoad( +#if LLVM_VERSION_MAJOR >= 14 + IRB.getInt32Ty(), +#endif + AFLContext); + PrevCtxLoad->setMetadata("nosanitize", N); + + CTX_offset = IRB.CreateMul( + ConstantInt::get(Type::getInt32Ty(Context), inst_in_this_func), + PrevCtxLoad, "CTXmul", false, true); + + CTX_add = + IRB.CreateAlloca(Type::getInt32Ty(Context), nullptr, "CTX_add"); + auto nosan = IRB.CreateStore(CTX_offset, CTX_add); + nosan->setMetadata("nosanitize", N); + + if (debug) + fprintf( + stderr, "DEBUG: extra CTX instrumentations for %s: %u * %u\n", + F.getName().str().c_str(), inst - inst_save, call_counter); + + } + + for (auto &IN : BB) { + + // check all calls and where callee count == 1 instrument + // our current caller_id to __afl_ctx + if (auto callInst = dyn_cast<CallInst>(&IN)) { + + Function *Callee = callInst->getCalledFunction(); + if (countCallers(Callee) == 1) { + + if (debug) + fprintf(stderr, "DEBUG: %s call to %s with only one caller\n", + F.getName().str().c_str(), + Callee->getName().str().c_str()); + + IRBuilder<> Builder(IN.getContext()); + Builder.SetInsertPoint(callInst); + StoreInst *StoreCtx = + Builder.CreateStore(PrevCtxLoad, AFLContext); + StoreCtx->setMetadata("nosanitize", N); + + } + + } + + } + + } + + } + + } + + inst = inst_save; + + /* if (debug) + fprintf(stderr, "Next instrumentation (%u-%u=%u %u-%u=%u)\n", inst, + inst_save, inst - inst_save, afl_global_id, save_global, + afl_global_id - save_global);*/ + + } for (auto &BB : F) { + skip_next = 0; + + /* + uint32_t j = 0; + fprintf(stderr, "BB %p ============================================\n", + CTX_add);*/ + for (auto &IN : BB) { + /* j++; + uint32_t i = 1; + std::string errMsg; + raw_string_ostream os(errMsg); + IN.print(os); + fprintf(stderr, "Next instruction, BB size now %zu: %02u %s\n", + BB.size(), j, os.str().c_str()); for (auto &IN2 : BB) { + + std::string errMsg2; + raw_string_ostream os2(errMsg2); + IN2.print(os2); + fprintf( + stderr, "%s %02u: %s\n", + strcmp(os.str().c_str(), os2.str().c_str()) == 0 ? ">>>" : " + ", i++, os2.str().c_str()); + + }*/ + CallInst *callInst = nullptr; if ((callInst = dyn_cast<CallInst>(&IN))) { @@ -1313,6 +1732,19 @@ void ModuleSanitizerCoverageLTO::instrumentFunction( if (FuncName.compare(StringRef("__afl_coverage_interesting"))) continue; Value *val = ConstantInt::get(Int32Ty, ++afl_global_id); + if (CTX_add) { + + IRBuilder<> Builder(Context); + LoadInst *CTX_load = Builder.CreateLoad( +#if LLVM_VERSION_MAJOR >= 14 + Builder.getInt32Ty(), +#endif + CTX_add); + ModuleSanitizerCoverageLTO::SetNoSanitizeMetadata(CTX_load); + val = Builder.CreateAdd(val, CTX_load); + + } + callInst->setOperand(1, val); ++inst; @@ -1320,164 +1752,228 @@ void ModuleSanitizerCoverageLTO::instrumentFunction( SelectInst *selectInst = nullptr; - /* - std::string errMsg; - raw_string_ostream os(errMsg); - IN.print(os); - fprintf(stderr, "X(%u): %s\n", skip_next, os.str().c_str()); - */ - if (!skip_next && (selectInst = dyn_cast<SelectInst>(&IN))) { + if ((selectInst = dyn_cast<SelectInst>(&IN))) { - uint32_t vector_cnt = 0; - Value *condition = selectInst->getCondition(); - Value *result; - auto t = condition->getType(); - IRBuilder<> IRB(selectInst->getNextNode()); + if (!skip_next) { - ++select_cnt; + // fprintf(stderr, "Select in\n"); - if (t->getTypeID() == llvm::Type::IntegerTyID) { + uint32_t vector_cnt = 0; + Value *condition = selectInst->getCondition(); + Value *result; + auto t = condition->getType(); + IRBuilder<> IRB(selectInst->getNextNode()); - Value *val1 = ConstantInt::get(Int32Ty, ++afl_global_id); - Value *val2 = ConstantInt::get(Int32Ty, ++afl_global_id); - result = IRB.CreateSelect(condition, val1, val2); - skip_next = 1; - inst += 2; + ++select_cnt; + + if (t->getTypeID() == llvm::Type::IntegerTyID) { - } else + Value *val1 = ConstantInt::get(Int32Ty, ++afl_global_id); + Value *val2 = ConstantInt::get(Int32Ty, ++afl_global_id); + if (CTX_add) { + LoadInst *CTX_load = IRB.CreateLoad( #if LLVM_VERSION_MAJOR >= 14 - if (t->getTypeID() == llvm::Type::FixedVectorTyID) { + IRB.getInt32Ty(), +#endif + CTX_add); + val1 = IRB.CreateAdd(val1, CTX_load); + val2 = IRB.CreateAdd(val2, CTX_load); - FixedVectorType *tt = dyn_cast<FixedVectorType>(t); - if (tt) { + } - uint32_t elements = tt->getElementCount().getFixedValue(); - vector_cnt = elements; - inst += vector_cnt * 2; - if (elements) { + result = IRB.CreateSelect(condition, val1, val2); + skip_next = 1; + inst += 2; - FixedVectorType *GuardPtr1 = - FixedVectorType::get(Int32Ty, elements); - FixedVectorType *GuardPtr2 = - FixedVectorType::get(Int32Ty, elements); - Value *x, *y; + } else - Value *val1 = ConstantInt::get(Int32Ty, ++afl_global_id); - Value *val2 = ConstantInt::get(Int32Ty, ++afl_global_id); - x = IRB.CreateInsertElement(GuardPtr1, val1, (uint64_t)0); - y = IRB.CreateInsertElement(GuardPtr2, val2, (uint64_t)0); +#if LLVM_VERSION_MAJOR >= 14 + if (t->getTypeID() == llvm::Type::FixedVectorTyID) { - for (uint64_t i = 1; i < elements; i++) { + FixedVectorType *tt = dyn_cast<FixedVectorType>(t); + if (tt) { - val1 = ConstantInt::get(Int32Ty, ++afl_global_id); - val2 = ConstantInt::get(Int32Ty, ++afl_global_id); - x = IRB.CreateInsertElement(GuardPtr1, val1, i); - y = IRB.CreateInsertElement(GuardPtr2, val2, i); + uint32_t elements = tt->getElementCount().getFixedValue(); + vector_cnt = elements; + inst += vector_cnt * 2; + if (elements) { - } + FixedVectorType *GuardPtr1 = + FixedVectorType::get(Int32Ty, elements); + FixedVectorType *GuardPtr2 = + FixedVectorType::get(Int32Ty, elements); + Value *x, *y; - result = IRB.CreateSelect(condition, x, y); - skip_next = 1; + Value *val1 = ConstantInt::get(Int32Ty, ++afl_global_id); + Value *val2 = ConstantInt::get(Int32Ty, ++afl_global_id); + if (CTX_add) { - } + LoadInst *CTX_load = IRB.CreateLoad( + #if LLVM_VERSION_MAJOR >= 14 + IRB.getInt32Ty(), + #endif + CTX_add); + val1 = IRB.CreateAdd(val1, CTX_load); + val2 = IRB.CreateAdd(val2, CTX_load); - } + } - } else + x = IRB.CreateInsertElement(GuardPtr1, val1, (uint64_t)0); + y = IRB.CreateInsertElement(GuardPtr2, val2, (uint64_t)0); -#endif - { + for (uint64_t i = 1; i < elements; i++) { - unhandled++; - continue; + val1 = ConstantInt::get(Int32Ty, ++afl_global_id); + val2 = ConstantInt::get(Int32Ty, ++afl_global_id); + /*if (CTX_add) { // already loaded I guess - } + LoadInst *CTX_load = IRB.CreateLoad( + #if LLVM_VERSION_MAJOR >= 14 + IRB.getInt32Ty(), + #endif + CTX_add); + val1 = IRB.CreateAdd(val1, CTX_load); + val2 = IRB.CreateAdd(val2, CTX_load); + + }*/ - uint32_t vector_cur = 0; - /* Load SHM pointer */ - LoadInst *MapPtr = - IRB.CreateLoad(PointerType::get(Int8Ty, 0), AFLMapPtr); - ModuleSanitizerCoverageLTO::SetNoSanitizeMetadata(MapPtr); + x = IRB.CreateInsertElement(GuardPtr1, val1, i); + y = IRB.CreateInsertElement(GuardPtr2, val2, i); - while (1) { + } - /* Get CurLoc */ - Value *MapPtrIdx = nullptr; + result = IRB.CreateSelect(condition, x, y); + skip_next = 1; - /* Load counter for CurLoc */ - if (!vector_cnt) { + } - MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, result); + } - } else { + } else + +#endif + { - auto element = IRB.CreateExtractElement(result, vector_cur++); - MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, element); + ++unhandled; + continue; } - if (use_threadsafe_counters) { + uint32_t vector_cur = 0; + /* Load SHM pointer */ + LoadInst *MapPtr = + IRB.CreateLoad(PointerType::get(Int8Ty, 0), AFLMapPtr); + ModuleSanitizerCoverageLTO::SetNoSanitizeMetadata(MapPtr); + + while (1) { + + /* Get CurLoc */ + Value *MapPtrIdx = nullptr; + + /* Load counter for CurLoc */ + if (!vector_cnt) { + + MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, result); + + } else { + + auto element = IRB.CreateExtractElement(result, vector_cur++); + MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, element); + + } + + if (use_threadsafe_counters) { - IRB.CreateAtomicRMW(llvm::AtomicRMWInst::BinOp::Add, MapPtrIdx, One, + IRB.CreateAtomicRMW(llvm::AtomicRMWInst::BinOp::Add, MapPtrIdx, + One, #if LLVM_VERSION_MAJOR >= 13 - llvm::MaybeAlign(1), + llvm::MaybeAlign(1), #endif - llvm::AtomicOrdering::Monotonic); + llvm::AtomicOrdering::Monotonic); - } else { + } else { - LoadInst *Counter = IRB.CreateLoad(IRB.getInt8Ty(), MapPtrIdx); - ModuleSanitizerCoverageLTO::SetNoSanitizeMetadata(Counter); + LoadInst *Counter = IRB.CreateLoad(IRB.getInt8Ty(), MapPtrIdx); + ModuleSanitizerCoverageLTO::SetNoSanitizeMetadata(Counter); - /* Update bitmap */ + /* Update bitmap */ - Value *Incr = IRB.CreateAdd(Counter, One); + Value *Incr = IRB.CreateAdd(Counter, One); - if (skip_nozero == NULL) { + if (skip_nozero == NULL) { - auto cf = IRB.CreateICmpEQ(Incr, Zero); - auto carry = IRB.CreateZExt(cf, Int8Ty); - Incr = IRB.CreateAdd(Incr, carry); + auto cf = IRB.CreateICmpEQ(Incr, Zero); + auto carry = IRB.CreateZExt(cf, Int8Ty); + Incr = IRB.CreateAdd(Incr, carry); + + } + + auto nosan = IRB.CreateStore(Incr, MapPtrIdx); + ModuleSanitizerCoverageLTO::SetNoSanitizeMetadata(nosan); } - auto nosan = IRB.CreateStore(Incr, MapPtrIdx); - ModuleSanitizerCoverageLTO::SetNoSanitizeMetadata(nosan); + if (!vector_cnt || vector_cnt == vector_cur) { break; } } - if (!vector_cnt || vector_cnt == vector_cur) { break; } - - } + skip_next = 1; + // fprintf(stderr, "Select out\n"); - skip_next = 1; + } else { - } else { + // fprintf(stderr, "Select skip\n"); + skip_next = 0; - skip_next = 0; + } } } - if (shouldInstrumentBlock(F, &BB, DT, PDT, Options)) - BlocksToInstrument.push_back(&BB); - for (auto &Inst : BB) { + if (!instrument_ctx) + if (shouldInstrumentBlock(F, &BB, DT, PDT, Options)) + BlocksToInstrument.push_back(&BB); - if (Options.IndirectCalls) { + /* + for (auto &Inst : BB) { - CallBase *CB = dyn_cast<CallBase>(&Inst); - if (CB && !CB->getCalledFunction()) IndirCalls.push_back(&Inst); + if (Options.IndirectCalls) { - } + CallBase *CB = dyn_cast<CallBase>(&Inst); + if (CB && !CB->getCalledFunction()) IndirCalls.push_back(&Inst); - } + } + + }*/ } InjectCoverage(F, BlocksToInstrument, IsLeafFunc); - InjectCoverageForIndirectCalls(F, IndirCalls); + // InjectCoverageForIndirectCalls(F, IndirCalls); + + /*if (debug) + fprintf(stderr, "Done instrumentation (%u-%u=%u %u-%u=%u)\n", inst, + inst_save, inst - inst_save, afl_global_id, save_global, + afl_global_id - save_global);*/ + + if (inst_in_this_func && call_counter > 1) { + + if (inst_in_this_func != afl_global_id - save_global) { + + fprintf( + stderr, + "BUG! inst_in_this_func %u != afl_global_id %u - save_global %u\n", + inst_in_this_func, afl_global_id, save_global); + exit(-1); + + } + + extra_ctx_inst += inst_in_this_func * (call_counter - 1); + afl_global_id += extra_ctx_inst; + + } } @@ -1603,6 +2099,34 @@ bool ModuleSanitizerCoverageLTO::InjectCoverage( } +bool ModuleSanitizerCoverageLTO::Fake_InjectCoverage( + Function &F, ArrayRef<BasicBlock *> AllBlocks, bool IsLeafFunc) { + + if (AllBlocks.empty()) return false; + + for (size_t i = 0, N = AllBlocks.size(); i < N; i++) { + + if (BlockList.size()) { + + int skip = 0; + for (uint32_t k = 0; k < BlockList.size(); k++) { + + if (AllBlocks[i] == BlockList[k]) { skip = 1; } + + } + + if (skip) continue; + + } + + ++inst; // InjectCoverageAtBlock() + + } + + return true; + +} + // On every indirect call we call a run-time function // __sanitizer_cov_indir_call* with two parameters: // - callee address, @@ -1610,6 +2134,7 @@ bool ModuleSanitizerCoverageLTO::InjectCoverage( // 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 ModuleSanitizerCoverageLTO::InjectCoverageForIndirectCalls( Function &F, ArrayRef<Instruction *> IndirCalls) { @@ -1628,6 +2153,8 @@ void ModuleSanitizerCoverageLTO::InjectCoverageForIndirectCalls( } +*/ + void ModuleSanitizerCoverageLTO::InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx, @@ -1674,6 +2201,19 @@ void ModuleSanitizerCoverageLTO::InjectCoverageAtBlock(Function &F, /* Set the ID of the inserted basic block */ ConstantInt *CurLoc = ConstantInt::get(Int32Tyi, afl_global_id); + Value *val = CurLoc; + + if (CTX_add) { + + LoadInst *CTX_load = IRB.CreateLoad( +#if LLVM_VERSION_MAJOR >= 14 + IRB.getInt32Ty(), +#endif + CTX_add); + ModuleSanitizerCoverageLTO::SetNoSanitizeMetadata(CTX_load); + val = IRB.CreateAdd(CurLoc, CTX_load); + + } /* Load SHM pointer */ @@ -1681,13 +2221,13 @@ void ModuleSanitizerCoverageLTO::InjectCoverageAtBlock(Function &F, if (map_addr) { - MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtrFixed, CurLoc); + MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtrFixed, val); } else { LoadInst *MapPtr = IRB.CreateLoad(PointerType::get(Int8Ty, 0), AFLMapPtr); ModuleSanitizerCoverageLTO::SetNoSanitizeMetadata(MapPtr); - MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, CurLoc); + MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, val); } @@ -1722,12 +2262,10 @@ void ModuleSanitizerCoverageLTO::InjectCoverageAtBlock(Function &F, // done :) - inst++; + ++inst; // AFL++ END /* - XXXXXXXXXXXXXXXXXXX - auto GuardPtr = IRB.CreateIntToPtr( IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), ConstantInt::get(IntptrTy, Idx * 4)), diff --git a/instrumentation/afl-compiler-rt.o.c b/instrumentation/afl-compiler-rt.o.c index caa3c3a8..e450dc45 100644 --- a/instrumentation/afl-compiler-rt.o.c +++ b/instrumentation/afl-compiler-rt.o.c @@ -87,6 +87,10 @@ __attribute__((weak)) void __sanitizer_symbolize_pc(void *, const char *fmt, #include <sys/mman.h> #include <fcntl.h> +#ifdef AFL_PERSISTENT_RECORD + #include "afl-persistent-replay.h" +#endif + /* Globals needed by the injected instrumentation. The __afl_area_initial region is used for instrumentation output before __afl_map_shm() has a chance to run. It will end up as .comm, so it shouldn't be too wasteful. */ @@ -186,6 +190,8 @@ __thread u32 __afl_prev_ctx; struct cmp_map *__afl_cmp_map; struct cmp_map *__afl_cmp_map_backup; +static u8 __afl_cmplog_max_len = 32; // 16-32 + /* Child pid? */ static s32 child_pid; @@ -264,7 +270,7 @@ static void send_forkserver_error(int error) { u32 status; if (!error || error > 0xffff) return; - status = (FS_OPT_ERROR | FS_OPT_SET_ERROR(error)); + status = (FS_NEW_ERROR | error); if (write(FORKSRV_FD + 1, (char *)&status, 4) != 4) { return; } } @@ -367,32 +373,13 @@ static void __afl_map_shm(void) { if ((ptr = getenv("AFL_MAP_SIZE")) != NULL) { val = atoi(ptr); } if (val < __afl_final_loc) { - if (__afl_final_loc > FS_OPT_MAX_MAPSIZE) { - - if (!getenv("AFL_QUIET")) - fprintf(stderr, - "Error: AFL++ tools *require* to set AFL_MAP_SIZE to %u " - "to be able to run this instrumented program!\n", - __afl_final_loc); - - if (id_str) { - - send_forkserver_error(FS_ERROR_MAP_SIZE); - exit(-1); - - } - - } else { + if (__afl_final_loc > MAP_INITIAL_SIZE && !getenv("AFL_QUIET")) { - if (__afl_final_loc > MAP_INITIAL_SIZE && !getenv("AFL_QUIET")) { - - fprintf(stderr, - "Warning: AFL++ tools might need to set AFL_MAP_SIZE to %u " - "to be able to run this instrumented program if this " - "crashes!\n", - __afl_final_loc); - - } + fprintf(stderr, + "Warning: AFL++ tools might need to set AFL_MAP_SIZE to %u " + "to be able to run this instrumented program if this " + "crashes!\n", + __afl_final_loc); } @@ -400,15 +387,6 @@ static void __afl_map_shm(void) { } - } else { - - if (getenv("AFL_DUMP_MAP_SIZE")) { - - printf("%u\n", MAP_SIZE); - exit(-1); - - } - } if (__afl_sharedmem_fuzzing && (!id_str || !getenv(SHM_FUZZ_ENV_VAR) || @@ -474,14 +452,13 @@ static void __afl_map_shm(void) { if (__afl_debug) { - fprintf( - stderr, - "DEBUG: (1) id_str %s, __afl_area_ptr %p, __afl_area_initial %p, " - "__afl_area_ptr_dummy %p, __afl_map_addr 0x%llx, MAP_SIZE %u, " - "__afl_final_loc %u, __afl_map_size %u, max_size_forkserver %u/0x%x\n", - id_str == NULL ? "<null>" : id_str, __afl_area_ptr, __afl_area_initial, - __afl_area_ptr_dummy, __afl_map_addr, MAP_SIZE, __afl_final_loc, - __afl_map_size, FS_OPT_MAX_MAPSIZE, FS_OPT_MAX_MAPSIZE); + fprintf(stderr, + "DEBUG: (1) id_str %s, __afl_area_ptr %p, __afl_area_initial %p, " + "__afl_area_ptr_dummy %p, __afl_map_addr 0x%llx, MAP_SIZE %u, " + "__afl_final_loc %u, __afl_map_size %u\n", + id_str == NULL ? "<null>" : id_str, __afl_area_ptr, + __afl_area_initial, __afl_area_ptr_dummy, __afl_map_addr, MAP_SIZE, + __afl_final_loc, __afl_map_size); } @@ -639,12 +616,10 @@ static void __afl_map_shm(void) { fprintf(stderr, "DEBUG: (2) id_str %s, __afl_area_ptr %p, __afl_area_initial %p, " "__afl_area_ptr_dummy %p, __afl_map_addr 0x%llx, MAP_SIZE " - "%u, __afl_final_loc %u, __afl_map_size %u, " - "max_size_forkserver %u/0x%x\n", + "%u, __afl_final_loc %u, __afl_map_size %u", id_str == NULL ? "<null>" : id_str, __afl_area_ptr, __afl_area_initial, __afl_area_ptr_dummy, __afl_map_addr, MAP_SIZE, - __afl_final_loc, __afl_map_size, FS_OPT_MAX_MAPSIZE, - FS_OPT_MAX_MAPSIZE); + __afl_final_loc, __afl_map_size); } @@ -761,6 +736,19 @@ static void __afl_map_shm(void) { #endif // __AFL_CODE_COVERAGE + if (!__afl_cmp_map && getenv("AFL_CMPLOG_DEBUG")) { + + __afl_cmp_map_backup = __afl_cmp_map = malloc(sizeof(struct cmp_map)); + + } + + if (getenv("AFL_CMPLOG_MAX_LEN")) { + + int tmp = atoi(getenv("AFL_CMPLOG_MAX_LEN")); + if (tmp >= 16 && tmp <= 32) { __afl_cmplog_max_len = tmp; } + + } + } /* unmap SHM. */ @@ -855,242 +843,6 @@ void write_error_with_location(char *text, char *filename, int linenumber) { } -#ifdef __linux__ -static void __afl_start_snapshots(void) { - - static u8 tmp[4] = {0, 0, 0, 0}; - u32 status = 0; - u32 already_read_first = 0; - u32 was_killed; - - u8 child_stopped = 0; - - void (*old_sigchld_handler)(int) = signal(SIGCHLD, SIG_DFL); - - /* Phone home and tell the parent that we're OK. If parent isn't there, - assume we're not running in forkserver mode and just execute program. */ - - status |= (FS_OPT_ENABLED | FS_OPT_SNAPSHOT | FS_OPT_NEWCMPLOG); - if (__afl_sharedmem_fuzzing) { status |= FS_OPT_SHDMEM_FUZZ; } - if (__afl_map_size <= FS_OPT_MAX_MAPSIZE) - status |= (FS_OPT_SET_MAPSIZE(__afl_map_size) | FS_OPT_MAPSIZE); - if (__afl_dictionary_len && __afl_dictionary) { status |= FS_OPT_AUTODICT; } - memcpy(tmp, &status, 4); - - if (write(FORKSRV_FD + 1, tmp, 4) != 4) { return; } - - if (__afl_sharedmem_fuzzing || (__afl_dictionary_len && __afl_dictionary)) { - - if (read(FORKSRV_FD, &was_killed, 4) != 4) { - - write_error("read to afl-fuzz"); - _exit(1); - - } - - if (__afl_debug) { - - fprintf(stderr, "DEBUG: target forkserver recv: %08x\n", was_killed); - - } - - if ((was_killed & (FS_OPT_ENABLED | FS_OPT_SHDMEM_FUZZ)) == - (FS_OPT_ENABLED | FS_OPT_SHDMEM_FUZZ)) { - - __afl_map_shm_fuzz(); - - } - - if ((was_killed & (FS_OPT_ENABLED | FS_OPT_AUTODICT)) == - (FS_OPT_ENABLED | FS_OPT_AUTODICT) && - __afl_dictionary_len && __afl_dictionary) { - - // great lets pass the dictionary through the forkserver FD - u32 len = __afl_dictionary_len, offset = 0; - s32 ret; - - if (write(FORKSRV_FD + 1, &len, 4) != 4) { - - write(2, "Error: could not send dictionary len\n", - strlen("Error: could not send dictionary len\n")); - _exit(1); - - } - - while (len != 0) { - - ret = write(FORKSRV_FD + 1, __afl_dictionary + offset, len); - - if (ret < 1) { - - write(2, "Error: could not send dictionary\n", - strlen("Error: could not send dictionary\n")); - _exit(1); - - } - - len -= ret; - offset += ret; - - } - - } else { - - // uh this forkserver does not understand extended option passing - // or does not want the dictionary - if (!__afl_fuzz_ptr) already_read_first = 1; - - } - - } - - while (1) { - - int status; - - if (already_read_first) { - - already_read_first = 0; - - } else { - - /* Wait for parent by reading from the pipe. Abort if read fails. */ - if (read(FORKSRV_FD, &was_killed, 4) != 4) { - - write_error("reading from afl-fuzz"); - _exit(1); - - } - - } - - #ifdef _AFL_DOCUMENT_MUTATIONS - if (__afl_fuzz_ptr) { - - static uint32_t counter = 0; - char fn[32]; - sprintf(fn, "%09u:forkserver", counter); - s32 fd_doc = open(fn, O_WRONLY | O_CREAT | O_TRUNC, DEFAULT_PERMISSION); - if (fd_doc >= 0) { - - if (write(fd_doc, __afl_fuzz_ptr, *__afl_fuzz_len) != *__afl_fuzz_len) { - - fprintf(stderr, "write of mutation file failed: %s\n", fn); - unlink(fn); - - } - - close(fd_doc); - - } - - counter++; - - } - - #endif - - /* If we stopped the child in persistent mode, but there was a race - condition and afl-fuzz already issued SIGKILL, write off the old - process. */ - - if (child_stopped && was_killed) { - - child_stopped = 0; - if (waitpid(child_pid, &status, 0) < 0) { - - write_error("child_stopped && was_killed"); - _exit(1); // TODO why exit? - - } - - } - - if (!child_stopped) { - - /* Once woken up, create a clone of our process. */ - - child_pid = fork(); - if (child_pid < 0) { - - write_error("fork"); - _exit(1); - - } - - /* In child process: close fds, resume execution. */ - - if (!child_pid) { - - //(void)nice(-20); // does not seem to improve - - signal(SIGCHLD, old_sigchld_handler); - signal(SIGTERM, old_sigterm_handler); - - close(FORKSRV_FD); - close(FORKSRV_FD + 1); - - if (!afl_snapshot_take(AFL_SNAPSHOT_MMAP | AFL_SNAPSHOT_FDS | - AFL_SNAPSHOT_REGS | AFL_SNAPSHOT_EXIT)) { - - raise(SIGSTOP); - - } - - __afl_area_ptr[0] = 1; - memset(__afl_prev_loc, 0, NGRAM_SIZE_MAX * sizeof(PREV_LOC_T)); - - return; - - } - - } else { - - /* Special handling for persistent mode: if the child is alive but - currently stopped, simply restart it with SIGCONT. */ - - kill(child_pid, SIGCONT); - child_stopped = 0; - - } - - /* In parent process: write PID to pipe, then wait for child. */ - - if (write(FORKSRV_FD + 1, &child_pid, 4) != 4) { - - write_error("write to afl-fuzz"); - _exit(1); - - } - - if (waitpid(child_pid, &status, WUNTRACED) < 0) { - - write_error("waitpid"); - _exit(1); - - } - - /* In persistent mode, the child stops itself with SIGSTOP to indicate - a successful run. In this case, we want to wake it up without forking - again. */ - - if (WIFSTOPPED(status)) child_stopped = 1; - - /* Relay wait status to pipe, then loop back. */ - - if (write(FORKSRV_FD + 1, &status, 4) != 4) { - - write_error("writing to afl-fuzz"); - _exit(1); - - } - - } - -} - -#endif - /* Fork server logic. */ static void __afl_start_forkserver(void) { @@ -1103,113 +855,92 @@ static void __afl_start_forkserver(void) { old_sigterm_handler = orig_action.sa_handler; signal(SIGTERM, at_exit); -#ifdef __linux__ - if (/*!is_persistent &&*/ !__afl_cmp_map && !getenv("AFL_NO_SNAPSHOT") && - afl_snapshot_init() >= 0) { - - __afl_start_snapshots(); - return; - - } - -#endif - - u8 tmp[4] = {0, 0, 0, 0}; - u32 status_for_fsrv = 0; u32 already_read_first = 0; u32 was_killed; + u32 version = 0x41464c00 + FS_NEW_VERSION_MAX; + u32 tmp = version ^ 0xffffffff, status2, status = version; + u8 *msg = (u8 *)&status; + u8 *reply = (u8 *)&status2; u8 child_stopped = 0; void (*old_sigchld_handler)(int) = signal(SIGCHLD, SIG_DFL); - if (__afl_map_size <= FS_OPT_MAX_MAPSIZE) { + /* Phone home and tell the parent that we're OK. If parent isn't there, + assume we're not running in forkserver mode and just execute program. */ - status_for_fsrv |= (FS_OPT_SET_MAPSIZE(__afl_map_size) | FS_OPT_MAPSIZE); + // return because possible non-forkserver usage + if (write(FORKSRV_FD + 1, msg, 4) != 4) { return; } - } + if (read(FORKSRV_FD, reply, 4) != 4) { _exit(1); } + if (tmp != status2) { - if (__afl_dictionary_len && __afl_dictionary) { - - status_for_fsrv |= FS_OPT_AUTODICT; + write_error("wrong forkserver message from AFL++ tool"); + _exit(1); } - if (__afl_sharedmem_fuzzing) { status_for_fsrv |= FS_OPT_SHDMEM_FUZZ; } - if (status_for_fsrv) { + // send the set/requested options to forkserver + status = FS_NEW_OPT_MAPSIZE; // we always send the map size + if (__afl_sharedmem_fuzzing) { status |= FS_NEW_OPT_SHDMEM_FUZZ; } + if (__afl_dictionary_len && __afl_dictionary) { - status_for_fsrv |= (FS_OPT_ENABLED | FS_OPT_NEWCMPLOG); + status |= FS_NEW_OPT_AUTODICT; } - memcpy(tmp, &status_for_fsrv, 4); + if (write(FORKSRV_FD + 1, msg, 4) != 4) { _exit(1); } - /* Phone home and tell the parent that we're OK. If parent isn't there, - assume we're not running in forkserver mode and just execute program. */ + // Now send the parameters for the set options, increasing by option number - if (write(FORKSRV_FD + 1, tmp, 4) != 4) { return; } + // FS_NEW_OPT_MAPSIZE - we always send the map size + status = __afl_map_size; + if (write(FORKSRV_FD + 1, msg, 4) != 4) { _exit(1); } - __afl_connected = 1; - - if (__afl_sharedmem_fuzzing || (__afl_dictionary_len && __afl_dictionary)) { + // FS_NEW_OPT_SHDMEM_FUZZ - no data - if (read(FORKSRV_FD, &was_killed, 4) != 4) _exit(1); - - if (__afl_debug) { - - fprintf(stderr, "DEBUG: target forkserver recv: %08x\n", was_killed); + // FS_NEW_OPT_AUTODICT - send autodictionary + if (__afl_dictionary_len && __afl_dictionary) { - } + // pass the dictionary through the forkserver FD + u32 len = __afl_dictionary_len, offset = 0; - if ((was_killed & (FS_OPT_ENABLED | FS_OPT_SHDMEM_FUZZ)) == - (FS_OPT_ENABLED | FS_OPT_SHDMEM_FUZZ)) { + if (write(FORKSRV_FD + 1, &len, 4) != 4) { - __afl_map_shm_fuzz(); + write(2, "Error: could not send dictionary len\n", + strlen("Error: could not send dictionary len\n")); + _exit(1); } - if ((was_killed & (FS_OPT_ENABLED | FS_OPT_AUTODICT)) == - (FS_OPT_ENABLED | FS_OPT_AUTODICT) && - __afl_dictionary_len && __afl_dictionary) { + while (len != 0) { - // great lets pass the dictionary through the forkserver FD - u32 len = __afl_dictionary_len, offset = 0; + s32 ret; + ret = write(FORKSRV_FD + 1, __afl_dictionary + offset, len); - if (write(FORKSRV_FD + 1, &len, 4) != 4) { + if (ret < 1) { - write(2, "Error: could not send dictionary len\n", - strlen("Error: could not send dictionary len\n")); + write_error("could not send dictionary"); _exit(1); } - while (len != 0) { - - s32 ret; - ret = write(FORKSRV_FD + 1, __afl_dictionary + offset, len); - - if (ret < 1) { - - write(2, "Error: could not send dictionary\n", - strlen("Error: could not send dictionary\n")); - _exit(1); - - } + len -= ret; + offset += ret; - len -= ret; - offset += ret; + } - } + } - } else { + // send welcome message as final message + status = version; + if (write(FORKSRV_FD + 1, msg, 4) != 4) { _exit(1); } - // uh this forkserver does not understand extended option passing - // or does not want the dictionary - if (!__afl_fuzz_ptr) already_read_first = 1; + // END forkserver handshake - } + __afl_connected = 1; - } + if (__afl_sharedmem_fuzzing) { __afl_map_shm_fuzz(); } while (1) { @@ -1225,7 +956,7 @@ static void __afl_start_forkserver(void) { if (read(FORKSRV_FD, &was_killed, 4) != 4) { - // write_error("read from afl-fuzz"); + write_error("read from AFL++ tool"); _exit(1); } @@ -1354,6 +1085,10 @@ int __afl_persistent_loop(unsigned int max_cnt) { static u8 first_pass = 1; static u32 cycle_cnt; +#ifdef AFL_PERSISTENT_RECORD + char tcase[PATH_MAX]; +#endif + if (first_pass) { /* Make sure that every iteration of __AFL_LOOP() starts with a clean slate. @@ -1365,14 +1100,59 @@ int __afl_persistent_loop(unsigned int max_cnt) { __afl_area_ptr[0] = 1; memset(__afl_prev_loc, 0, NGRAM_SIZE_MAX * sizeof(PREV_LOC_T)); - cycle_cnt = max_cnt; first_pass = 0; __afl_selective_coverage_temp = 1; +#ifdef AFL_PERSISTENT_RECORD + if (unlikely(is_replay_record)) { + + cycle_cnt = replay_record_cnt; + goto persistent_record; + + } else + +#endif + { + + cycle_cnt = max_cnt; + + } + return 1; } else if (--cycle_cnt) { +#ifdef AFL_PERSISTENT_RECORD + if (unlikely(is_replay_record)) { + + persistent_record: + + snprintf(tcase, PATH_MAX, "%s/%s", + replay_record_dir ? replay_record_dir : "./", + record_list[replay_record_cnt - cycle_cnt]->d_name); + + #ifdef AFL_PERSISTENT_REPLAY_ARGPARSE + if (unlikely(record_arg)) { + + *record_arg = tcase; + + } else + + #endif // AFL_PERSISTENT_REPLAY_ARGPARSE + { + + int fd = open(tcase, O_RDONLY); + dup2(fd, 0); + close(fd); + + } + + return 1; + + } + +#endif + raise(SIGSTOP); __afl_area_ptr[0] = 1; @@ -1837,7 +1617,7 @@ void __sanitizer_cov_pcs_init(const uintptr_t *pcs_beg, } - if (pc_filter) { + if (pc_filter && !mod_info->next) { char PcDescr[1024]; // This function is a part of the sanitizer run-time. @@ -1864,7 +1644,8 @@ void __sanitizer_cov_pcs_init(const uintptr_t *pcs_beg, } - if (__afl_filter_pcs && strstr(mod_info->name, __afl_filter_pcs_module)) { + if (__afl_filter_pcs && !mod_info->next && + strstr(mod_info->name, __afl_filter_pcs_module)) { u32 result_index; if (locate_in_pcs(PC, &result_index)) { @@ -1889,7 +1670,7 @@ void __sanitizer_cov_pcs_init(const uintptr_t *pcs_beg, } - mod_info->mapped = 1; + if (__afl_pcmap_ptr) { mod_info->mapped = 1; } if (__afl_debug) { @@ -2181,7 +1962,8 @@ void __cmplog_ins_hook1(uint8_t arg1, uint8_t arg2, uint8_t attr) { void __cmplog_ins_hook2(uint16_t arg1, uint16_t arg2, uint8_t attr) { - if (unlikely(!__afl_cmp_map || arg1 == arg2)) return; + if (likely(!__afl_cmp_map)) return; + if (unlikely(arg1 == arg2)) return; uintptr_t k = (uintptr_t)__builtin_return_address(0); k = (uintptr_t)(default_hash((u8 *)&k, sizeof(uintptr_t)) & (CMP_MAP_W - 1)); @@ -2219,7 +2001,8 @@ void __cmplog_ins_hook4(uint32_t arg1, uint32_t arg2, uint8_t attr) { // fprintf(stderr, "hook4 arg0=%x arg1=%x attr=%u\n", arg1, arg2, attr); - if (unlikely(!__afl_cmp_map || arg1 == arg2)) return; + if (likely(!__afl_cmp_map)) return; + if (unlikely(arg1 == arg2)) return; uintptr_t k = (uintptr_t)__builtin_return_address(0); k = (uintptr_t)(default_hash((u8 *)&k, sizeof(uintptr_t)) & (CMP_MAP_W - 1)); @@ -2257,7 +2040,8 @@ void __cmplog_ins_hook8(uint64_t arg1, uint64_t arg2, uint8_t attr) { // fprintf(stderr, "hook8 arg0=%lx arg1=%lx attr=%u\n", arg1, arg2, attr); - if (unlikely(!__afl_cmp_map || arg1 == arg2)) return; + if (likely(!__afl_cmp_map)) return; + if (unlikely(arg1 == arg2)) return; uintptr_t k = (uintptr_t)__builtin_return_address(0); k = (uintptr_t)(default_hash((u8 *)&k, sizeof(uintptr_t)) & (CMP_MAP_W - 1)); @@ -2300,7 +2084,8 @@ void __cmplog_ins_hookN(uint128_t arg1, uint128_t arg2, uint8_t attr, // (u64)(arg1 >> 64), (u64)arg1, (u64)(arg2 >> 64), (u64)arg2, size + 1, // attr); - if (unlikely(!__afl_cmp_map || arg1 == arg2)) return; + if (likely(!__afl_cmp_map)) return; + if (unlikely(arg1 == arg2 || size > __afl_cmplog_max_len)) return; uintptr_t k = (uintptr_t)__builtin_return_address(0); k = (uintptr_t)(default_hash((u8 *)&k, sizeof(uintptr_t)) & (CMP_MAP_W - 1)); @@ -2344,6 +2129,7 @@ void __cmplog_ins_hookN(uint128_t arg1, uint128_t arg2, uint8_t attr, void __cmplog_ins_hook16(uint128_t arg1, uint128_t arg2, uint8_t attr) { if (likely(!__afl_cmp_map)) return; + if (16 > __afl_cmplog_max_len) return; uintptr_t k = (uintptr_t)__builtin_return_address(0); k = (uintptr_t)(default_hash((u8 *)&k, sizeof(uintptr_t)) & (CMP_MAP_W - 1)); @@ -2537,13 +2323,25 @@ void __cmplog_rtn_hook_strn(u8 *ptr1, u8 *ptr2, u64 len) { // fprintf(stderr, "RTN1 %p %p %u\n", ptr1, ptr2, len); if (likely(!__afl_cmp_map)) return; - if (unlikely(!len)) return; - int len0 = MIN(len, 31); + if (unlikely(!len || len > __afl_cmplog_max_len)) return; + + int len0 = MIN(len, 32); + int len1 = strnlen(ptr1, len0); - if (len1 < 31) len1 = area_is_valid(ptr1, len1 + 1); + if (len1 <= 32) len1 = area_is_valid(ptr1, len1 + 1); + if (len1 > __afl_cmplog_max_len) len1 = 0; + int len2 = strnlen(ptr2, len0); - if (len2 < 31) len2 = area_is_valid(ptr2, len2 + 1); - int l = MAX(len1, len2); + if (len2 <= 32) len2 = area_is_valid(ptr2, len2 + 1); + if (len2 > __afl_cmplog_max_len) len2 = 0; + + int l; + if (!len1) + l = len2; + else if (!len2) + l = len1; + else + l = MAX(len1, len2); if (l < 2) return; uintptr_t k = (uintptr_t)__builtin_return_address(0); @@ -2587,10 +2385,18 @@ void __cmplog_rtn_hook_str(u8 *ptr1, u8 *ptr2) { // fprintf(stderr, "RTN1 %p %p\n", ptr1, ptr2); if (likely(!__afl_cmp_map)) return; if (unlikely(!ptr1 || !ptr2)) return; - int len1 = strnlen(ptr1, 30) + 1; - int len2 = strnlen(ptr2, 30) + 1; - int l = MAX(len1, len2); - if (l < 3) return; + int len1 = strnlen(ptr1, 31) + 1; + int len2 = strnlen(ptr2, 31) + 1; + if (len1 > __afl_cmplog_max_len) len1 = 0; + if (len2 > __afl_cmplog_max_len) len2 = 0; + int l; + if (!len1) + l = len2; + else if (!len2) + l = len1; + else + l = MAX(len1, len2); + if (l < 2) return; uintptr_t k = (uintptr_t)__builtin_return_address(0); k = (uintptr_t)(default_hash((u8 *)&k, sizeof(uintptr_t)) & (CMP_MAP_W - 1)); @@ -2632,7 +2438,7 @@ void __cmplog_rtn_hook(u8 *ptr1, u8 *ptr2) { /* u32 i; - if (area_is_valid(ptr1, 31) <= 0 || area_is_valid(ptr2, 31) <= 0) return; + if (area_is_valid(ptr1, 32) <= 0 || area_is_valid(ptr2, 32) <= 0) return; fprintf(stderr, "rtn arg0="); for (i = 0; i < 32; i++) fprintf(stderr, "%02x", ptr1[i]); @@ -2645,10 +2451,10 @@ void __cmplog_rtn_hook(u8 *ptr1, u8 *ptr2) { // fprintf(stderr, "RTN1 %p %p\n", ptr1, ptr2); if (likely(!__afl_cmp_map)) return; int l1, l2; - if ((l1 = area_is_valid(ptr1, 31)) <= 0 || - (l2 = area_is_valid(ptr2, 31)) <= 0) + if ((l1 = area_is_valid(ptr1, 32)) <= 0 || + (l2 = area_is_valid(ptr2, 32)) <= 0) return; - int len = MIN(31, MIN(l1, l2)); + int len = MIN(__afl_cmplog_max_len, MIN(l1, l2)); // fprintf(stderr, "RTN2 %u\n", len); uintptr_t k = (uintptr_t)__builtin_return_address(0); @@ -2697,7 +2503,7 @@ void __cmplog_rtn_hook_n(u8 *ptr1, u8 *ptr2, u64 len) { #if 0 /* u32 i; - if (area_is_valid(ptr1, 31) <= 0 || area_is_valid(ptr2, 31) <= 0) return; + if (area_is_valid(ptr1, 32) <= 0 || area_is_valid(ptr2, 32) <= 0) return; fprintf(stderr, "rtn_n len=%u arg0=", len); for (i = 0; i < len; i++) fprintf(stderr, "%02x", ptr1[i]); @@ -2709,12 +2515,15 @@ void __cmplog_rtn_hook_n(u8 *ptr1, u8 *ptr2, u64 len) { // fprintf(stderr, "RTN1 %p %p %u\n", ptr1, ptr2, len); if (likely(!__afl_cmp_map)) return; - if (unlikely(!len)) return; - int l = MIN(31, len); + if (!len) return; + int l = MIN(32, len), l1, l2; - if ((l = area_is_valid(ptr1, l)) <= 0 || (l = area_is_valid(ptr2, l)) <= 0) + if ((l1 = area_is_valid(ptr1, l)) <= 0 || (l2 = area_is_valid(ptr2, l)) <= 0) return; + len = MIN(l1, l2); + if (len > __afl_cmplog_max_len) return; + // fprintf(stderr, "RTN2 %u\n", l); uintptr_t k = (uintptr_t)__builtin_return_address(0); k = (uintptr_t)(default_hash((u8 *)&k, sizeof(uintptr_t)) & (CMP_MAP_W - 1)); diff --git a/instrumentation/afl-gcc-cmptrs-pass.so.cc b/instrumentation/afl-gcc-cmptrs-pass.so.cc index 929a9d7a..96bd5ba8 100644 --- a/instrumentation/afl-gcc-cmptrs-pass.so.cc +++ b/instrumentation/afl-gcc-cmptrs-pass.so.cc @@ -180,19 +180,19 @@ struct afl_cmptrs_pass : afl_base_pass { c = DECL_CONTEXT(c); if (c && TREE_CODE(c) != TRANSLATION_UNIT_DECL) return false; - /* Check that the first nonstatic data member of the record type + /* Check that the first nonstatic named data member of the record type is named _M_dataplus. */ for (c = TYPE_FIELDS(t); c; c = DECL_CHAIN(c)) - if (TREE_CODE(c) == FIELD_DECL) break; + if (TREE_CODE(c) == FIELD_DECL && DECL_NAME(c)) break; if (!c || !integer_zerop(DECL_FIELD_BIT_OFFSET(c)) || strcmp(IDENTIFIER_POINTER(DECL_NAME(c)), "_M_dataplus") != 0) return false; - /* Check that the second nonstatic data member of the record type + /* Check that the second nonstatic named data member of the record type is named _M_string_length. */ tree f2; for (f2 = DECL_CHAIN(c); f2; f2 = DECL_CHAIN(f2)) - if (TREE_CODE(f2) == FIELD_DECL) break; + if (TREE_CODE(f2) == FIELD_DECL && DECL_NAME(f2)) break; if (!f2 /* No need to check this field's offset. */ || strcmp(IDENTIFIER_POINTER(DECL_NAME(f2)), "_M_string_length") != 0) return false; @@ -208,9 +208,12 @@ struct afl_cmptrs_pass : afl_base_pass { strcmp(IDENTIFIER_POINTER(TYPE_IDENTIFIER(c)), "_Alloc_hider") != 0) return false; - /* And its first data member is named _M_p. */ + /* And its first nonstatic named data member should be named _M_p. + There may be (unnamed) subobjects from empty base classes. We + skip the subobjects, then check the offset of the first data + member. */ for (c = TYPE_FIELDS(c); c; c = DECL_CHAIN(c)) - if (TREE_CODE(c) == FIELD_DECL) break; + if (TREE_CODE(c) == FIELD_DECL && DECL_NAME(c)) break; if (!c || !integer_zerop(DECL_FIELD_BIT_OFFSET(c)) || strcmp(IDENTIFIER_POINTER(DECL_NAME(c)), "_M_p") != 0) return false; |