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/ADT/StringExtras.h"
52 #include "llvm/Analysis/ValueTracking.h"
53 #include "llvm/IR/Dominators.h"
54 #include "llvm/IR/IRBuilder.h"
55 #include "llvm/IR/InlineAsm.h"
56 #include "llvm/IR/InstVisitor.h"
57 #include "llvm/IR/LLVMContext.h"
58 #include "llvm/IR/MDBuilder.h"
59 #include "llvm/IR/Type.h"
60 #include "llvm/IR/Value.h"
61 #include "llvm/Pass.h"
62 #include "llvm/Support/CommandLine.h"
63 #include "llvm/Support/SpecialCaseList.h"
64 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
65 #include "llvm/Transforms/Utils/Local.h"
70 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
71 // alignment requirements provided by the input IR are correct. For example,
72 // if the input IR contains a load with alignment 8, this flag will cause
73 // the shadow load to have alignment 16. This flag is disabled by default as
74 // we have unfortunately encountered too much code (including Clang itself;
75 // see PR14291) which performs misaligned access.
76 static cl::opt<bool> ClPreserveAlignment(
77 "dfsan-preserve-alignment",
78 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
81 // The ABI list file controls how shadow parameters are passed. The pass treats
82 // every function labelled "uninstrumented" in the ABI list file as conforming
83 // to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
84 // additional annotations for those functions, a call to one of those functions
85 // will produce a warning message, as the labelling behaviour of the function is
86 // unknown. The other supported annotations are "functional" and "discard",
87 // which are described below under DataFlowSanitizer::WrapperKind.
88 static cl::opt<std::string> ClABIListFile(
90 cl::desc("File listing native ABI functions and how the pass treats them"),
93 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
94 // functions (see DataFlowSanitizer::InstrumentedABI below).
95 static cl::opt<bool> ClArgsABI(
97 cl::desc("Use the argument ABI rather than the TLS ABI"),
100 // Controls whether the pass includes or ignores the labels of pointers in load
102 static cl::opt<bool> ClCombinePointerLabelsOnLoad(
103 "dfsan-combine-pointer-labels-on-load",
104 cl::desc("Combine the label of the pointer with the label of the data when "
105 "loading from memory."),
106 cl::Hidden, cl::init(true));
108 // Controls whether the pass includes or ignores the labels of pointers in
109 // stores instructions.
110 static cl::opt<bool> ClCombinePointerLabelsOnStore(
111 "dfsan-combine-pointer-labels-on-store",
112 cl::desc("Combine the label of the pointer with the label of the data when "
113 "storing in memory."),
114 cl::Hidden, cl::init(false));
116 static cl::opt<bool> ClDebugNonzeroLabels(
117 "dfsan-debug-nonzero-labels",
118 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
119 "load or return with a nonzero label"),
124 StringRef GetGlobalTypeString(const GlobalValue &G) {
125 // Types of GlobalVariables are always pointer types.
126 Type *GType = G.getType()->getElementType();
127 // For now we support blacklisting struct types only.
128 if (StructType *SGType = dyn_cast<StructType>(GType)) {
129 if (!SGType->isLiteral())
130 return SGType->getName();
132 return "<unknown type>";
136 std::unique_ptr<SpecialCaseList> SCL;
139 DFSanABIList(SpecialCaseList *SCL) : SCL(SCL) {}
141 /// Returns whether either this function or its source file are listed in the
143 bool isIn(const Function &F, const StringRef Category) const {
144 return isIn(*F.getParent(), Category) ||
145 SCL->inSection("fun", F.getName(), Category);
148 /// Returns whether this global alias is listed in the given category.
150 /// If GA aliases a function, the alias's name is matched as a function name
151 /// would be. Similarly, aliases of globals are matched like globals.
152 bool isIn(const GlobalAlias &GA, const StringRef Category) const {
153 if (isIn(*GA.getParent(), Category))
156 if (isa<FunctionType>(GA.getType()->getElementType()))
157 return SCL->inSection("fun", GA.getName(), Category);
159 return SCL->inSection("global", GA.getName(), Category) ||
160 SCL->inSection("type", GetGlobalTypeString(GA), Category);
163 /// Returns whether this module is listed in the given category.
164 bool isIn(const Module &M, const StringRef Category) const {
165 return SCL->inSection("src", M.getModuleIdentifier(), Category);
169 class DataFlowSanitizer : public ModulePass {
170 friend struct DFSanFunction;
171 friend class DFSanVisitor;
177 /// Which ABI should be used for instrumented functions?
178 enum InstrumentedABI {
179 /// Argument and return value labels are passed through additional
180 /// arguments and by modifying the return type.
183 /// Argument and return value labels are passed through TLS variables
184 /// __dfsan_arg_tls and __dfsan_retval_tls.
188 /// How should calls to uninstrumented functions be handled?
190 /// This function is present in an uninstrumented form but we don't know
191 /// how it should be handled. Print a warning and call the function anyway.
192 /// Don't label the return value.
195 /// This function does not write to (user-accessible) memory, and its return
196 /// value is unlabelled.
199 /// This function does not write to (user-accessible) memory, and the label
200 /// of its return value is the union of the label of its arguments.
203 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
204 /// where F is the name of the function. This function may wrap the
205 /// original function or provide its own implementation. This is similar to
206 /// the IA_Args ABI, except that IA_Args uses a struct return type to
207 /// pass the return value shadow in a register, while WK_Custom uses an
208 /// extra pointer argument to return the shadow. This allows the wrapped
209 /// form of the function type to be expressed in C.
213 const DataLayout *DL;
216 IntegerType *ShadowTy;
217 PointerType *ShadowPtrTy;
218 IntegerType *IntptrTy;
219 ConstantInt *ZeroShadow;
220 ConstantInt *ShadowPtrMask;
221 ConstantInt *ShadowPtrMul;
224 void *(*GetArgTLSPtr)();
225 void *(*GetRetvalTLSPtr)();
227 Constant *GetRetvalTLS;
228 FunctionType *DFSanUnionFnTy;
229 FunctionType *DFSanUnionLoadFnTy;
230 FunctionType *DFSanUnimplementedFnTy;
231 FunctionType *DFSanSetLabelFnTy;
232 FunctionType *DFSanNonzeroLabelFnTy;
233 Constant *DFSanUnionFn;
234 Constant *DFSanUnionLoadFn;
235 Constant *DFSanUnimplementedFn;
236 Constant *DFSanSetLabelFn;
237 Constant *DFSanNonzeroLabelFn;
238 MDNode *ColdCallWeights;
239 DFSanABIList ABIList;
240 DenseMap<Value *, Function *> UnwrappedFnMap;
241 AttributeSet ReadOnlyNoneAttrs;
243 Value *getShadowAddress(Value *Addr, Instruction *Pos);
244 bool isInstrumented(const Function *F);
245 bool isInstrumented(const GlobalAlias *GA);
246 FunctionType *getArgsFunctionType(FunctionType *T);
247 FunctionType *getTrampolineFunctionType(FunctionType *T);
248 FunctionType *getCustomFunctionType(FunctionType *T);
249 InstrumentedABI getInstrumentedABI();
250 WrapperKind getWrapperKind(Function *F);
251 void addGlobalNamePrefix(GlobalValue *GV);
252 Function *buildWrapperFunction(Function *F, StringRef NewFName,
253 GlobalValue::LinkageTypes NewFLink,
254 FunctionType *NewFT);
255 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
258 DataFlowSanitizer(StringRef ABIListFile = StringRef(),
259 void *(*getArgTLS)() = nullptr,
260 void *(*getRetValTLS)() = nullptr);
262 bool doInitialization(Module &M) override;
263 bool runOnModule(Module &M) override;
266 struct DFSanFunction {
267 DataFlowSanitizer &DFS;
270 DataFlowSanitizer::InstrumentedABI IA;
274 AllocaInst *LabelReturnAlloca;
275 DenseMap<Value *, Value *> ValShadowMap;
276 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
277 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
278 DenseSet<Instruction *> SkipInsts;
279 DenseSet<Value *> NonZeroChecks;
281 struct CachedCombinedShadow {
285 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
286 CachedCombinedShadows;
288 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
289 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
290 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
291 LabelReturnAlloca(nullptr) {
294 Value *getArgTLSPtr();
295 Value *getArgTLS(unsigned Index, Instruction *Pos);
296 Value *getRetvalTLS();
297 Value *getShadow(Value *V);
298 void setShadow(Instruction *I, Value *Shadow);
299 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
300 Value *combineOperandShadows(Instruction *Inst);
301 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
303 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
307 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
310 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
312 void visitOperandShadowInst(Instruction &I);
314 void visitBinaryOperator(BinaryOperator &BO);
315 void visitCastInst(CastInst &CI);
316 void visitCmpInst(CmpInst &CI);
317 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
318 void visitLoadInst(LoadInst &LI);
319 void visitStoreInst(StoreInst &SI);
320 void visitReturnInst(ReturnInst &RI);
321 void visitCallSite(CallSite CS);
322 void visitPHINode(PHINode &PN);
323 void visitExtractElementInst(ExtractElementInst &I);
324 void visitInsertElementInst(InsertElementInst &I);
325 void visitShuffleVectorInst(ShuffleVectorInst &I);
326 void visitExtractValueInst(ExtractValueInst &I);
327 void visitInsertValueInst(InsertValueInst &I);
328 void visitAllocaInst(AllocaInst &I);
329 void visitSelectInst(SelectInst &I);
330 void visitMemSetInst(MemSetInst &I);
331 void visitMemTransferInst(MemTransferInst &I);
336 char DataFlowSanitizer::ID;
337 INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
338 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
340 ModulePass *llvm::createDataFlowSanitizerPass(StringRef ABIListFile,
341 void *(*getArgTLS)(),
342 void *(*getRetValTLS)()) {
343 return new DataFlowSanitizer(ABIListFile, getArgTLS, getRetValTLS);
346 DataFlowSanitizer::DataFlowSanitizer(StringRef ABIListFile,
347 void *(*getArgTLS)(),
348 void *(*getRetValTLS)())
349 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
350 ABIList(SpecialCaseList::createOrDie(ABIListFile.empty() ? ClABIListFile
354 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
355 llvm::SmallVector<Type *, 4> ArgTypes;
356 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
357 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
358 ArgTypes.push_back(ShadowTy);
360 ArgTypes.push_back(ShadowPtrTy);
361 Type *RetType = T->getReturnType();
362 if (!RetType->isVoidTy())
363 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
364 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
367 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
368 assert(!T->isVarArg());
369 llvm::SmallVector<Type *, 4> ArgTypes;
370 ArgTypes.push_back(T->getPointerTo());
371 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
372 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
373 ArgTypes.push_back(ShadowTy);
374 Type *RetType = T->getReturnType();
375 if (!RetType->isVoidTy())
376 ArgTypes.push_back(ShadowPtrTy);
377 return FunctionType::get(T->getReturnType(), ArgTypes, false);
380 FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
381 assert(!T->isVarArg());
382 llvm::SmallVector<Type *, 4> ArgTypes;
383 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
386 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
387 *i)->getElementType()))) {
388 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
389 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
391 ArgTypes.push_back(*i);
394 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
395 ArgTypes.push_back(ShadowTy);
396 Type *RetType = T->getReturnType();
397 if (!RetType->isVoidTy())
398 ArgTypes.push_back(ShadowPtrTy);
399 return FunctionType::get(T->getReturnType(), ArgTypes, false);
402 bool DataFlowSanitizer::doInitialization(Module &M) {
403 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
405 report_fatal_error("data layout missing");
406 DL = &DLP->getDataLayout();
409 Ctx = &M.getContext();
410 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
411 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
412 IntptrTy = DL->getIntPtrType(*Ctx);
413 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
414 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
415 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
417 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
419 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
420 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
422 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
423 DFSanUnimplementedFnTy = FunctionType::get(
424 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
425 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
426 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
427 DFSanSetLabelArgs, /*isVarArg=*/false);
428 DFSanNonzeroLabelFnTy = FunctionType::get(
429 Type::getVoidTy(*Ctx), ArrayRef<Type *>(), /*isVarArg=*/false);
432 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
434 GetArgTLS = ConstantExpr::getIntToPtr(
435 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
436 PointerType::getUnqual(
437 FunctionType::get(PointerType::getUnqual(ArgTLSTy),
440 if (GetRetvalTLSPtr) {
442 GetRetvalTLS = ConstantExpr::getIntToPtr(
443 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
444 PointerType::getUnqual(
445 FunctionType::get(PointerType::getUnqual(ShadowTy),
449 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
453 bool DataFlowSanitizer::isInstrumented(const Function *F) {
454 return !ABIList.isIn(*F, "uninstrumented");
457 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
458 return !ABIList.isIn(*GA, "uninstrumented");
461 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
462 return ClArgsABI ? IA_Args : IA_TLS;
465 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
466 if (ABIList.isIn(*F, "functional"))
467 return WK_Functional;
468 if (ABIList.isIn(*F, "discard"))
470 if (ABIList.isIn(*F, "custom"))
476 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
477 std::string GVName = GV->getName(), Prefix = "dfs$";
478 GV->setName(Prefix + GVName);
480 // Try to change the name of the function in module inline asm. We only do
481 // this for specific asm directives, currently only ".symver", to try to avoid
482 // corrupting asm which happens to contain the symbol name as a substring.
483 // Note that the substitution for .symver assumes that the versioned symbol
484 // also has an instrumented name.
485 std::string Asm = GV->getParent()->getModuleInlineAsm();
486 std::string SearchStr = ".symver " + GVName + ",";
487 size_t Pos = Asm.find(SearchStr);
488 if (Pos != std::string::npos) {
489 Asm.replace(Pos, SearchStr.size(),
490 ".symver " + Prefix + GVName + "," + Prefix);
491 GV->getParent()->setModuleInlineAsm(Asm);
496 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
497 GlobalValue::LinkageTypes NewFLink,
498 FunctionType *NewFT) {
499 FunctionType *FT = F->getFunctionType();
500 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
502 NewF->copyAttributesFrom(F);
503 NewF->removeAttributes(
504 AttributeSet::ReturnIndex,
505 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
506 AttributeSet::ReturnIndex));
508 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
509 std::vector<Value *> Args;
510 unsigned n = FT->getNumParams();
511 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
512 Args.push_back(&*ai);
513 CallInst *CI = CallInst::Create(F, Args, "", BB);
514 if (FT->getReturnType()->isVoidTy())
515 ReturnInst::Create(*Ctx, BB);
517 ReturnInst::Create(*Ctx, CI, BB);
522 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
524 FunctionType *FTT = getTrampolineFunctionType(FT);
525 Constant *C = Mod->getOrInsertFunction(FName, FTT);
526 Function *F = dyn_cast<Function>(C);
527 if (F && F->isDeclaration()) {
528 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
529 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
530 std::vector<Value *> Args;
531 Function::arg_iterator AI = F->arg_begin(); ++AI;
532 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
533 Args.push_back(&*AI);
535 CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
537 if (FT->getReturnType()->isVoidTy())
538 RI = ReturnInst::Create(*Ctx, BB);
540 RI = ReturnInst::Create(*Ctx, CI, BB);
542 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
543 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
544 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
545 DFSF.ValShadowMap[ValAI] = ShadowAI;
546 DFSanVisitor(DFSF).visitCallInst(*CI);
547 if (!FT->getReturnType()->isVoidTy())
548 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
549 &F->getArgumentList().back(), RI);
555 bool DataFlowSanitizer::runOnModule(Module &M) {
559 if (ABIList.isIn(M, "skip"))
563 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
564 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
565 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
566 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
568 if (!GetRetvalTLSPtr) {
569 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
570 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
571 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
574 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
575 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
576 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
577 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
578 F->addAttribute(1, Attribute::ZExt);
579 F->addAttribute(2, Attribute::ZExt);
582 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
583 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
584 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
585 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
587 DFSanUnimplementedFn =
588 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
590 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
591 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
592 F->addAttribute(1, Attribute::ZExt);
594 DFSanNonzeroLabelFn =
595 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
597 std::vector<Function *> FnsToInstrument;
598 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
599 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
600 if (!i->isIntrinsic() &&
602 i != DFSanUnionLoadFn &&
603 i != DFSanUnimplementedFn &&
604 i != DFSanSetLabelFn &&
605 i != DFSanNonzeroLabelFn)
606 FnsToInstrument.push_back(&*i);
609 // Give function aliases prefixes when necessary, and build wrappers where the
610 // instrumentedness is inconsistent.
611 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
612 GlobalAlias *GA = &*i;
614 // Don't stop on weak. We assume people aren't playing games with the
615 // instrumentedness of overridden weak aliases.
616 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
617 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
618 if (GAInst && FInst) {
619 addGlobalNamePrefix(GA);
620 } else if (GAInst != FInst) {
621 // Non-instrumented alias of an instrumented function, or vice versa.
622 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
623 // below will take care of instrumenting it.
625 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
626 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
628 GA->eraseFromParent();
629 FnsToInstrument.push_back(NewF);
635 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
636 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
638 // First, change the ABI of every function in the module. ABI-listed
639 // functions keep their original ABI and get a wrapper function.
640 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
641 e = FnsToInstrument.end();
644 FunctionType *FT = F.getFunctionType();
646 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
647 FT->getReturnType()->isVoidTy());
649 if (isInstrumented(&F)) {
650 // Instrumented functions get a 'dfs$' prefix. This allows us to more
651 // easily identify cases of mismatching ABIs.
652 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
653 FunctionType *NewFT = getArgsFunctionType(FT);
654 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
655 NewF->copyAttributesFrom(&F);
656 NewF->removeAttributes(
657 AttributeSet::ReturnIndex,
658 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
659 AttributeSet::ReturnIndex));
660 for (Function::arg_iterator FArg = F.arg_begin(),
661 NewFArg = NewF->arg_begin(),
662 FArgEnd = F.arg_end();
663 FArg != FArgEnd; ++FArg, ++NewFArg) {
664 FArg->replaceAllUsesWith(NewFArg);
666 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
668 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
670 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
673 BA->replaceAllUsesWith(
674 BlockAddress::get(NewF, BA->getBasicBlock()));
678 F.replaceAllUsesWith(
679 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
683 addGlobalNamePrefix(NewF);
685 addGlobalNamePrefix(&F);
687 // Hopefully, nobody will try to indirectly call a vararg
689 } else if (FT->isVarArg()) {
690 UnwrappedFnMap[&F] = &F;
692 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
693 // Build a wrapper function for F. The wrapper simply calls F, and is
694 // added to FnsToInstrument so that any instrumentation according to its
695 // WrapperKind is done in the second pass below.
696 FunctionType *NewFT = getInstrumentedABI() == IA_Args
697 ? getArgsFunctionType(FT)
699 Function *NewF = buildWrapperFunction(
700 &F, std::string("dfsw$") + std::string(F.getName()),
701 GlobalValue::LinkOnceODRLinkage, NewFT);
702 if (getInstrumentedABI() == IA_TLS)
703 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
705 Value *WrappedFnCst =
706 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
707 F.replaceAllUsesWith(WrappedFnCst);
708 UnwrappedFnMap[WrappedFnCst] = &F;
711 if (!F.isDeclaration()) {
712 // This function is probably defining an interposition of an
713 // uninstrumented function and hence needs to keep the original ABI.
714 // But any functions it may call need to use the instrumented ABI, so
715 // we instrument it in a mode which preserves the original ABI.
716 FnsWithNativeABI.insert(&F);
718 // This code needs to rebuild the iterators, as they may be invalidated
719 // by the push_back, taking care that the new range does not include
720 // any functions added by this code.
721 size_t N = i - FnsToInstrument.begin(),
722 Count = e - FnsToInstrument.begin();
723 FnsToInstrument.push_back(&F);
724 i = FnsToInstrument.begin() + N;
725 e = FnsToInstrument.begin() + Count;
730 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
731 e = FnsToInstrument.end();
733 if (!*i || (*i)->isDeclaration())
736 removeUnreachableBlocks(**i);
738 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
740 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
741 // Build a copy of the list before iterating over it.
742 llvm::SmallVector<BasicBlock *, 4> BBList(
743 depth_first(&(*i)->getEntryBlock()));
745 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
748 Instruction *Inst = &(*i)->front();
750 // DFSanVisitor may split the current basic block, changing the current
751 // instruction's next pointer and moving the next instruction to the
752 // tail block from which we should continue.
753 Instruction *Next = Inst->getNextNode();
754 // DFSanVisitor may delete Inst, so keep track of whether it was a
756 bool IsTerminator = isa<TerminatorInst>(Inst);
757 if (!DFSF.SkipInsts.count(Inst))
758 DFSanVisitor(DFSF).visit(Inst);
765 // We will not necessarily be able to compute the shadow for every phi node
766 // until we have visited every block. Therefore, the code that handles phi
767 // nodes adds them to the PHIFixups list so that they can be properly
769 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
770 i = DFSF.PHIFixups.begin(),
771 e = DFSF.PHIFixups.end();
773 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
775 i->second->setIncomingValue(
776 val, DFSF.getShadow(i->first->getIncomingValue(val)));
780 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
781 // places (i.e. instructions in basic blocks we haven't even begun visiting
782 // yet). To make our life easier, do this work in a pass after the main
784 if (ClDebugNonzeroLabels) {
785 for (DenseSet<Value *>::iterator i = DFSF.NonZeroChecks.begin(),
786 e = DFSF.NonZeroChecks.end();
789 if (Instruction *I = dyn_cast<Instruction>(*i))
790 Pos = I->getNextNode();
792 Pos = DFSF.F->getEntryBlock().begin();
793 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
794 Pos = Pos->getNextNode();
795 IRBuilder<> IRB(Pos);
796 Value *Ne = IRB.CreateICmpNE(*i, DFSF.DFS.ZeroShadow);
797 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
798 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
799 IRBuilder<> ThenIRB(BI);
800 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
808 Value *DFSanFunction::getArgTLSPtr() {
812 return ArgTLSPtr = DFS.ArgTLS;
814 IRBuilder<> IRB(F->getEntryBlock().begin());
815 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
818 Value *DFSanFunction::getRetvalTLS() {
822 return RetvalTLSPtr = DFS.RetvalTLS;
824 IRBuilder<> IRB(F->getEntryBlock().begin());
825 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
828 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
829 IRBuilder<> IRB(Pos);
830 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
833 Value *DFSanFunction::getShadow(Value *V) {
834 if (!isa<Argument>(V) && !isa<Instruction>(V))
835 return DFS.ZeroShadow;
836 Value *&Shadow = ValShadowMap[V];
838 if (Argument *A = dyn_cast<Argument>(V)) {
840 return DFS.ZeroShadow;
842 case DataFlowSanitizer::IA_TLS: {
843 Value *ArgTLSPtr = getArgTLSPtr();
844 Instruction *ArgTLSPos =
845 DFS.ArgTLS ? &*F->getEntryBlock().begin()
846 : cast<Instruction>(ArgTLSPtr)->getNextNode();
847 IRBuilder<> IRB(ArgTLSPos);
848 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
851 case DataFlowSanitizer::IA_Args: {
852 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
853 Function::arg_iterator i = F->arg_begin();
857 assert(Shadow->getType() == DFS.ShadowTy);
861 NonZeroChecks.insert(Shadow);
863 Shadow = DFS.ZeroShadow;
869 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
870 assert(!ValShadowMap.count(I));
871 assert(Shadow->getType() == DFS.ShadowTy);
872 ValShadowMap[I] = Shadow;
875 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
876 assert(Addr != RetvalTLS && "Reinstrumenting?");
877 IRBuilder<> IRB(Pos);
878 return IRB.CreateIntToPtr(
880 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
885 // Generates IR to compute the union of the two given shadows, inserting it
886 // before Pos. Returns the computed union Value.
887 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
888 if (V1 == DFS.ZeroShadow)
890 if (V2 == DFS.ZeroShadow)
895 auto Key = std::make_pair(V1, V2);
897 std::swap(Key.first, Key.second);
898 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
899 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
902 IRBuilder<> IRB(Pos);
903 BasicBlock *Head = Pos->getParent();
904 Value *Ne = IRB.CreateICmpNE(V1, V2);
905 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
906 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
907 IRBuilder<> ThenIRB(BI);
908 CallInst *Call = ThenIRB.CreateCall2(DFS.DFSanUnionFn, V1, V2);
909 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
910 Call->addAttribute(1, Attribute::ZExt);
911 Call->addAttribute(2, Attribute::ZExt);
913 BasicBlock *Tail = BI->getSuccessor(0);
914 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", Tail->begin());
915 Phi->addIncoming(Call, Call->getParent());
916 Phi->addIncoming(V1, Head);
923 // A convenience function which folds the shadows of each of the operands
924 // of the provided instruction Inst, inserting the IR before Inst. Returns
925 // the computed union Value.
926 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
927 if (Inst->getNumOperands() == 0)
928 return DFS.ZeroShadow;
930 Value *Shadow = getShadow(Inst->getOperand(0));
931 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
932 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
937 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
938 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
939 DFSF.setShadow(&I, CombinedShadow);
942 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
943 // Addr has alignment Align, and take the union of each of those shadows.
944 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
946 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
947 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
948 AllocaShadowMap.find(AI);
949 if (i != AllocaShadowMap.end()) {
950 IRBuilder<> IRB(Pos);
951 return IRB.CreateLoad(i->second);
955 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
956 SmallVector<Value *, 2> Objs;
957 GetUnderlyingObjects(Addr, Objs, DFS.DL);
958 bool AllConstants = true;
959 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
961 if (isa<Function>(*i) || isa<BlockAddress>(*i))
963 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
966 AllConstants = false;
970 return DFS.ZeroShadow;
972 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
975 return DFS.ZeroShadow;
977 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
978 LI->setAlignment(ShadowAlign);
982 IRBuilder<> IRB(Pos);
984 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
985 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
986 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
989 if (Size % (64 / DFS.ShadowWidth) == 0) {
990 // Fast path for the common case where each byte has identical shadow: load
991 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
992 // shadow is non-equal.
993 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
994 IRBuilder<> FallbackIRB(FallbackBB);
995 CallInst *FallbackCall = FallbackIRB.CreateCall2(
996 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
997 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
999 // Compare each of the shadows stored in the loaded 64 bits to each other,
1000 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1001 IRBuilder<> IRB(Pos);
1003 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1004 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1005 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1006 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1007 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1008 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1009 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1011 BasicBlock *Head = Pos->getParent();
1012 BasicBlock *Tail = Head->splitBasicBlock(Pos);
1014 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1015 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1017 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1018 for (auto Child : Children)
1019 DT.changeImmediateDominator(Child, NewNode);
1022 // In the following code LastBr will refer to the previous basic block's
1023 // conditional branch instruction, whose true successor is fixed up to point
1024 // to the next block during the loop below or to the tail after the final
1026 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1027 ReplaceInstWithInst(Head->getTerminator(), LastBr);
1028 DT.addNewBlock(FallbackBB, Head);
1030 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1031 Ofs += 64 / DFS.ShadowWidth) {
1032 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
1033 DT.addNewBlock(NextBB, LastBr->getParent());
1034 IRBuilder<> NextIRB(NextBB);
1035 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
1036 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1037 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1038 LastBr->setSuccessor(0, NextBB);
1039 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1042 LastBr->setSuccessor(0, Tail);
1043 FallbackIRB.CreateBr(Tail);
1044 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1045 Shadow->addIncoming(FallbackCall, FallbackBB);
1046 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1050 IRBuilder<> IRB(Pos);
1051 CallInst *FallbackCall = IRB.CreateCall2(
1052 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1053 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1054 return FallbackCall;
1057 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1058 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
1060 if (ClPreserveAlignment) {
1061 Align = LI.getAlignment();
1063 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
1067 IRBuilder<> IRB(&LI);
1068 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1069 if (ClCombinePointerLabelsOnLoad) {
1070 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
1071 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
1073 if (Shadow != DFSF.DFS.ZeroShadow)
1074 DFSF.NonZeroChecks.insert(Shadow);
1076 DFSF.setShadow(&LI, Shadow);
1079 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1080 Value *Shadow, Instruction *Pos) {
1081 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1082 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1083 AllocaShadowMap.find(AI);
1084 if (i != AllocaShadowMap.end()) {
1085 IRBuilder<> IRB(Pos);
1086 IRB.CreateStore(Shadow, i->second);
1091 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1092 IRBuilder<> IRB(Pos);
1093 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1094 if (Shadow == DFS.ZeroShadow) {
1095 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1096 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1097 Value *ExtShadowAddr =
1098 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1099 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1103 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1104 uint64_t Offset = 0;
1105 if (Size >= ShadowVecSize) {
1106 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1107 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1108 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1109 ShadowVec = IRB.CreateInsertElement(
1110 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1112 Value *ShadowVecAddr =
1113 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1115 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
1116 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1117 Size -= ShadowVecSize;
1119 } while (Size >= ShadowVecSize);
1120 Offset *= ShadowVecSize;
1123 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
1124 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1130 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1132 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
1134 if (ClPreserveAlignment) {
1135 Align = SI.getAlignment();
1137 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
1142 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1143 if (ClCombinePointerLabelsOnStore) {
1144 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
1145 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
1147 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
1150 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1151 visitOperandShadowInst(BO);
1154 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1156 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1158 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1159 visitOperandShadowInst(GEPI);
1162 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1163 visitOperandShadowInst(I);
1166 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1167 visitOperandShadowInst(I);
1170 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1171 visitOperandShadowInst(I);
1174 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1175 visitOperandShadowInst(I);
1178 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1179 visitOperandShadowInst(I);
1182 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1183 bool AllLoadsStores = true;
1184 for (User *U : I.users()) {
1185 if (isa<LoadInst>(U))
1188 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1189 if (SI->getPointerOperand() == &I)
1193 AllLoadsStores = false;
1196 if (AllLoadsStores) {
1197 IRBuilder<> IRB(&I);
1198 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1200 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1203 void DFSanVisitor::visitSelectInst(SelectInst &I) {
1204 Value *CondShadow = DFSF.getShadow(I.getCondition());
1205 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1206 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1208 if (isa<VectorType>(I.getCondition()->getType())) {
1211 DFSF.combineShadows(
1212 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
1215 if (TrueShadow == FalseShadow) {
1216 ShadowSel = TrueShadow;
1219 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1221 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
1225 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1226 IRBuilder<> IRB(&I);
1227 Value *ValShadow = DFSF.getShadow(I.getValue());
1229 DFSF.DFS.DFSanSetLabelFn, ValShadow,
1230 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1231 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1234 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1235 IRBuilder<> IRB(&I);
1236 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1237 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1238 Value *LenShadow = IRB.CreateMul(
1240 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1242 if (ClPreserveAlignment) {
1243 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1244 ConstantInt::get(I.getAlignmentCst()->getType(),
1245 DFSF.DFS.ShadowWidth / 8));
1247 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1248 DFSF.DFS.ShadowWidth / 8);
1250 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1251 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1252 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1253 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1254 AlignShadow, I.getVolatileCst());
1257 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
1258 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
1260 case DataFlowSanitizer::IA_TLS: {
1261 Value *S = DFSF.getShadow(RI.getReturnValue());
1262 IRBuilder<> IRB(&RI);
1263 IRB.CreateStore(S, DFSF.getRetvalTLS());
1266 case DataFlowSanitizer::IA_Args: {
1267 IRBuilder<> IRB(&RI);
1268 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1270 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1272 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1273 RI.setOperand(0, InsShadow);
1280 void DFSanVisitor::visitCallSite(CallSite CS) {
1281 Function *F = CS.getCalledFunction();
1282 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1283 visitOperandShadowInst(*CS.getInstruction());
1287 IRBuilder<> IRB(CS.getInstruction());
1289 DenseMap<Value *, Function *>::iterator i =
1290 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1291 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1292 Function *F = i->second;
1293 switch (DFSF.DFS.getWrapperKind(F)) {
1294 case DataFlowSanitizer::WK_Warning: {
1295 CS.setCalledFunction(F);
1296 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1297 IRB.CreateGlobalStringPtr(F->getName()));
1298 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1301 case DataFlowSanitizer::WK_Discard: {
1302 CS.setCalledFunction(F);
1303 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1306 case DataFlowSanitizer::WK_Functional: {
1307 CS.setCalledFunction(F);
1308 visitOperandShadowInst(*CS.getInstruction());
1311 case DataFlowSanitizer::WK_Custom: {
1312 // Don't try to handle invokes of custom functions, it's too complicated.
1313 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1315 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1316 FunctionType *FT = F->getFunctionType();
1317 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1318 std::string CustomFName = "__dfsw_";
1319 CustomFName += F->getName();
1321 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1322 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1323 CustomFn->copyAttributesFrom(F);
1325 // Custom functions returning non-void will write to the return label.
1326 if (!FT->getReturnType()->isVoidTy()) {
1327 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1328 DFSF.DFS.ReadOnlyNoneAttrs);
1332 std::vector<Value *> Args;
1334 CallSite::arg_iterator i = CS.arg_begin();
1335 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
1336 Type *T = (*i)->getType();
1337 FunctionType *ParamFT;
1338 if (isa<PointerType>(T) &&
1339 (ParamFT = dyn_cast<FunctionType>(
1340 cast<PointerType>(T)->getElementType()))) {
1341 std::string TName = "dfst";
1342 TName += utostr(FT->getNumParams() - n);
1344 TName += F->getName();
1345 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1348 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1355 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1356 Args.push_back(DFSF.getShadow(*i));
1358 if (!FT->getReturnType()->isVoidTy()) {
1359 if (!DFSF.LabelReturnAlloca) {
1360 DFSF.LabelReturnAlloca =
1361 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1362 DFSF.F->getEntryBlock().begin());
1364 Args.push_back(DFSF.LabelReturnAlloca);
1367 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1368 CustomCI->setCallingConv(CI->getCallingConv());
1369 CustomCI->setAttributes(CI->getAttributes());
1371 if (!FT->getReturnType()->isVoidTy()) {
1372 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1373 DFSF.setShadow(CustomCI, LabelLoad);
1376 CI->replaceAllUsesWith(CustomCI);
1377 CI->eraseFromParent();
1385 FunctionType *FT = cast<FunctionType>(
1386 CS.getCalledValue()->getType()->getPointerElementType());
1387 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1388 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1389 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1390 DFSF.getArgTLS(i, CS.getInstruction()));
1394 Instruction *Next = nullptr;
1395 if (!CS.getType()->isVoidTy()) {
1396 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1397 if (II->getNormalDest()->getSinglePredecessor()) {
1398 Next = II->getNormalDest()->begin();
1401 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1402 Next = NewBB->begin();
1405 Next = CS->getNextNode();
1408 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1409 IRBuilder<> NextIRB(Next);
1410 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1411 DFSF.SkipInsts.insert(LI);
1412 DFSF.setShadow(CS.getInstruction(), LI);
1413 DFSF.NonZeroChecks.insert(LI);
1417 // Do all instrumentation for IA_Args down here to defer tampering with the
1418 // CFG in a way that SplitEdge may be able to detect.
1419 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1420 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
1422 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1423 std::vector<Value *> Args;
1425 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1426 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1430 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1431 Args.push_back(DFSF.getShadow(*i));
1433 if (FT->isVarArg()) {
1434 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1435 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1436 AllocaInst *VarArgShadow =
1437 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1438 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1439 for (unsigned n = 0; i != e; ++i, ++n) {
1440 IRB.CreateStore(DFSF.getShadow(*i),
1441 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1447 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1448 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1451 NewCS = IRB.CreateCall(Func, Args);
1453 NewCS.setCallingConv(CS.getCallingConv());
1454 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1455 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1456 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1457 AttributeSet::ReturnIndex)));
1460 ExtractValueInst *ExVal =
1461 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1462 DFSF.SkipInsts.insert(ExVal);
1463 ExtractValueInst *ExShadow =
1464 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1465 DFSF.SkipInsts.insert(ExShadow);
1466 DFSF.setShadow(ExVal, ExShadow);
1467 DFSF.NonZeroChecks.insert(ExShadow);
1469 CS.getInstruction()->replaceAllUsesWith(ExVal);
1472 CS.getInstruction()->eraseFromParent();
1476 void DFSanVisitor::visitPHINode(PHINode &PN) {
1478 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1480 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1481 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1482 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1484 ShadowPN->addIncoming(UndefShadow, *i);
1487 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1488 DFSF.setShadow(&PN, ShadowPN);