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 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(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 if (!DFSF.SkipInsts.count(Inst))
426 DFSanVisitor(DFSF).visit(Inst);
427 if (isa<TerminatorInst>(Inst))
433 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
434 i = DFSF.PHIFixups.begin(),
435 e = DFSF.PHIFixups.end();
437 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
439 i->second->setIncomingValue(
440 val, DFSF.getShadow(i->first->getIncomingValue(val)));
448 Value *DFSanFunction::getArgTLSPtr() {
452 return ArgTLSPtr = DFS.ArgTLS;
454 IRBuilder<> IRB(F->getEntryBlock().begin());
455 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
458 Value *DFSanFunction::getRetvalTLS() {
462 return RetvalTLSPtr = DFS.RetvalTLS;
464 IRBuilder<> IRB(F->getEntryBlock().begin());
465 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
468 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
469 IRBuilder<> IRB(Pos);
470 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
473 Value *DFSanFunction::getShadow(Value *V) {
474 if (!isa<Argument>(V) && !isa<Instruction>(V))
475 return DFS.ZeroShadow;
476 Value *&Shadow = ValShadowMap[V];
478 if (Argument *A = dyn_cast<Argument>(V)) {
480 case DataFlowSanitizer::IA_TLS: {
481 Value *ArgTLSPtr = getArgTLSPtr();
482 Instruction *ArgTLSPos =
483 DFS.ArgTLS ? &*F->getEntryBlock().begin()
484 : cast<Instruction>(ArgTLSPtr)->getNextNode();
485 IRBuilder<> IRB(ArgTLSPos);
486 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
489 case DataFlowSanitizer::IA_Args: {
490 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
491 Function::arg_iterator i = F->arg_begin();
498 Shadow = DFS.ZeroShadow;
502 Shadow = DFS.ZeroShadow;
508 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
509 assert(!ValShadowMap.count(I));
510 assert(Shadow->getType() == DFS.ShadowTy);
511 ValShadowMap[I] = Shadow;
514 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
515 assert(Addr != RetvalTLS && "Reinstrumenting?");
516 IRBuilder<> IRB(Pos);
517 return IRB.CreateIntToPtr(
519 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
524 // Generates IR to compute the union of the two given shadows, inserting it
525 // before Pos. Returns the computed union Value.
526 Value *DataFlowSanitizer::combineShadows(Value *V1, Value *V2,
528 if (V1 == ZeroShadow)
530 if (V2 == ZeroShadow)
534 IRBuilder<> IRB(Pos);
535 BasicBlock *Head = Pos->getParent();
536 Value *Ne = IRB.CreateICmpNE(V1, V2);
537 Instruction *NeInst = dyn_cast<Instruction>(Ne);
539 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
540 NeInst, /*Unreachable=*/ false, ColdCallWeights));
541 IRBuilder<> ThenIRB(BI);
542 CallInst *Call = ThenIRB.CreateCall2(DFSanUnionFn, V1, V2);
543 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
544 Call->addAttribute(1, Attribute::ZExt);
545 Call->addAttribute(2, Attribute::ZExt);
547 BasicBlock *Tail = BI->getSuccessor(0);
548 PHINode *Phi = PHINode::Create(ShadowTy, 2, "", Tail->begin());
549 Phi->addIncoming(Call, Call->getParent());
550 Phi->addIncoming(ZeroShadow, Head);
559 // A convenience function which folds the shadows of each of the operands
560 // of the provided instruction Inst, inserting the IR before Inst. Returns
561 // the computed union Value.
562 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
563 if (Inst->getNumOperands() == 0)
564 return DFS.ZeroShadow;
566 Value *Shadow = getShadow(Inst->getOperand(0));
567 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
568 Shadow = DFS.combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
573 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
574 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
575 DFSF.setShadow(&I, CombinedShadow);
578 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
579 // Addr has alignment Align, and take the union of each of those shadows.
580 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
582 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
583 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
584 AllocaShadowMap.find(AI);
585 if (i != AllocaShadowMap.end()) {
586 IRBuilder<> IRB(Pos);
587 return IRB.CreateLoad(i->second);
591 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
592 SmallVector<Value *, 2> Objs;
593 GetUnderlyingObjects(Addr, Objs, DFS.DL);
594 bool AllConstants = true;
595 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
597 if (isa<Function>(*i) || isa<BlockAddress>(*i))
599 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
602 AllConstants = false;
606 return DFS.ZeroShadow;
608 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
611 return DFS.ZeroShadow;
613 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
614 LI->setAlignment(ShadowAlign);
618 IRBuilder<> IRB(Pos);
620 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
621 return DFS.combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
622 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign),
626 if (Size % (64 / DFS.ShadowWidth) == 0) {
627 // Fast path for the common case where each byte has identical shadow: load
628 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
629 // shadow is non-equal.
630 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
631 IRBuilder<> FallbackIRB(FallbackBB);
632 CallInst *FallbackCall = FallbackIRB.CreateCall2(
633 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
634 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
636 // Compare each of the shadows stored in the loaded 64 bits to each other,
637 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
638 IRBuilder<> IRB(Pos);
640 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
641 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
642 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
643 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
644 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
645 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
646 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
648 BasicBlock *Head = Pos->getParent();
649 BasicBlock *Tail = Head->splitBasicBlock(Pos);
650 // In the following code LastBr will refer to the previous basic block's
651 // conditional branch instruction, whose true successor is fixed up to point
652 // to the next block during the loop below or to the tail after the final
654 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
655 ReplaceInstWithInst(Head->getTerminator(), LastBr);
657 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
658 Ofs += 64 / DFS.ShadowWidth) {
659 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
660 IRBuilder<> NextIRB(NextBB);
661 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
662 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
663 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
664 LastBr->setSuccessor(0, NextBB);
665 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
668 LastBr->setSuccessor(0, Tail);
669 FallbackIRB.CreateBr(Tail);
670 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
671 Shadow->addIncoming(FallbackCall, FallbackBB);
672 Shadow->addIncoming(TruncShadow, LastBr->getParent());
676 IRBuilder<> IRB(Pos);
677 CallInst *FallbackCall = IRB.CreateCall2(
678 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
679 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
683 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
684 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
686 if (ClPreserveAlignment) {
687 Align = LI.getAlignment();
689 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
693 IRBuilder<> IRB(&LI);
694 Value *LoadedShadow =
695 DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
696 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
697 DFSF.setShadow(&LI, DFSF.DFS.combineShadows(LoadedShadow, PtrShadow, &LI));
700 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
701 Value *Shadow, Instruction *Pos) {
702 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
703 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
704 AllocaShadowMap.find(AI);
705 if (i != AllocaShadowMap.end()) {
706 IRBuilder<> IRB(Pos);
707 IRB.CreateStore(Shadow, i->second);
712 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
713 IRBuilder<> IRB(Pos);
714 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
715 if (Shadow == DFS.ZeroShadow) {
716 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
717 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
718 Value *ExtShadowAddr =
719 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
720 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
724 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
726 if (Size >= ShadowVecSize) {
727 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
728 Value *ShadowVec = UndefValue::get(ShadowVecTy);
729 for (unsigned i = 0; i != ShadowVecSize; ++i) {
730 ShadowVec = IRB.CreateInsertElement(
731 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
733 Value *ShadowVecAddr =
734 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
736 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
737 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
738 Size -= ShadowVecSize;
740 } while (Size >= ShadowVecSize);
741 Offset *= ShadowVecSize;
744 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
745 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
751 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
753 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
755 if (ClPreserveAlignment) {
756 Align = SI.getAlignment();
758 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
762 DFSF.storeShadow(SI.getPointerOperand(), Size, Align,
763 DFSF.getShadow(SI.getValueOperand()), &SI);
766 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
767 visitOperandShadowInst(BO);
770 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
772 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
774 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
775 visitOperandShadowInst(GEPI);
778 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
779 visitOperandShadowInst(I);
782 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
783 visitOperandShadowInst(I);
786 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
787 visitOperandShadowInst(I);
790 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
791 visitOperandShadowInst(I);
794 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
795 visitOperandShadowInst(I);
798 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
799 bool AllLoadsStores = true;
800 for (Instruction::use_iterator i = I.use_begin(), e = I.use_end(); i != e;
802 if (isa<LoadInst>(*i))
805 if (StoreInst *SI = dyn_cast<StoreInst>(*i)) {
806 if (SI->getPointerOperand() == &I)
810 AllLoadsStores = false;
813 if (AllLoadsStores) {
815 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
817 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
820 void DFSanVisitor::visitSelectInst(SelectInst &I) {
821 Value *CondShadow = DFSF.getShadow(I.getCondition());
822 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
823 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
825 if (isa<VectorType>(I.getCondition()->getType())) {
827 &I, DFSF.DFS.combineShadows(
829 DFSF.DFS.combineShadows(TrueShadow, FalseShadow, &I), &I));
832 if (TrueShadow == FalseShadow) {
833 ShadowSel = TrueShadow;
836 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
838 DFSF.setShadow(&I, DFSF.DFS.combineShadows(CondShadow, ShadowSel, &I));
842 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
844 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
845 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
846 Value *LenShadow = IRB.CreateMul(
848 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
850 if (ClPreserveAlignment) {
851 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
852 ConstantInt::get(I.getAlignmentCst()->getType(),
853 DFSF.DFS.ShadowWidth / 8));
855 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
856 DFSF.DFS.ShadowWidth / 8);
858 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
859 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
860 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
861 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
862 AlignShadow, I.getVolatileCst());
865 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
866 if (RI.getReturnValue()) {
868 case DataFlowSanitizer::IA_TLS: {
869 Value *S = DFSF.getShadow(RI.getReturnValue());
870 IRBuilder<> IRB(&RI);
871 IRB.CreateStore(S, DFSF.getRetvalTLS());
874 case DataFlowSanitizer::IA_Args: {
875 IRBuilder<> IRB(&RI);
876 Type *RT = DFSF.F->getFunctionType()->getReturnType();
878 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
880 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
881 RI.setOperand(0, InsShadow);
890 void DFSanVisitor::visitCallSite(CallSite CS) {
891 Function *F = CS.getCalledFunction();
892 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
893 visitOperandShadowInst(*CS.getInstruction());
897 DenseMap<Value *, Function *>::iterator i =
898 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
899 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
900 CS.setCalledFunction(i->second);
901 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
905 IRBuilder<> IRB(CS.getInstruction());
907 FunctionType *FT = cast<FunctionType>(
908 CS.getCalledValue()->getType()->getPointerElementType());
909 if (DFSF.DFS.getDefaultInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
910 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
911 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
912 DFSF.getArgTLS(i, CS.getInstruction()));
916 Instruction *Next = 0;
917 if (!CS.getType()->isVoidTy()) {
918 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
919 if (II->getNormalDest()->getSinglePredecessor()) {
920 Next = II->getNormalDest()->begin();
923 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
924 Next = NewBB->begin();
927 Next = CS->getNextNode();
930 if (DFSF.DFS.getDefaultInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
931 IRBuilder<> NextIRB(Next);
932 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
933 DFSF.SkipInsts.insert(LI);
934 DFSF.setShadow(CS.getInstruction(), LI);
938 // Do all instrumentation for IA_Args down here to defer tampering with the
939 // CFG in a way that SplitEdge may be able to detect.
940 if (DFSF.DFS.getDefaultInstrumentedABI() == DataFlowSanitizer::IA_Args) {
941 FunctionType *NewFT = DFSF.DFS.getInstrumentedFunctionType(FT);
943 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
944 std::vector<Value *> Args;
946 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
947 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
951 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
952 Args.push_back(DFSF.getShadow(*i));
954 if (FT->isVarArg()) {
955 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
956 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
957 AllocaInst *VarArgShadow =
958 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
959 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
960 for (unsigned n = 0; i != e; ++i, ++n) {
961 IRB.CreateStore(DFSF.getShadow(*i),
962 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
968 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
969 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
972 NewCS = IRB.CreateCall(Func, Args);
974 NewCS.setCallingConv(CS.getCallingConv());
975 NewCS.setAttributes(CS.getAttributes().removeAttributes(
976 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
977 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
978 AttributeSet::ReturnIndex)));
981 ExtractValueInst *ExVal =
982 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
983 DFSF.SkipInsts.insert(ExVal);
984 ExtractValueInst *ExShadow =
985 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
986 DFSF.SkipInsts.insert(ExShadow);
987 DFSF.setShadow(ExVal, ExShadow);
989 CS.getInstruction()->replaceAllUsesWith(ExVal);
992 CS.getInstruction()->eraseFromParent();
996 void DFSanVisitor::visitPHINode(PHINode &PN) {
998 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1000 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1001 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1002 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1004 ShadowPN->addIncoming(UndefShadow, *i);
1007 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1008 DFSF.setShadow(&PN, ShadowPN);