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 ABI list file controls how shadow parameters are passed. The pass treats
80 // every function labelled "uninstrumented" in the ABI list file as conforming
81 // to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
82 // additional annotations for those functions, a call to one of those functions
83 // will produce a warning message, as the labelling behaviour of the function is
84 // unknown. The other supported annotations are "functional" and "discard",
85 // which are described below under DataFlowSanitizer::WrapperKind.
86 static cl::opt<std::string> ClABIListFile(
88 cl::desc("File listing native ABI functions and how the pass treats them"),
91 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
92 // functions (see DataFlowSanitizer::InstrumentedABI below).
93 static cl::opt<bool> ClArgsABI(
95 cl::desc("Use the argument ABI rather than the TLS ABI"),
98 static cl::opt<bool> ClDebugNonzeroLabels(
99 "dfsan-debug-nonzero-labels",
100 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
101 "load or return with a nonzero label"),
106 class DataFlowSanitizer : public ModulePass {
107 friend struct DFSanFunction;
108 friend class DFSanVisitor;
114 /// Which ABI should be used for instrumented functions?
115 enum InstrumentedABI {
116 /// Argument and return value labels are passed through additional
117 /// arguments and by modifying the return type.
120 /// Argument and return value labels are passed through TLS variables
121 /// __dfsan_arg_tls and __dfsan_retval_tls.
125 /// How should calls to uninstrumented functions be handled?
127 /// This function is present in an uninstrumented form but we don't know
128 /// how it should be handled. Print a warning and call the function anyway.
129 /// Don't label the return value.
132 /// This function does not write to (user-accessible) memory, and its return
133 /// value is unlabelled.
136 /// This function does not write to (user-accessible) memory, and the label
137 /// of its return value is the union of the label of its arguments.
140 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
141 /// where F is the name of the function. This function may wrap the
142 /// original function or provide its own implementation. This is similar to
143 /// the IA_Args ABI, except that IA_Args uses a struct return type to
144 /// pass the return value shadow in a register, while WK_Custom uses an
145 /// extra pointer argument to return the shadow. This allows the wrapped
146 /// form of the function type to be expressed in C.
153 IntegerType *ShadowTy;
154 PointerType *ShadowPtrTy;
155 IntegerType *IntptrTy;
156 ConstantInt *ZeroShadow;
157 ConstantInt *ShadowPtrMask;
158 ConstantInt *ShadowPtrMul;
161 void *(*GetArgTLSPtr)();
162 void *(*GetRetvalTLSPtr)();
164 Constant *GetRetvalTLS;
165 FunctionType *DFSanUnionFnTy;
166 FunctionType *DFSanUnionLoadFnTy;
167 FunctionType *DFSanUnimplementedFnTy;
168 FunctionType *DFSanSetLabelFnTy;
169 FunctionType *DFSanNonzeroLabelFnTy;
170 Constant *DFSanUnionFn;
171 Constant *DFSanUnionLoadFn;
172 Constant *DFSanUnimplementedFn;
173 Constant *DFSanSetLabelFn;
174 Constant *DFSanNonzeroLabelFn;
175 MDNode *ColdCallWeights;
176 OwningPtr<SpecialCaseList> ABIList;
177 DenseMap<Value *, Function *> UnwrappedFnMap;
178 AttributeSet ReadOnlyNoneAttrs;
180 Value *getShadowAddress(Value *Addr, Instruction *Pos);
181 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
182 bool isInstrumented(const Function *F);
183 bool isInstrumented(const GlobalAlias *GA);
184 FunctionType *getArgsFunctionType(FunctionType *T);
185 FunctionType *getCustomFunctionType(FunctionType *T);
186 InstrumentedABI getInstrumentedABI();
187 WrapperKind getWrapperKind(Function *F);
188 void addGlobalNamePrefix(GlobalValue *GV);
189 Function *buildWrapperFunction(Function *F, StringRef NewFName,
190 GlobalValue::LinkageTypes NewFLink,
191 FunctionType *NewFT);
194 DataFlowSanitizer(StringRef ABIListFile = StringRef(),
195 void *(*getArgTLS)() = 0, void *(*getRetValTLS)() = 0);
197 bool doInitialization(Module &M);
198 bool runOnModule(Module &M);
201 struct DFSanFunction {
202 DataFlowSanitizer &DFS;
204 DataFlowSanitizer::InstrumentedABI IA;
208 AllocaInst *LabelReturnAlloca;
209 DenseMap<Value *, Value *> ValShadowMap;
210 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
211 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
212 DenseSet<Instruction *> SkipInsts;
213 DenseSet<Value *> NonZeroChecks;
215 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
216 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
217 IsNativeABI(IsNativeABI), ArgTLSPtr(0), RetvalTLSPtr(0),
218 LabelReturnAlloca(0) {}
219 Value *getArgTLSPtr();
220 Value *getArgTLS(unsigned Index, Instruction *Pos);
221 Value *getRetvalTLS();
222 Value *getShadow(Value *V);
223 void setShadow(Instruction *I, Value *Shadow);
224 Value *combineOperandShadows(Instruction *Inst);
225 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
227 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
231 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
234 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
236 void visitOperandShadowInst(Instruction &I);
238 void visitBinaryOperator(BinaryOperator &BO);
239 void visitCastInst(CastInst &CI);
240 void visitCmpInst(CmpInst &CI);
241 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
242 void visitLoadInst(LoadInst &LI);
243 void visitStoreInst(StoreInst &SI);
244 void visitReturnInst(ReturnInst &RI);
245 void visitCallSite(CallSite CS);
246 void visitPHINode(PHINode &PN);
247 void visitExtractElementInst(ExtractElementInst &I);
248 void visitInsertElementInst(InsertElementInst &I);
249 void visitShuffleVectorInst(ShuffleVectorInst &I);
250 void visitExtractValueInst(ExtractValueInst &I);
251 void visitInsertValueInst(InsertValueInst &I);
252 void visitAllocaInst(AllocaInst &I);
253 void visitSelectInst(SelectInst &I);
254 void visitMemSetInst(MemSetInst &I);
255 void visitMemTransferInst(MemTransferInst &I);
260 char DataFlowSanitizer::ID;
261 INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
262 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
264 ModulePass *llvm::createDataFlowSanitizerPass(StringRef ABIListFile,
265 void *(*getArgTLS)(),
266 void *(*getRetValTLS)()) {
267 return new DataFlowSanitizer(ABIListFile, getArgTLS, getRetValTLS);
270 DataFlowSanitizer::DataFlowSanitizer(StringRef ABIListFile,
271 void *(*getArgTLS)(),
272 void *(*getRetValTLS)())
273 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
274 ABIList(SpecialCaseList::createOrDie(ABIListFile.empty() ? ClABIListFile
278 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
279 llvm::SmallVector<Type *, 4> ArgTypes;
280 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
281 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
282 ArgTypes.push_back(ShadowTy);
284 ArgTypes.push_back(ShadowPtrTy);
285 Type *RetType = T->getReturnType();
286 if (!RetType->isVoidTy())
287 RetType = StructType::get(RetType, ShadowTy, (Type *)0);
288 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
291 FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
292 assert(!T->isVarArg());
293 llvm::SmallVector<Type *, 4> ArgTypes;
294 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
295 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
296 ArgTypes.push_back(ShadowTy);
297 Type *RetType = T->getReturnType();
298 if (!RetType->isVoidTy())
299 ArgTypes.push_back(ShadowPtrTy);
300 return FunctionType::get(T->getReturnType(), ArgTypes, false);
303 bool DataFlowSanitizer::doInitialization(Module &M) {
304 DL = getAnalysisIfAvailable<DataLayout>();
309 Ctx = &M.getContext();
310 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
311 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
312 IntptrTy = DL->getIntPtrType(*Ctx);
313 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
314 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
315 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
317 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
319 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
320 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
322 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
323 DFSanUnimplementedFnTy = FunctionType::get(
324 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
325 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
326 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
327 DFSanSetLabelArgs, /*isVarArg=*/false);
328 DFSanNonzeroLabelFnTy = FunctionType::get(
329 Type::getVoidTy(*Ctx), ArrayRef<Type *>(), /*isVarArg=*/false);
332 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
334 GetArgTLS = ConstantExpr::getIntToPtr(
335 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
336 PointerType::getUnqual(
337 FunctionType::get(PointerType::getUnqual(ArgTLSTy), (Type *)0)));
339 if (GetRetvalTLSPtr) {
341 GetRetvalTLS = ConstantExpr::getIntToPtr(
342 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
343 PointerType::getUnqual(
344 FunctionType::get(PointerType::getUnqual(ShadowTy), (Type *)0)));
347 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
351 bool DataFlowSanitizer::isInstrumented(const Function *F) {
352 return !ABIList->isIn(*F, "uninstrumented");
355 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
356 return !ABIList->isIn(*GA, "uninstrumented");
359 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
360 return ClArgsABI ? IA_Args : IA_TLS;
363 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
364 if (ABIList->isIn(*F, "functional"))
365 return WK_Functional;
366 if (ABIList->isIn(*F, "discard"))
368 if (ABIList->isIn(*F, "custom"))
374 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
375 std::string GVName = GV->getName(), Prefix = "dfs$";
376 GV->setName(Prefix + GVName);
378 // Try to change the name of the function in module inline asm. We only do
379 // this for specific asm directives, currently only ".symver", to try to avoid
380 // corrupting asm which happens to contain the symbol name as a substring.
381 // Note that the substitution for .symver assumes that the versioned symbol
382 // also has an instrumented name.
383 std::string Asm = GV->getParent()->getModuleInlineAsm();
384 std::string SearchStr = ".symver " + GVName + ",";
385 size_t Pos = Asm.find(SearchStr);
386 if (Pos != std::string::npos) {
387 Asm.replace(Pos, SearchStr.size(),
388 ".symver " + Prefix + GVName + "," + Prefix);
389 GV->getParent()->setModuleInlineAsm(Asm);
394 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
395 GlobalValue::LinkageTypes NewFLink,
396 FunctionType *NewFT) {
397 FunctionType *FT = F->getFunctionType();
398 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
400 NewF->copyAttributesFrom(F);
401 NewF->removeAttributes(
402 AttributeSet::ReturnIndex,
403 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
404 AttributeSet::ReturnIndex));
406 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
407 std::vector<Value *> Args;
408 unsigned n = FT->getNumParams();
409 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
410 Args.push_back(&*ai);
411 CallInst *CI = CallInst::Create(F, Args, "", BB);
412 if (FT->getReturnType()->isVoidTy())
413 ReturnInst::Create(*Ctx, BB);
415 ReturnInst::Create(*Ctx, CI, BB);
420 bool DataFlowSanitizer::runOnModule(Module &M) {
424 if (ABIList->isIn(M, "skip"))
428 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
429 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
430 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
431 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
433 if (!GetRetvalTLSPtr) {
434 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
435 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
436 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
439 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
440 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
441 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
442 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
443 F->addAttribute(1, Attribute::ZExt);
444 F->addAttribute(2, Attribute::ZExt);
447 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
448 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
449 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
451 DFSanUnimplementedFn =
452 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
454 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
455 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
456 F->addAttribute(1, Attribute::ZExt);
458 DFSanNonzeroLabelFn =
459 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
461 std::vector<Function *> FnsToInstrument;
462 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
463 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
464 if (!i->isIntrinsic() &&
466 i != DFSanUnionLoadFn &&
467 i != DFSanUnimplementedFn &&
468 i != DFSanSetLabelFn &&
469 i != DFSanNonzeroLabelFn)
470 FnsToInstrument.push_back(&*i);
473 // Give function aliases prefixes when necessary, and build wrappers where the
474 // instrumentedness is inconsistent.
475 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
476 GlobalAlias *GA = &*i;
478 // Don't stop on weak. We assume people aren't playing games with the
479 // instrumentedness of overridden weak aliases.
480 if (Function *F = dyn_cast<Function>(
481 GA->resolveAliasedGlobal(/*stopOnWeak=*/false))) {
482 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
483 if (GAInst && FInst) {
484 addGlobalNamePrefix(GA);
485 } else if (GAInst != FInst) {
486 // Non-instrumented alias of an instrumented function, or vice versa.
487 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
488 // below will take care of instrumenting it.
490 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
491 GA->replaceAllUsesWith(NewF);
493 GA->eraseFromParent();
494 FnsToInstrument.push_back(NewF);
500 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
501 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
503 // First, change the ABI of every function in the module. ABI-listed
504 // functions keep their original ABI and get a wrapper function.
505 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
506 e = FnsToInstrument.end();
509 FunctionType *FT = F.getFunctionType();
511 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
512 FT->getReturnType()->isVoidTy());
514 if (isInstrumented(&F)) {
515 // Instrumented functions get a 'dfs$' prefix. This allows us to more
516 // easily identify cases of mismatching ABIs.
517 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
518 FunctionType *NewFT = getArgsFunctionType(FT);
519 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
520 NewF->copyAttributesFrom(&F);
521 NewF->removeAttributes(
522 AttributeSet::ReturnIndex,
523 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
524 AttributeSet::ReturnIndex));
525 for (Function::arg_iterator FArg = F.arg_begin(),
526 NewFArg = NewF->arg_begin(),
527 FArgEnd = F.arg_end();
528 FArg != FArgEnd; ++FArg, ++NewFArg) {
529 FArg->replaceAllUsesWith(NewFArg);
531 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
533 for (Function::use_iterator ui = F.use_begin(), ue = F.use_end();
535 BlockAddress *BA = dyn_cast<BlockAddress>(ui.getUse().getUser());
538 BA->replaceAllUsesWith(
539 BlockAddress::get(NewF, BA->getBasicBlock()));
543 F.replaceAllUsesWith(
544 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
548 addGlobalNamePrefix(NewF);
550 addGlobalNamePrefix(&F);
552 // Hopefully, nobody will try to indirectly call a vararg
554 } else if (FT->isVarArg()) {
555 UnwrappedFnMap[&F] = &F;
557 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
558 // Build a wrapper function for F. The wrapper simply calls F, and is
559 // added to FnsToInstrument so that any instrumentation according to its
560 // WrapperKind is done in the second pass below.
561 FunctionType *NewFT = getInstrumentedABI() == IA_Args
562 ? getArgsFunctionType(FT)
565 buildWrapperFunction(&F, std::string("dfsw$") + std::string(F.getName()),
566 GlobalValue::LinkOnceODRLinkage, NewFT);
567 if (getInstrumentedABI() == IA_TLS)
568 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
570 Value *WrappedFnCst =
571 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
572 F.replaceAllUsesWith(WrappedFnCst);
573 UnwrappedFnMap[WrappedFnCst] = &F;
576 if (!F.isDeclaration()) {
577 // This function is probably defining an interposition of an
578 // uninstrumented function and hence needs to keep the original ABI.
579 // But any functions it may call need to use the instrumented ABI, so
580 // we instrument it in a mode which preserves the original ABI.
581 FnsWithNativeABI.insert(&F);
583 // This code needs to rebuild the iterators, as they may be invalidated
584 // by the push_back, taking care that the new range does not include
585 // any functions added by this code.
586 size_t N = i - FnsToInstrument.begin(),
587 Count = e - FnsToInstrument.begin();
588 FnsToInstrument.push_back(&F);
589 i = FnsToInstrument.begin() + N;
590 e = FnsToInstrument.begin() + Count;
595 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
596 e = FnsToInstrument.end();
598 if (!*i || (*i)->isDeclaration())
601 removeUnreachableBlocks(**i);
603 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
605 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
606 // Build a copy of the list before iterating over it.
607 llvm::SmallVector<BasicBlock *, 4> BBList;
608 std::copy(df_begin(&(*i)->getEntryBlock()), df_end(&(*i)->getEntryBlock()),
609 std::back_inserter(BBList));
611 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
614 Instruction *Inst = &(*i)->front();
616 // DFSanVisitor may split the current basic block, changing the current
617 // instruction's next pointer and moving the next instruction to the
618 // tail block from which we should continue.
619 Instruction *Next = Inst->getNextNode();
620 // DFSanVisitor may delete Inst, so keep track of whether it was a
622 bool IsTerminator = isa<TerminatorInst>(Inst);
623 if (!DFSF.SkipInsts.count(Inst))
624 DFSanVisitor(DFSF).visit(Inst);
631 // We will not necessarily be able to compute the shadow for every phi node
632 // until we have visited every block. Therefore, the code that handles phi
633 // nodes adds them to the PHIFixups list so that they can be properly
635 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
636 i = DFSF.PHIFixups.begin(),
637 e = DFSF.PHIFixups.end();
639 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
641 i->second->setIncomingValue(
642 val, DFSF.getShadow(i->first->getIncomingValue(val)));
646 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
647 // places (i.e. instructions in basic blocks we haven't even begun visiting
648 // yet). To make our life easier, do this work in a pass after the main
650 if (ClDebugNonzeroLabels) {
651 for (DenseSet<Value *>::iterator i = DFSF.NonZeroChecks.begin(),
652 e = DFSF.NonZeroChecks.end();
655 if (Instruction *I = dyn_cast<Instruction>(*i))
656 Pos = I->getNextNode();
658 Pos = DFSF.F->getEntryBlock().begin();
659 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
660 Pos = Pos->getNextNode();
661 IRBuilder<> IRB(Pos);
662 Instruction *NeInst = cast<Instruction>(
663 IRB.CreateICmpNE(*i, DFSF.DFS.ZeroShadow));
664 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
665 NeInst, /*Unreachable=*/ false, ColdCallWeights));
666 IRBuilder<> ThenIRB(BI);
667 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
675 Value *DFSanFunction::getArgTLSPtr() {
679 return ArgTLSPtr = DFS.ArgTLS;
681 IRBuilder<> IRB(F->getEntryBlock().begin());
682 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
685 Value *DFSanFunction::getRetvalTLS() {
689 return RetvalTLSPtr = DFS.RetvalTLS;
691 IRBuilder<> IRB(F->getEntryBlock().begin());
692 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
695 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
696 IRBuilder<> IRB(Pos);
697 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
700 Value *DFSanFunction::getShadow(Value *V) {
701 if (!isa<Argument>(V) && !isa<Instruction>(V))
702 return DFS.ZeroShadow;
703 Value *&Shadow = ValShadowMap[V];
705 if (Argument *A = dyn_cast<Argument>(V)) {
707 return DFS.ZeroShadow;
709 case DataFlowSanitizer::IA_TLS: {
710 Value *ArgTLSPtr = getArgTLSPtr();
711 Instruction *ArgTLSPos =
712 DFS.ArgTLS ? &*F->getEntryBlock().begin()
713 : cast<Instruction>(ArgTLSPtr)->getNextNode();
714 IRBuilder<> IRB(ArgTLSPos);
715 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
718 case DataFlowSanitizer::IA_Args: {
719 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
720 Function::arg_iterator i = F->arg_begin();
724 assert(Shadow->getType() == DFS.ShadowTy);
728 NonZeroChecks.insert(Shadow);
730 Shadow = DFS.ZeroShadow;
736 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
737 assert(!ValShadowMap.count(I));
738 assert(Shadow->getType() == DFS.ShadowTy);
739 ValShadowMap[I] = Shadow;
742 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
743 assert(Addr != RetvalTLS && "Reinstrumenting?");
744 IRBuilder<> IRB(Pos);
745 return IRB.CreateIntToPtr(
747 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
752 // Generates IR to compute the union of the two given shadows, inserting it
753 // before Pos. Returns the computed union Value.
754 Value *DataFlowSanitizer::combineShadows(Value *V1, Value *V2,
756 if (V1 == ZeroShadow)
758 if (V2 == ZeroShadow)
762 IRBuilder<> IRB(Pos);
763 BasicBlock *Head = Pos->getParent();
764 Value *Ne = IRB.CreateICmpNE(V1, V2);
765 Instruction *NeInst = dyn_cast<Instruction>(Ne);
767 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
768 NeInst, /*Unreachable=*/ false, ColdCallWeights));
769 IRBuilder<> ThenIRB(BI);
770 CallInst *Call = ThenIRB.CreateCall2(DFSanUnionFn, V1, V2);
771 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
772 Call->addAttribute(1, Attribute::ZExt);
773 Call->addAttribute(2, Attribute::ZExt);
775 BasicBlock *Tail = BI->getSuccessor(0);
776 PHINode *Phi = PHINode::Create(ShadowTy, 2, "", Tail->begin());
777 Phi->addIncoming(Call, Call->getParent());
778 Phi->addIncoming(ZeroShadow, Head);
787 // A convenience function which folds the shadows of each of the operands
788 // of the provided instruction Inst, inserting the IR before Inst. Returns
789 // the computed union Value.
790 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
791 if (Inst->getNumOperands() == 0)
792 return DFS.ZeroShadow;
794 Value *Shadow = getShadow(Inst->getOperand(0));
795 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
796 Shadow = DFS.combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
801 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
802 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
803 DFSF.setShadow(&I, CombinedShadow);
806 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
807 // Addr has alignment Align, and take the union of each of those shadows.
808 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
810 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
811 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
812 AllocaShadowMap.find(AI);
813 if (i != AllocaShadowMap.end()) {
814 IRBuilder<> IRB(Pos);
815 return IRB.CreateLoad(i->second);
819 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
820 SmallVector<Value *, 2> Objs;
821 GetUnderlyingObjects(Addr, Objs, DFS.DL);
822 bool AllConstants = true;
823 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
825 if (isa<Function>(*i) || isa<BlockAddress>(*i))
827 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
830 AllConstants = false;
834 return DFS.ZeroShadow;
836 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
839 return DFS.ZeroShadow;
841 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
842 LI->setAlignment(ShadowAlign);
846 IRBuilder<> IRB(Pos);
848 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
849 return DFS.combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
850 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign),
854 if (Size % (64 / DFS.ShadowWidth) == 0) {
855 // Fast path for the common case where each byte has identical shadow: load
856 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
857 // shadow is non-equal.
858 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
859 IRBuilder<> FallbackIRB(FallbackBB);
860 CallInst *FallbackCall = FallbackIRB.CreateCall2(
861 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
862 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
864 // Compare each of the shadows stored in the loaded 64 bits to each other,
865 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
866 IRBuilder<> IRB(Pos);
868 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
869 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
870 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
871 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
872 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
873 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
874 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
876 BasicBlock *Head = Pos->getParent();
877 BasicBlock *Tail = Head->splitBasicBlock(Pos);
878 // In the following code LastBr will refer to the previous basic block's
879 // conditional branch instruction, whose true successor is fixed up to point
880 // to the next block during the loop below or to the tail after the final
882 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
883 ReplaceInstWithInst(Head->getTerminator(), LastBr);
885 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
886 Ofs += 64 / DFS.ShadowWidth) {
887 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
888 IRBuilder<> NextIRB(NextBB);
889 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
890 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
891 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
892 LastBr->setSuccessor(0, NextBB);
893 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
896 LastBr->setSuccessor(0, Tail);
897 FallbackIRB.CreateBr(Tail);
898 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
899 Shadow->addIncoming(FallbackCall, FallbackBB);
900 Shadow->addIncoming(TruncShadow, LastBr->getParent());
904 IRBuilder<> IRB(Pos);
905 CallInst *FallbackCall = IRB.CreateCall2(
906 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
907 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
911 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
912 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
914 if (ClPreserveAlignment) {
915 Align = LI.getAlignment();
917 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
921 IRBuilder<> IRB(&LI);
922 Value *LoadedShadow =
923 DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
924 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
925 Value *CombinedShadow = DFSF.DFS.combineShadows(LoadedShadow, PtrShadow, &LI);
926 if (CombinedShadow != DFSF.DFS.ZeroShadow)
927 DFSF.NonZeroChecks.insert(CombinedShadow);
929 DFSF.setShadow(&LI, CombinedShadow);
932 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
933 Value *Shadow, Instruction *Pos) {
934 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
935 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
936 AllocaShadowMap.find(AI);
937 if (i != AllocaShadowMap.end()) {
938 IRBuilder<> IRB(Pos);
939 IRB.CreateStore(Shadow, i->second);
944 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
945 IRBuilder<> IRB(Pos);
946 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
947 if (Shadow == DFS.ZeroShadow) {
948 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
949 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
950 Value *ExtShadowAddr =
951 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
952 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
956 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
958 if (Size >= ShadowVecSize) {
959 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
960 Value *ShadowVec = UndefValue::get(ShadowVecTy);
961 for (unsigned i = 0; i != ShadowVecSize; ++i) {
962 ShadowVec = IRB.CreateInsertElement(
963 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
965 Value *ShadowVecAddr =
966 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
968 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
969 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
970 Size -= ShadowVecSize;
972 } while (Size >= ShadowVecSize);
973 Offset *= ShadowVecSize;
976 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
977 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
983 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
985 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
987 if (ClPreserveAlignment) {
988 Align = SI.getAlignment();
990 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
994 DFSF.storeShadow(SI.getPointerOperand(), Size, Align,
995 DFSF.getShadow(SI.getValueOperand()), &SI);
998 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
999 visitOperandShadowInst(BO);
1002 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1004 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1006 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1007 visitOperandShadowInst(GEPI);
1010 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1011 visitOperandShadowInst(I);
1014 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1015 visitOperandShadowInst(I);
1018 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1019 visitOperandShadowInst(I);
1022 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1023 visitOperandShadowInst(I);
1026 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1027 visitOperandShadowInst(I);
1030 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1031 bool AllLoadsStores = true;
1032 for (Instruction::use_iterator i = I.use_begin(), e = I.use_end(); i != e;
1034 if (isa<LoadInst>(*i))
1037 if (StoreInst *SI = dyn_cast<StoreInst>(*i)) {
1038 if (SI->getPointerOperand() == &I)
1042 AllLoadsStores = false;
1045 if (AllLoadsStores) {
1046 IRBuilder<> IRB(&I);
1047 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1049 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1052 void DFSanVisitor::visitSelectInst(SelectInst &I) {
1053 Value *CondShadow = DFSF.getShadow(I.getCondition());
1054 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1055 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1057 if (isa<VectorType>(I.getCondition()->getType())) {
1059 &I, DFSF.DFS.combineShadows(
1061 DFSF.DFS.combineShadows(TrueShadow, FalseShadow, &I), &I));
1064 if (TrueShadow == FalseShadow) {
1065 ShadowSel = TrueShadow;
1068 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1070 DFSF.setShadow(&I, DFSF.DFS.combineShadows(CondShadow, ShadowSel, &I));
1074 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1075 IRBuilder<> IRB(&I);
1076 Value *ValShadow = DFSF.getShadow(I.getValue());
1078 DFSF.DFS.DFSanSetLabelFn, ValShadow,
1079 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1080 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1083 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1084 IRBuilder<> IRB(&I);
1085 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1086 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1087 Value *LenShadow = IRB.CreateMul(
1089 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1091 if (ClPreserveAlignment) {
1092 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1093 ConstantInt::get(I.getAlignmentCst()->getType(),
1094 DFSF.DFS.ShadowWidth / 8));
1096 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1097 DFSF.DFS.ShadowWidth / 8);
1099 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1100 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1101 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1102 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1103 AlignShadow, I.getVolatileCst());
1106 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
1107 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
1109 case DataFlowSanitizer::IA_TLS: {
1110 Value *S = DFSF.getShadow(RI.getReturnValue());
1111 IRBuilder<> IRB(&RI);
1112 IRB.CreateStore(S, DFSF.getRetvalTLS());
1115 case DataFlowSanitizer::IA_Args: {
1116 IRBuilder<> IRB(&RI);
1117 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1119 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1121 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1122 RI.setOperand(0, InsShadow);
1129 void DFSanVisitor::visitCallSite(CallSite CS) {
1130 Function *F = CS.getCalledFunction();
1131 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1132 visitOperandShadowInst(*CS.getInstruction());
1136 IRBuilder<> IRB(CS.getInstruction());
1138 DenseMap<Value *, Function *>::iterator i =
1139 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1140 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1141 Function *F = i->second;
1142 switch (DFSF.DFS.getWrapperKind(F)) {
1143 case DataFlowSanitizer::WK_Warning: {
1144 CS.setCalledFunction(F);
1145 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1146 IRB.CreateGlobalStringPtr(F->getName()));
1147 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1150 case DataFlowSanitizer::WK_Discard: {
1151 CS.setCalledFunction(F);
1152 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1155 case DataFlowSanitizer::WK_Functional: {
1156 CS.setCalledFunction(F);
1157 visitOperandShadowInst(*CS.getInstruction());
1160 case DataFlowSanitizer::WK_Custom: {
1161 // Don't try to handle invokes of custom functions, it's too complicated.
1162 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1164 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1165 FunctionType *FT = F->getFunctionType();
1166 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1167 std::string CustomFName = "__dfsw_";
1168 CustomFName += F->getName();
1170 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1171 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1172 CustomFn->copyAttributesFrom(F);
1174 // Custom functions returning non-void will write to the return label.
1175 if (!FT->getReturnType()->isVoidTy()) {
1176 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1177 DFSF.DFS.ReadOnlyNoneAttrs);
1181 std::vector<Value *> Args;
1183 CallSite::arg_iterator i = CS.arg_begin();
1184 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1188 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1189 Args.push_back(DFSF.getShadow(*i));
1191 if (!FT->getReturnType()->isVoidTy()) {
1192 if (!DFSF.LabelReturnAlloca) {
1193 DFSF.LabelReturnAlloca =
1194 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1195 DFSF.F->getEntryBlock().begin());
1197 Args.push_back(DFSF.LabelReturnAlloca);
1200 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1201 CustomCI->setCallingConv(CI->getCallingConv());
1202 CustomCI->setAttributes(CI->getAttributes());
1204 if (!FT->getReturnType()->isVoidTy()) {
1205 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1206 DFSF.setShadow(CustomCI, LabelLoad);
1209 CI->replaceAllUsesWith(CustomCI);
1210 CI->eraseFromParent();
1218 FunctionType *FT = cast<FunctionType>(
1219 CS.getCalledValue()->getType()->getPointerElementType());
1220 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1221 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1222 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1223 DFSF.getArgTLS(i, CS.getInstruction()));
1227 Instruction *Next = 0;
1228 if (!CS.getType()->isVoidTy()) {
1229 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1230 if (II->getNormalDest()->getSinglePredecessor()) {
1231 Next = II->getNormalDest()->begin();
1234 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1235 Next = NewBB->begin();
1238 Next = CS->getNextNode();
1241 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1242 IRBuilder<> NextIRB(Next);
1243 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1244 DFSF.SkipInsts.insert(LI);
1245 DFSF.setShadow(CS.getInstruction(), LI);
1246 DFSF.NonZeroChecks.insert(LI);
1250 // Do all instrumentation for IA_Args down here to defer tampering with the
1251 // CFG in a way that SplitEdge may be able to detect.
1252 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1253 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
1255 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1256 std::vector<Value *> Args;
1258 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1259 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1263 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1264 Args.push_back(DFSF.getShadow(*i));
1266 if (FT->isVarArg()) {
1267 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1268 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1269 AllocaInst *VarArgShadow =
1270 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1271 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1272 for (unsigned n = 0; i != e; ++i, ++n) {
1273 IRB.CreateStore(DFSF.getShadow(*i),
1274 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1280 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1281 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1284 NewCS = IRB.CreateCall(Func, Args);
1286 NewCS.setCallingConv(CS.getCallingConv());
1287 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1288 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1289 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1290 AttributeSet::ReturnIndex)));
1293 ExtractValueInst *ExVal =
1294 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1295 DFSF.SkipInsts.insert(ExVal);
1296 ExtractValueInst *ExShadow =
1297 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1298 DFSF.SkipInsts.insert(ExShadow);
1299 DFSF.setShadow(ExVal, ExShadow);
1300 DFSF.NonZeroChecks.insert(ExShadow);
1302 CS.getInstruction()->replaceAllUsesWith(ExVal);
1305 CS.getInstruction()->eraseFromParent();
1309 void DFSanVisitor::visitPHINode(PHINode &PN) {
1311 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1313 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1314 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1315 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1317 ShadowPN->addIncoming(UndefShadow, *i);
1320 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1321 DFSF.setShadow(&PN, ShadowPN);