1 //===-- DataFlowSanitizer.cpp - dynamic data flow analysis ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file is a part of DataFlowSanitizer, a generalised dynamic data flow
13 /// Unlike other Sanitizer tools, this tool is not designed to detect a specific
14 /// class of bugs on its own. Instead, it provides a generic dynamic data flow
15 /// analysis framework to be used by clients to help detect application-specific
16 /// issues within their own code.
18 /// The analysis is based on automatic propagation of data flow labels (also
19 /// known as taint labels) through a program as it performs computation. Each
20 /// byte of application memory is backed by two bytes of shadow memory which
21 /// hold the label. On Linux/x86_64, memory is laid out as follows:
23 /// +--------------------+ 0x800000000000 (top of memory)
24 /// | application memory |
25 /// +--------------------+ 0x700000008000 (kAppAddr)
29 /// +--------------------+ 0x200200000000 (kUnusedAddr)
31 /// +--------------------+ 0x200000000000 (kUnionTableAddr)
33 /// +--------------------+ 0x000000010000 (kShadowAddr)
34 /// | reserved by kernel |
35 /// +--------------------+ 0x000000000000
37 /// To derive a shadow memory address from an application memory address,
38 /// bits 44-46 are cleared to bring the address into the range
39 /// [0x000000008000,0x100000000000). Then the address is shifted left by 1 to
40 /// account for the double byte representation of shadow labels and move the
41 /// address into the shadow memory range. See the function
42 /// DataFlowSanitizer::getShadowAddress below.
44 /// For more information, please refer to the design document:
45 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
47 #include "llvm/Transforms/Instrumentation.h"
48 #include "llvm/ADT/DenseMap.h"
49 #include "llvm/ADT/DenseSet.h"
50 #include "llvm/ADT/DepthFirstIterator.h"
51 #include "llvm/Analysis/ValueTracking.h"
52 #include "llvm/IR/InlineAsm.h"
53 #include "llvm/IR/IRBuilder.h"
54 #include "llvm/IR/LLVMContext.h"
55 #include "llvm/IR/MDBuilder.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/IR/Value.h"
58 #include "llvm/InstVisitor.h"
59 #include "llvm/Pass.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
62 #include "llvm/Transforms/Utils/SpecialCaseList.h"
67 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
68 // alignment requirements provided by the input IR are correct. For example,
69 // if the input IR contains a load with alignment 8, this flag will cause
70 // the shadow load to have alignment 16. This flag is disabled by default as
71 // we have unfortunately encountered too much code (including Clang itself;
72 // see PR14291) which performs misaligned access.
73 static cl::opt<bool> ClPreserveAlignment(
74 "dfsan-preserve-alignment",
75 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
78 // The greylist file controls how shadow parameters are passed.
79 // The program acts as though every function in the greylist is passed
80 // parameters with zero shadow and that its return value also has zero shadow.
81 // This avoids the use of TLS or extra function parameters to pass shadow state
82 // and essentially makes the function conform to the "native" (i.e. unsanitized)
84 static cl::opt<std::string> ClGreylistFile(
86 cl::desc("File containing the list of functions with a native ABI"),
89 static cl::opt<bool> ClArgsABI(
91 cl::desc("Use the argument ABI rather than the TLS ABI"),
96 class DataFlowSanitizer : public ModulePass {
97 friend struct DFSanFunction;
98 friend class DFSanVisitor;
104 enum InstrumentedABI {
114 IntegerType *ShadowTy;
115 PointerType *ShadowPtrTy;
116 IntegerType *IntptrTy;
117 ConstantInt *ZeroShadow;
118 ConstantInt *ShadowPtrMask;
119 ConstantInt *ShadowPtrMul;
122 void *(*GetArgTLSPtr)();
123 void *(*GetRetvalTLSPtr)();
125 Constant *GetRetvalTLS;
126 FunctionType *DFSanUnionFnTy;
127 FunctionType *DFSanUnionLoadFnTy;
128 Constant *DFSanUnionFn;
129 Constant *DFSanUnionLoadFn;
130 MDNode *ColdCallWeights;
131 SpecialCaseList Greylist;
132 DenseMap<Value *, Function *> UnwrappedFnMap;
134 Value *getShadowAddress(Value *Addr, Instruction *Pos);
135 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
136 FunctionType *getInstrumentedFunctionType(FunctionType *T);
137 InstrumentedABI getInstrumentedABI(Function *F);
138 InstrumentedABI getDefaultInstrumentedABI();
141 DataFlowSanitizer(void *(*getArgTLS)() = 0, void *(*getRetValTLS)() = 0);
143 bool doInitialization(Module &M);
144 bool runOnModule(Module &M);
147 struct DFSanFunction {
148 DataFlowSanitizer &DFS;
150 DataFlowSanitizer::InstrumentedABI IA;
153 DenseMap<Value *, Value *> ValShadowMap;
154 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
155 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
156 DenseSet<Instruction *> SkipInsts;
158 DFSanFunction(DataFlowSanitizer &DFS, Function *F)
159 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI(F)), ArgTLSPtr(0),
161 Value *getArgTLSPtr();
162 Value *getArgTLS(unsigned Index, Instruction *Pos);
163 Value *getRetvalTLS();
164 Value *getShadow(Value *V);
165 void setShadow(Instruction *I, Value *Shadow);
166 Value *combineOperandShadows(Instruction *Inst);
167 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
169 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
173 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
176 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
178 void visitOperandShadowInst(Instruction &I);
180 void visitBinaryOperator(BinaryOperator &BO);
181 void visitCastInst(CastInst &CI);
182 void visitCmpInst(CmpInst &CI);
183 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
184 void visitLoadInst(LoadInst &LI);
185 void visitStoreInst(StoreInst &SI);
186 void visitReturnInst(ReturnInst &RI);
187 void visitCallSite(CallSite CS);
188 void visitPHINode(PHINode &PN);
189 void visitExtractElementInst(ExtractElementInst &I);
190 void visitInsertElementInst(InsertElementInst &I);
191 void visitShuffleVectorInst(ShuffleVectorInst &I);
192 void visitExtractValueInst(ExtractValueInst &I);
193 void visitInsertValueInst(InsertValueInst &I);
194 void visitAllocaInst(AllocaInst &I);
195 void visitSelectInst(SelectInst &I);
196 void visitMemTransferInst(MemTransferInst &I);
201 char DataFlowSanitizer::ID;
202 INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
203 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
205 ModulePass *llvm::createDataFlowSanitizerPass(void *(*getArgTLS)(),
206 void *(*getRetValTLS)()) {
207 return new DataFlowSanitizer(getArgTLS, getRetValTLS);
210 DataFlowSanitizer::DataFlowSanitizer(void *(*getArgTLS)(),
211 void *(*getRetValTLS)())
212 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
213 Greylist(ClGreylistFile) {}
215 FunctionType *DataFlowSanitizer::getInstrumentedFunctionType(FunctionType *T) {
216 llvm::SmallVector<Type *, 4> ArgTypes;
217 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
218 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
219 ArgTypes.push_back(ShadowTy);
221 ArgTypes.push_back(ShadowPtrTy);
222 Type *RetType = T->getReturnType();
223 if (!RetType->isVoidTy())
224 RetType = StructType::get(RetType, ShadowTy, (Type *)0);
225 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
228 bool DataFlowSanitizer::doInitialization(Module &M) {
229 DL = getAnalysisIfAvailable<DataLayout>();
234 Ctx = &M.getContext();
235 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
236 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
237 IntptrTy = DL->getIntPtrType(*Ctx);
238 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
239 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
240 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
242 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
244 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
245 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
247 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
250 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
252 GetArgTLS = ConstantExpr::getIntToPtr(
253 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
254 PointerType::getUnqual(
255 FunctionType::get(PointerType::getUnqual(ArgTLSTy), (Type *)0)));
257 if (GetRetvalTLSPtr) {
259 GetRetvalTLS = ConstantExpr::getIntToPtr(
260 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
261 PointerType::getUnqual(
262 FunctionType::get(PointerType::getUnqual(ShadowTy), (Type *)0)));
265 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
269 DataFlowSanitizer::InstrumentedABI
270 DataFlowSanitizer::getInstrumentedABI(Function *F) {
271 if (Greylist.isIn(*F))
274 return getDefaultInstrumentedABI();
277 DataFlowSanitizer::InstrumentedABI
278 DataFlowSanitizer::getDefaultInstrumentedABI() {
279 return ClArgsABI ? IA_Args : IA_TLS;
282 bool DataFlowSanitizer::runOnModule(Module &M) {
287 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
288 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
289 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
290 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
292 if (!GetRetvalTLSPtr) {
293 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
294 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
295 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
298 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
299 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
300 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
301 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
302 F->addAttribute(1, Attribute::ZExt);
303 F->addAttribute(2, Attribute::ZExt);
306 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
307 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
308 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
311 std::vector<Function *> FnsToInstrument;
312 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
313 if (!i->isIntrinsic() && i != DFSanUnionFn && i != DFSanUnionLoadFn)
314 FnsToInstrument.push_back(&*i);
317 // First, change the ABI of every function in the module. Greylisted
318 // functions keep their original ABI and get a wrapper function.
319 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
320 e = FnsToInstrument.end();
324 FunctionType *FT = F.getFunctionType();
325 FunctionType *NewFT = getInstrumentedFunctionType(FT);
326 // If the function types are the same (i.e. void()), we don't need to do
329 switch (getInstrumentedABI(&F)) {
331 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
332 NewF->setCallingConv(F.getCallingConv());
333 NewF->setAttributes(F.getAttributes().removeAttributes(
334 *Ctx, AttributeSet::ReturnIndex,
335 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
336 AttributeSet::ReturnIndex)));
337 for (Function::arg_iterator FArg = F.arg_begin(),
338 NewFArg = NewF->arg_begin(),
339 FArgEnd = F.arg_end();
340 FArg != FArgEnd; ++FArg, ++NewFArg) {
341 FArg->replaceAllUsesWith(NewFArg);
343 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
345 for (Function::use_iterator ui = F.use_begin(), ue = F.use_end();
347 BlockAddress *BA = dyn_cast<BlockAddress>(ui.getUse().getUser());
350 BA->replaceAllUsesWith(
351 BlockAddress::get(NewF, BA->getBasicBlock()));
355 F.replaceAllUsesWith(
356 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
363 assert(!FT->isVarArg() && "varargs not handled here yet");
364 assert(getDefaultInstrumentedABI() == IA_Args);
366 Function::Create(NewFT, GlobalValue::LinkOnceODRLinkage,
367 std::string("dfsw$") + F.getName(), &M);
368 NewF->setCallingConv(F.getCallingConv());
369 NewF->setAttributes(F.getAttributes());
371 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
372 std::vector<Value *> Args;
373 unsigned n = FT->getNumParams();
374 for (Function::arg_iterator i = NewF->arg_begin(); n != 0; ++i, --n)
376 CallInst *CI = CallInst::Create(&F, Args, "", BB);
377 if (FT->getReturnType()->isVoidTy())
378 ReturnInst::Create(*Ctx, BB);
380 Value *InsVal = InsertValueInst::Create(
381 UndefValue::get(NewFT->getReturnType()), CI, 0, "", BB);
383 InsertValueInst::Create(InsVal, ZeroShadow, 1, "", BB);
384 ReturnInst::Create(*Ctx, InsShadow, BB);
387 Value *WrappedFnCst =
388 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
389 F.replaceAllUsesWith(WrappedFnCst);
390 UnwrappedFnMap[WrappedFnCst] = &F;
399 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
400 e = FnsToInstrument.end();
402 if ((*i)->isDeclaration())
405 DFSanFunction DFSF(*this, *i);
407 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
408 // Build a copy of the list before iterating over it.
409 llvm::SmallVector<BasicBlock *, 4> BBList;
410 std::copy(df_begin(&(*i)->getEntryBlock()), df_end(&(*i)->getEntryBlock()),
411 std::back_inserter(BBList));
413 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
416 Instruction *Inst = &(*i)->front();
418 // DFSanVisitor may split the current basic block, changing the current
419 // instruction's next pointer and moving the next instruction to the
420 // tail block from which we should continue.
421 Instruction *Next = Inst->getNextNode();
422 if (!DFSF.SkipInsts.count(Inst))
423 DFSanVisitor(DFSF).visit(Inst);
424 if (isa<TerminatorInst>(Inst))
430 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
431 i = DFSF.PHIFixups.begin(),
432 e = DFSF.PHIFixups.end();
434 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
436 i->second->setIncomingValue(
437 val, DFSF.getShadow(i->first->getIncomingValue(val)));
445 Value *DFSanFunction::getArgTLSPtr() {
449 return ArgTLSPtr = DFS.ArgTLS;
451 IRBuilder<> IRB(F->getEntryBlock().begin());
452 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
455 Value *DFSanFunction::getRetvalTLS() {
459 return RetvalTLSPtr = DFS.RetvalTLS;
461 IRBuilder<> IRB(F->getEntryBlock().begin());
462 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
465 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
466 IRBuilder<> IRB(Pos);
467 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
470 Value *DFSanFunction::getShadow(Value *V) {
471 if (!isa<Argument>(V) && !isa<Instruction>(V))
472 return DFS.ZeroShadow;
473 Value *&Shadow = ValShadowMap[V];
475 if (Argument *A = dyn_cast<Argument>(V)) {
477 case DataFlowSanitizer::IA_TLS: {
478 Value *ArgTLSPtr = getArgTLSPtr();
479 Instruction *ArgTLSPos =
480 DFS.ArgTLS ? &*F->getEntryBlock().begin()
481 : cast<Instruction>(ArgTLSPtr)->getNextNode();
482 IRBuilder<> IRB(ArgTLSPos);
483 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
486 case DataFlowSanitizer::IA_Args: {
487 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
488 Function::arg_iterator i = F->arg_begin();
495 Shadow = DFS.ZeroShadow;
499 Shadow = DFS.ZeroShadow;
505 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
506 assert(!ValShadowMap.count(I));
507 assert(Shadow->getType() == DFS.ShadowTy);
508 ValShadowMap[I] = Shadow;
511 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
512 assert(Addr != RetvalTLS && "Reinstrumenting?");
513 IRBuilder<> IRB(Pos);
514 return IRB.CreateIntToPtr(
516 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
521 // Generates IR to compute the union of the two given shadows, inserting it
522 // before Pos. Returns the computed union Value.
523 Value *DataFlowSanitizer::combineShadows(Value *V1, Value *V2,
525 if (V1 == ZeroShadow)
527 if (V2 == ZeroShadow)
531 IRBuilder<> IRB(Pos);
532 BasicBlock *Head = Pos->getParent();
533 Value *Ne = IRB.CreateICmpNE(V1, V2);
534 Instruction *NeInst = dyn_cast<Instruction>(Ne);
536 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
537 NeInst, /*Unreachable=*/ false, ColdCallWeights));
538 IRBuilder<> ThenIRB(BI);
539 CallInst *Call = ThenIRB.CreateCall2(DFSanUnionFn, V1, V2);
540 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
541 Call->addAttribute(1, Attribute::ZExt);
542 Call->addAttribute(2, Attribute::ZExt);
544 BasicBlock *Tail = BI->getSuccessor(0);
545 PHINode *Phi = PHINode::Create(ShadowTy, 2, "", Tail->begin());
546 Phi->addIncoming(Call, Call->getParent());
547 Phi->addIncoming(ZeroShadow, Head);
556 // A convenience function which folds the shadows of each of the operands
557 // of the provided instruction Inst, inserting the IR before Inst. Returns
558 // the computed union Value.
559 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
560 if (Inst->getNumOperands() == 0)
561 return DFS.ZeroShadow;
563 Value *Shadow = getShadow(Inst->getOperand(0));
564 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
565 Shadow = DFS.combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
570 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
571 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
572 DFSF.setShadow(&I, CombinedShadow);
575 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
576 // Addr has alignment Align, and take the union of each of those shadows.
577 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
579 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
580 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
581 AllocaShadowMap.find(AI);
582 if (i != AllocaShadowMap.end()) {
583 IRBuilder<> IRB(Pos);
584 return IRB.CreateLoad(i->second);
588 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
589 SmallVector<Value *, 2> Objs;
590 GetUnderlyingObjects(Addr, Objs, DFS.DL);
591 bool AllConstants = true;
592 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
594 if (isa<Function>(*i) || isa<BlockAddress>(*i))
596 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
599 AllConstants = false;
603 return DFS.ZeroShadow;
605 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
608 return DFS.ZeroShadow;
610 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
611 LI->setAlignment(ShadowAlign);
615 IRBuilder<> IRB(Pos);
617 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
618 return DFS.combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
619 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign),
623 if (Size % (64 / DFS.ShadowWidth) == 0) {
624 // Fast path for the common case where each byte has identical shadow: load
625 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
626 // shadow is non-equal.
627 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
628 IRBuilder<> FallbackIRB(FallbackBB);
629 CallInst *FallbackCall = FallbackIRB.CreateCall2(
630 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
631 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
633 // Compare each of the shadows stored in the loaded 64 bits to each other,
634 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
635 IRBuilder<> IRB(Pos);
637 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
638 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
639 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
640 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
641 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
642 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
643 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
645 BasicBlock *Head = Pos->getParent();
646 BasicBlock *Tail = Head->splitBasicBlock(Pos);
647 // In the following code LastBr will refer to the previous basic block's
648 // conditional branch instruction, whose true successor is fixed up to point
649 // to the next block during the loop below or to the tail after the final
651 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
652 ReplaceInstWithInst(Head->getTerminator(), LastBr);
654 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
655 Ofs += 64 / DFS.ShadowWidth) {
656 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
657 IRBuilder<> NextIRB(NextBB);
658 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
659 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
660 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
661 LastBr->setSuccessor(0, NextBB);
662 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
665 LastBr->setSuccessor(0, Tail);
666 FallbackIRB.CreateBr(Tail);
667 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
668 Shadow->addIncoming(FallbackCall, FallbackBB);
669 Shadow->addIncoming(TruncShadow, LastBr->getParent());
673 IRBuilder<> IRB(Pos);
674 CallInst *FallbackCall = IRB.CreateCall2(
675 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
676 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
680 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
681 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
683 if (ClPreserveAlignment) {
684 Align = LI.getAlignment();
686 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
690 IRBuilder<> IRB(&LI);
691 Value *LoadedShadow =
692 DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
693 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
694 DFSF.setShadow(&LI, DFSF.DFS.combineShadows(LoadedShadow, PtrShadow, &LI));
697 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
698 Value *Shadow, Instruction *Pos) {
699 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
700 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
701 AllocaShadowMap.find(AI);
702 if (i != AllocaShadowMap.end()) {
703 IRBuilder<> IRB(Pos);
704 IRB.CreateStore(Shadow, i->second);
709 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
710 IRBuilder<> IRB(Pos);
711 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
712 if (Shadow == DFS.ZeroShadow) {
713 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
714 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
715 Value *ExtShadowAddr =
716 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
717 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
721 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
723 if (Size >= ShadowVecSize) {
724 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
725 Value *ShadowVec = UndefValue::get(ShadowVecTy);
726 for (unsigned i = 0; i != ShadowVecSize; ++i) {
727 ShadowVec = IRB.CreateInsertElement(
728 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
730 Value *ShadowVecAddr =
731 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
733 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
734 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
735 Size -= ShadowVecSize;
737 } while (Size >= ShadowVecSize);
738 Offset *= ShadowVecSize;
741 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
742 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
748 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
750 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
752 if (ClPreserveAlignment) {
753 Align = SI.getAlignment();
755 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
759 DFSF.storeShadow(SI.getPointerOperand(), Size, Align,
760 DFSF.getShadow(SI.getValueOperand()), &SI);
763 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
764 visitOperandShadowInst(BO);
767 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
769 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
771 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
772 visitOperandShadowInst(GEPI);
775 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
776 visitOperandShadowInst(I);
779 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
780 visitOperandShadowInst(I);
783 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
784 visitOperandShadowInst(I);
787 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
788 visitOperandShadowInst(I);
791 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
792 visitOperandShadowInst(I);
795 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
796 bool AllLoadsStores = true;
797 for (Instruction::use_iterator i = I.use_begin(), e = I.use_end(); i != e;
799 if (isa<LoadInst>(*i))
802 if (StoreInst *SI = dyn_cast<StoreInst>(*i)) {
803 if (SI->getPointerOperand() == &I)
807 AllLoadsStores = false;
810 if (AllLoadsStores) {
812 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
814 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
817 void DFSanVisitor::visitSelectInst(SelectInst &I) {
818 Value *CondShadow = DFSF.getShadow(I.getCondition());
819 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
820 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
822 if (isa<VectorType>(I.getCondition()->getType())) {
824 &I, DFSF.DFS.combineShadows(
826 DFSF.DFS.combineShadows(TrueShadow, FalseShadow, &I), &I));
829 if (TrueShadow == FalseShadow) {
830 ShadowSel = TrueShadow;
833 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
835 DFSF.setShadow(&I, DFSF.DFS.combineShadows(CondShadow, ShadowSel, &I));
839 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
841 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
842 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
843 Value *LenShadow = IRB.CreateMul(
845 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
847 if (ClPreserveAlignment) {
848 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
849 ConstantInt::get(I.getAlignmentCst()->getType(),
850 DFSF.DFS.ShadowWidth / 8));
852 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
853 DFSF.DFS.ShadowWidth / 8);
855 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
856 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
857 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
858 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
859 AlignShadow, I.getVolatileCst());
862 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
863 if (RI.getReturnValue()) {
865 case DataFlowSanitizer::IA_TLS: {
866 Value *S = DFSF.getShadow(RI.getReturnValue());
867 IRBuilder<> IRB(&RI);
868 IRB.CreateStore(S, DFSF.getRetvalTLS());
871 case DataFlowSanitizer::IA_Args: {
872 IRBuilder<> IRB(&RI);
873 Type *RT = DFSF.F->getFunctionType()->getReturnType();
875 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
877 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
878 RI.setOperand(0, InsShadow);
887 void DFSanVisitor::visitCallSite(CallSite CS) {
888 Function *F = CS.getCalledFunction();
889 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
890 visitOperandShadowInst(*CS.getInstruction());
894 DenseMap<Value *, Function *>::iterator i =
895 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
896 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
897 CS.setCalledFunction(i->second);
898 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
902 IRBuilder<> IRB(CS.getInstruction());
904 FunctionType *FT = cast<FunctionType>(
905 CS.getCalledValue()->getType()->getPointerElementType());
906 if (DFSF.DFS.getDefaultInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
907 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
908 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
909 DFSF.getArgTLS(i, CS.getInstruction()));
913 Instruction *Next = 0;
914 if (!CS.getType()->isVoidTy()) {
915 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
916 if (II->getNormalDest()->getSinglePredecessor()) {
917 Next = II->getNormalDest()->begin();
920 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
921 Next = NewBB->begin();
924 Next = CS->getNextNode();
927 if (DFSF.DFS.getDefaultInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
928 IRBuilder<> NextIRB(Next);
929 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
930 DFSF.SkipInsts.insert(LI);
931 DFSF.setShadow(CS.getInstruction(), LI);
935 // Do all instrumentation for IA_Args down here to defer tampering with the
936 // CFG in a way that SplitEdge may be able to detect.
937 if (DFSF.DFS.getDefaultInstrumentedABI() == DataFlowSanitizer::IA_Args) {
938 FunctionType *NewFT = DFSF.DFS.getInstrumentedFunctionType(FT);
940 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
941 std::vector<Value *> Args;
943 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
944 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
948 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
949 Args.push_back(DFSF.getShadow(*i));
951 if (FT->isVarArg()) {
952 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
953 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
954 AllocaInst *VarArgShadow =
955 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
956 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
957 for (unsigned n = 0; i != e; ++i, ++n) {
958 IRB.CreateStore(DFSF.getShadow(*i),
959 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
965 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
966 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
969 NewCS = IRB.CreateCall(Func, Args);
971 NewCS.setCallingConv(CS.getCallingConv());
972 NewCS.setAttributes(CS.getAttributes().removeAttributes(
973 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
974 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
975 AttributeSet::ReturnIndex)));
978 ExtractValueInst *ExVal =
979 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
980 DFSF.SkipInsts.insert(ExVal);
981 ExtractValueInst *ExShadow =
982 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
983 DFSF.SkipInsts.insert(ExShadow);
984 DFSF.setShadow(ExVal, ExShadow);
986 CS.getInstruction()->replaceAllUsesWith(ExVal);
989 CS.getInstruction()->eraseFromParent();
993 void DFSanVisitor::visitPHINode(PHINode &PN) {
995 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
997 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
998 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
999 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1001 ShadowPN->addIncoming(UndefShadow, *i);
1004 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1005 DFSF.setShadow(&PN, ShadowPN);