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/Local.h"
63 #include "llvm/Transforms/Utils/SpecialCaseList.h"
68 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
69 // alignment requirements provided by the input IR are correct. For example,
70 // if the input IR contains a load with alignment 8, this flag will cause
71 // the shadow load to have alignment 16. This flag is disabled by default as
72 // we have unfortunately encountered too much code (including Clang itself;
73 // see PR14291) which performs misaligned access.
74 static cl::opt<bool> ClPreserveAlignment(
75 "dfsan-preserve-alignment",
76 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
79 // The greylist file controls how shadow parameters are passed.
80 // The program acts as though every function in the greylist is passed
81 // parameters with zero shadow and that its return value also has zero shadow.
82 // This avoids the use of TLS or extra function parameters to pass shadow state
83 // and essentially makes the function conform to the "native" (i.e. unsanitized)
85 static cl::opt<std::string> ClGreylistFile(
87 cl::desc("File containing the list of functions with a native ABI"),
90 static cl::opt<bool> ClArgsABI(
92 cl::desc("Use the argument ABI rather than the TLS ABI"),
97 class DataFlowSanitizer : public ModulePass {
98 friend struct DFSanFunction;
99 friend class DFSanVisitor;
105 enum InstrumentedABI {
115 IntegerType *ShadowTy;
116 PointerType *ShadowPtrTy;
117 IntegerType *IntptrTy;
118 ConstantInt *ZeroShadow;
119 ConstantInt *ShadowPtrMask;
120 ConstantInt *ShadowPtrMul;
123 void *(*GetArgTLSPtr)();
124 void *(*GetRetvalTLSPtr)();
126 Constant *GetRetvalTLS;
127 FunctionType *DFSanUnionFnTy;
128 FunctionType *DFSanUnionLoadFnTy;
129 Constant *DFSanUnionFn;
130 Constant *DFSanUnionLoadFn;
131 MDNode *ColdCallWeights;
132 OwningPtr<SpecialCaseList> Greylist;
133 DenseMap<Value *, Function *> UnwrappedFnMap;
135 Value *getShadowAddress(Value *Addr, Instruction *Pos);
136 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
137 FunctionType *getInstrumentedFunctionType(FunctionType *T);
138 InstrumentedABI getInstrumentedABI(Function *F);
139 InstrumentedABI getDefaultInstrumentedABI();
142 DataFlowSanitizer(void *(*getArgTLS)() = 0, void *(*getRetValTLS)() = 0);
144 bool doInitialization(Module &M);
145 bool runOnModule(Module &M);
148 struct DFSanFunction {
149 DataFlowSanitizer &DFS;
151 DataFlowSanitizer::InstrumentedABI IA;
154 DenseMap<Value *, Value *> ValShadowMap;
155 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
156 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
157 DenseSet<Instruction *> SkipInsts;
159 DFSanFunction(DataFlowSanitizer &DFS, Function *F)
160 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI(F)), ArgTLSPtr(0),
162 Value *getArgTLSPtr();
163 Value *getArgTLS(unsigned Index, Instruction *Pos);
164 Value *getRetvalTLS();
165 Value *getShadow(Value *V);
166 void setShadow(Instruction *I, Value *Shadow);
167 Value *combineOperandShadows(Instruction *Inst);
168 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
170 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
174 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
177 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
179 void visitOperandShadowInst(Instruction &I);
181 void visitBinaryOperator(BinaryOperator &BO);
182 void visitCastInst(CastInst &CI);
183 void visitCmpInst(CmpInst &CI);
184 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
185 void visitLoadInst(LoadInst &LI);
186 void visitStoreInst(StoreInst &SI);
187 void visitReturnInst(ReturnInst &RI);
188 void visitCallSite(CallSite CS);
189 void visitPHINode(PHINode &PN);
190 void visitExtractElementInst(ExtractElementInst &I);
191 void visitInsertElementInst(InsertElementInst &I);
192 void visitShuffleVectorInst(ShuffleVectorInst &I);
193 void visitExtractValueInst(ExtractValueInst &I);
194 void visitInsertValueInst(InsertValueInst &I);
195 void visitAllocaInst(AllocaInst &I);
196 void visitSelectInst(SelectInst &I);
197 void visitMemTransferInst(MemTransferInst &I);
202 char DataFlowSanitizer::ID;
203 INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
204 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
206 ModulePass *llvm::createDataFlowSanitizerPass(void *(*getArgTLS)(),
207 void *(*getRetValTLS)()) {
208 return new DataFlowSanitizer(getArgTLS, getRetValTLS);
211 DataFlowSanitizer::DataFlowSanitizer(void *(*getArgTLS)(),
212 void *(*getRetValTLS)())
213 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
214 Greylist(SpecialCaseList::createOrDie(ClGreylistFile)) {}
216 FunctionType *DataFlowSanitizer::getInstrumentedFunctionType(FunctionType *T) {
217 llvm::SmallVector<Type *, 4> ArgTypes;
218 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
219 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
220 ArgTypes.push_back(ShadowTy);
222 ArgTypes.push_back(ShadowPtrTy);
223 Type *RetType = T->getReturnType();
224 if (!RetType->isVoidTy())
225 RetType = StructType::get(RetType, ShadowTy, (Type *)0);
226 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
229 bool DataFlowSanitizer::doInitialization(Module &M) {
230 DL = getAnalysisIfAvailable<DataLayout>();
235 Ctx = &M.getContext();
236 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
237 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
238 IntptrTy = DL->getIntPtrType(*Ctx);
239 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
240 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
241 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
243 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
245 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
246 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
248 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
251 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
253 GetArgTLS = ConstantExpr::getIntToPtr(
254 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
255 PointerType::getUnqual(
256 FunctionType::get(PointerType::getUnqual(ArgTLSTy), (Type *)0)));
258 if (GetRetvalTLSPtr) {
260 GetRetvalTLS = ConstantExpr::getIntToPtr(
261 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
262 PointerType::getUnqual(
263 FunctionType::get(PointerType::getUnqual(ShadowTy), (Type *)0)));
266 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
270 DataFlowSanitizer::InstrumentedABI
271 DataFlowSanitizer::getInstrumentedABI(Function *F) {
272 if (Greylist->isIn(*F))
275 return getDefaultInstrumentedABI();
278 DataFlowSanitizer::InstrumentedABI
279 DataFlowSanitizer::getDefaultInstrumentedABI() {
280 return ClArgsABI ? IA_Args : IA_TLS;
283 bool DataFlowSanitizer::runOnModule(Module &M) {
288 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
289 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
290 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
291 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
293 if (!GetRetvalTLSPtr) {
294 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
295 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
296 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
299 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
300 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
301 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
302 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
303 F->addAttribute(1, Attribute::ZExt);
304 F->addAttribute(2, Attribute::ZExt);
307 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
308 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
309 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
312 std::vector<Function *> FnsToInstrument;
313 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
314 if (!i->isIntrinsic() && i != DFSanUnionFn && i != DFSanUnionLoadFn)
315 FnsToInstrument.push_back(&*i);
318 // First, change the ABI of every function in the module. Greylisted
319 // functions keep their original ABI and get a wrapper function.
320 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
321 e = FnsToInstrument.end();
325 FunctionType *FT = F.getFunctionType();
326 FunctionType *NewFT = getInstrumentedFunctionType(FT);
327 // If the function types are the same (i.e. void()), we don't need to do
330 switch (getInstrumentedABI(&F)) {
332 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
333 NewF->setCallingConv(F.getCallingConv());
334 NewF->setAttributes(F.getAttributes().removeAttributes(
335 *Ctx, AttributeSet::ReturnIndex,
336 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
337 AttributeSet::ReturnIndex)));
338 for (Function::arg_iterator FArg = F.arg_begin(),
339 NewFArg = NewF->arg_begin(),
340 FArgEnd = F.arg_end();
341 FArg != FArgEnd; ++FArg, ++NewFArg) {
342 FArg->replaceAllUsesWith(NewFArg);
344 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
346 for (Function::use_iterator ui = F.use_begin(), ue = F.use_end();
348 BlockAddress *BA = dyn_cast<BlockAddress>(ui.getUse().getUser());
351 BA->replaceAllUsesWith(
352 BlockAddress::get(NewF, BA->getBasicBlock()));
356 F.replaceAllUsesWith(
357 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
364 assert(!FT->isVarArg() && "varargs not handled here yet");
365 assert(getDefaultInstrumentedABI() == IA_Args);
367 Function::Create(NewFT, GlobalValue::LinkOnceODRLinkage,
368 std::string("dfsw$") + F.getName(), &M);
369 NewF->setCallingConv(F.getCallingConv());
370 NewF->setAttributes(F.getAttributes());
372 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
373 std::vector<Value *> Args;
374 unsigned n = FT->getNumParams();
375 for (Function::arg_iterator i = NewF->arg_begin(); n != 0; ++i, --n)
377 CallInst *CI = CallInst::Create(&F, Args, "", BB);
378 if (FT->getReturnType()->isVoidTy())
379 ReturnInst::Create(*Ctx, BB);
381 Value *InsVal = InsertValueInst::Create(
382 UndefValue::get(NewFT->getReturnType()), CI, 0, "", BB);
384 InsertValueInst::Create(InsVal, ZeroShadow, 1, "", BB);
385 ReturnInst::Create(*Ctx, InsShadow, BB);
388 Value *WrappedFnCst =
389 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
390 F.replaceAllUsesWith(WrappedFnCst);
391 UnwrappedFnMap[WrappedFnCst] = &F;
400 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
401 e = FnsToInstrument.end();
403 if ((*i)->isDeclaration())
406 removeUnreachableBlocks(**i);
408 DFSanFunction DFSF(*this, *i);
410 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
411 // Build a copy of the list before iterating over it.
412 llvm::SmallVector<BasicBlock *, 4> BBList;
413 std::copy(df_begin(&(*i)->getEntryBlock()), df_end(&(*i)->getEntryBlock()),
414 std::back_inserter(BBList));
416 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
419 Instruction *Inst = &(*i)->front();
421 // DFSanVisitor may split the current basic block, changing the current
422 // instruction's next pointer and moving the next instruction to the
423 // tail block from which we should continue.
424 Instruction *Next = Inst->getNextNode();
425 // DFSanVisitor may delete Inst, so keep track of whether it was a
427 bool IsTerminator = isa<TerminatorInst>(Inst);
428 if (!DFSF.SkipInsts.count(Inst))
429 DFSanVisitor(DFSF).visit(Inst);
436 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
437 i = DFSF.PHIFixups.begin(),
438 e = DFSF.PHIFixups.end();
440 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
442 i->second->setIncomingValue(
443 val, DFSF.getShadow(i->first->getIncomingValue(val)));
451 Value *DFSanFunction::getArgTLSPtr() {
455 return ArgTLSPtr = DFS.ArgTLS;
457 IRBuilder<> IRB(F->getEntryBlock().begin());
458 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
461 Value *DFSanFunction::getRetvalTLS() {
465 return RetvalTLSPtr = DFS.RetvalTLS;
467 IRBuilder<> IRB(F->getEntryBlock().begin());
468 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
471 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
472 IRBuilder<> IRB(Pos);
473 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
476 Value *DFSanFunction::getShadow(Value *V) {
477 if (!isa<Argument>(V) && !isa<Instruction>(V))
478 return DFS.ZeroShadow;
479 Value *&Shadow = ValShadowMap[V];
481 if (Argument *A = dyn_cast<Argument>(V)) {
483 case DataFlowSanitizer::IA_TLS: {
484 Value *ArgTLSPtr = getArgTLSPtr();
485 Instruction *ArgTLSPos =
486 DFS.ArgTLS ? &*F->getEntryBlock().begin()
487 : cast<Instruction>(ArgTLSPtr)->getNextNode();
488 IRBuilder<> IRB(ArgTLSPos);
489 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
492 case DataFlowSanitizer::IA_Args: {
493 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
494 Function::arg_iterator i = F->arg_begin();
501 Shadow = DFS.ZeroShadow;
505 Shadow = DFS.ZeroShadow;
511 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
512 assert(!ValShadowMap.count(I));
513 assert(Shadow->getType() == DFS.ShadowTy);
514 ValShadowMap[I] = Shadow;
517 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
518 assert(Addr != RetvalTLS && "Reinstrumenting?");
519 IRBuilder<> IRB(Pos);
520 return IRB.CreateIntToPtr(
522 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
527 // Generates IR to compute the union of the two given shadows, inserting it
528 // before Pos. Returns the computed union Value.
529 Value *DataFlowSanitizer::combineShadows(Value *V1, Value *V2,
531 if (V1 == ZeroShadow)
533 if (V2 == ZeroShadow)
537 IRBuilder<> IRB(Pos);
538 BasicBlock *Head = Pos->getParent();
539 Value *Ne = IRB.CreateICmpNE(V1, V2);
540 Instruction *NeInst = dyn_cast<Instruction>(Ne);
542 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
543 NeInst, /*Unreachable=*/ false, ColdCallWeights));
544 IRBuilder<> ThenIRB(BI);
545 CallInst *Call = ThenIRB.CreateCall2(DFSanUnionFn, V1, V2);
546 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
547 Call->addAttribute(1, Attribute::ZExt);
548 Call->addAttribute(2, Attribute::ZExt);
550 BasicBlock *Tail = BI->getSuccessor(0);
551 PHINode *Phi = PHINode::Create(ShadowTy, 2, "", Tail->begin());
552 Phi->addIncoming(Call, Call->getParent());
553 Phi->addIncoming(ZeroShadow, Head);
562 // A convenience function which folds the shadows of each of the operands
563 // of the provided instruction Inst, inserting the IR before Inst. Returns
564 // the computed union Value.
565 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
566 if (Inst->getNumOperands() == 0)
567 return DFS.ZeroShadow;
569 Value *Shadow = getShadow(Inst->getOperand(0));
570 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
571 Shadow = DFS.combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
576 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
577 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
578 DFSF.setShadow(&I, CombinedShadow);
581 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
582 // Addr has alignment Align, and take the union of each of those shadows.
583 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
585 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
586 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
587 AllocaShadowMap.find(AI);
588 if (i != AllocaShadowMap.end()) {
589 IRBuilder<> IRB(Pos);
590 return IRB.CreateLoad(i->second);
594 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
595 SmallVector<Value *, 2> Objs;
596 GetUnderlyingObjects(Addr, Objs, DFS.DL);
597 bool AllConstants = true;
598 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
600 if (isa<Function>(*i) || isa<BlockAddress>(*i))
602 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
605 AllConstants = false;
609 return DFS.ZeroShadow;
611 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
614 return DFS.ZeroShadow;
616 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
617 LI->setAlignment(ShadowAlign);
621 IRBuilder<> IRB(Pos);
623 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
624 return DFS.combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
625 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign),
629 if (Size % (64 / DFS.ShadowWidth) == 0) {
630 // Fast path for the common case where each byte has identical shadow: load
631 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
632 // shadow is non-equal.
633 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
634 IRBuilder<> FallbackIRB(FallbackBB);
635 CallInst *FallbackCall = FallbackIRB.CreateCall2(
636 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
637 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
639 // Compare each of the shadows stored in the loaded 64 bits to each other,
640 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
641 IRBuilder<> IRB(Pos);
643 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
644 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
645 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
646 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
647 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
648 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
649 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
651 BasicBlock *Head = Pos->getParent();
652 BasicBlock *Tail = Head->splitBasicBlock(Pos);
653 // In the following code LastBr will refer to the previous basic block's
654 // conditional branch instruction, whose true successor is fixed up to point
655 // to the next block during the loop below or to the tail after the final
657 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
658 ReplaceInstWithInst(Head->getTerminator(), LastBr);
660 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
661 Ofs += 64 / DFS.ShadowWidth) {
662 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
663 IRBuilder<> NextIRB(NextBB);
664 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
665 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
666 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
667 LastBr->setSuccessor(0, NextBB);
668 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
671 LastBr->setSuccessor(0, Tail);
672 FallbackIRB.CreateBr(Tail);
673 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
674 Shadow->addIncoming(FallbackCall, FallbackBB);
675 Shadow->addIncoming(TruncShadow, LastBr->getParent());
679 IRBuilder<> IRB(Pos);
680 CallInst *FallbackCall = IRB.CreateCall2(
681 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
682 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
686 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
687 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
689 if (ClPreserveAlignment) {
690 Align = LI.getAlignment();
692 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
696 IRBuilder<> IRB(&LI);
697 Value *LoadedShadow =
698 DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
699 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
700 DFSF.setShadow(&LI, DFSF.DFS.combineShadows(LoadedShadow, PtrShadow, &LI));
703 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
704 Value *Shadow, Instruction *Pos) {
705 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
706 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
707 AllocaShadowMap.find(AI);
708 if (i != AllocaShadowMap.end()) {
709 IRBuilder<> IRB(Pos);
710 IRB.CreateStore(Shadow, i->second);
715 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
716 IRBuilder<> IRB(Pos);
717 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
718 if (Shadow == DFS.ZeroShadow) {
719 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
720 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
721 Value *ExtShadowAddr =
722 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
723 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
727 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
729 if (Size >= ShadowVecSize) {
730 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
731 Value *ShadowVec = UndefValue::get(ShadowVecTy);
732 for (unsigned i = 0; i != ShadowVecSize; ++i) {
733 ShadowVec = IRB.CreateInsertElement(
734 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
736 Value *ShadowVecAddr =
737 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
739 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
740 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
741 Size -= ShadowVecSize;
743 } while (Size >= ShadowVecSize);
744 Offset *= ShadowVecSize;
747 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
748 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
754 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
756 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
758 if (ClPreserveAlignment) {
759 Align = SI.getAlignment();
761 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
765 DFSF.storeShadow(SI.getPointerOperand(), Size, Align,
766 DFSF.getShadow(SI.getValueOperand()), &SI);
769 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
770 visitOperandShadowInst(BO);
773 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
775 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
777 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
778 visitOperandShadowInst(GEPI);
781 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
782 visitOperandShadowInst(I);
785 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
786 visitOperandShadowInst(I);
789 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
790 visitOperandShadowInst(I);
793 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
794 visitOperandShadowInst(I);
797 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
798 visitOperandShadowInst(I);
801 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
802 bool AllLoadsStores = true;
803 for (Instruction::use_iterator i = I.use_begin(), e = I.use_end(); i != e;
805 if (isa<LoadInst>(*i))
808 if (StoreInst *SI = dyn_cast<StoreInst>(*i)) {
809 if (SI->getPointerOperand() == &I)
813 AllLoadsStores = false;
816 if (AllLoadsStores) {
818 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
820 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
823 void DFSanVisitor::visitSelectInst(SelectInst &I) {
824 Value *CondShadow = DFSF.getShadow(I.getCondition());
825 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
826 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
828 if (isa<VectorType>(I.getCondition()->getType())) {
830 &I, DFSF.DFS.combineShadows(
832 DFSF.DFS.combineShadows(TrueShadow, FalseShadow, &I), &I));
835 if (TrueShadow == FalseShadow) {
836 ShadowSel = TrueShadow;
839 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
841 DFSF.setShadow(&I, DFSF.DFS.combineShadows(CondShadow, ShadowSel, &I));
845 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
847 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
848 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
849 Value *LenShadow = IRB.CreateMul(
851 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
853 if (ClPreserveAlignment) {
854 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
855 ConstantInt::get(I.getAlignmentCst()->getType(),
856 DFSF.DFS.ShadowWidth / 8));
858 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
859 DFSF.DFS.ShadowWidth / 8);
861 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
862 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
863 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
864 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
865 AlignShadow, I.getVolatileCst());
868 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
869 if (RI.getReturnValue()) {
871 case DataFlowSanitizer::IA_TLS: {
872 Value *S = DFSF.getShadow(RI.getReturnValue());
873 IRBuilder<> IRB(&RI);
874 IRB.CreateStore(S, DFSF.getRetvalTLS());
877 case DataFlowSanitizer::IA_Args: {
878 IRBuilder<> IRB(&RI);
879 Type *RT = DFSF.F->getFunctionType()->getReturnType();
881 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
883 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
884 RI.setOperand(0, InsShadow);
893 void DFSanVisitor::visitCallSite(CallSite CS) {
894 Function *F = CS.getCalledFunction();
895 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
896 visitOperandShadowInst(*CS.getInstruction());
900 DenseMap<Value *, Function *>::iterator i =
901 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
902 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
903 CS.setCalledFunction(i->second);
904 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
908 IRBuilder<> IRB(CS.getInstruction());
910 FunctionType *FT = cast<FunctionType>(
911 CS.getCalledValue()->getType()->getPointerElementType());
912 if (DFSF.DFS.getDefaultInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
913 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
914 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
915 DFSF.getArgTLS(i, CS.getInstruction()));
919 Instruction *Next = 0;
920 if (!CS.getType()->isVoidTy()) {
921 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
922 if (II->getNormalDest()->getSinglePredecessor()) {
923 Next = II->getNormalDest()->begin();
926 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
927 Next = NewBB->begin();
930 Next = CS->getNextNode();
933 if (DFSF.DFS.getDefaultInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
934 IRBuilder<> NextIRB(Next);
935 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
936 DFSF.SkipInsts.insert(LI);
937 DFSF.setShadow(CS.getInstruction(), LI);
941 // Do all instrumentation for IA_Args down here to defer tampering with the
942 // CFG in a way that SplitEdge may be able to detect.
943 if (DFSF.DFS.getDefaultInstrumentedABI() == DataFlowSanitizer::IA_Args) {
944 FunctionType *NewFT = DFSF.DFS.getInstrumentedFunctionType(FT);
946 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
947 std::vector<Value *> Args;
949 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
950 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
954 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
955 Args.push_back(DFSF.getShadow(*i));
957 if (FT->isVarArg()) {
958 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
959 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
960 AllocaInst *VarArgShadow =
961 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
962 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
963 for (unsigned n = 0; i != e; ++i, ++n) {
964 IRB.CreateStore(DFSF.getShadow(*i),
965 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
971 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
972 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
975 NewCS = IRB.CreateCall(Func, Args);
977 NewCS.setCallingConv(CS.getCallingConv());
978 NewCS.setAttributes(CS.getAttributes().removeAttributes(
979 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
980 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
981 AttributeSet::ReturnIndex)));
984 ExtractValueInst *ExVal =
985 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
986 DFSF.SkipInsts.insert(ExVal);
987 ExtractValueInst *ExShadow =
988 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
989 DFSF.SkipInsts.insert(ExShadow);
990 DFSF.setShadow(ExVal, ExShadow);
992 CS.getInstruction()->replaceAllUsesWith(ExVal);
995 CS.getInstruction()->eraseFromParent();
999 void DFSanVisitor::visitPHINode(PHINode &PN) {
1001 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1003 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1004 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1005 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1007 ShadowPN->addIncoming(UndefShadow, *i);
1010 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1011 DFSF.setShadow(&PN, ShadowPN);