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"
73 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
74 // alignment requirements provided by the input IR are correct. For example,
75 // if the input IR contains a load with alignment 8, this flag will cause
76 // the shadow load to have alignment 16. This flag is disabled by default as
77 // we have unfortunately encountered too much code (including Clang itself;
78 // see PR14291) which performs misaligned access.
79 static cl::opt<bool> ClPreserveAlignment(
80 "dfsan-preserve-alignment",
81 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
84 // The ABI list file controls how shadow parameters are passed. The pass treats
85 // every function labelled "uninstrumented" in the ABI list file as conforming
86 // to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
87 // additional annotations for those functions, a call to one of those functions
88 // will produce a warning message, as the labelling behaviour of the function is
89 // unknown. The other supported annotations are "functional" and "discard",
90 // which are described below under DataFlowSanitizer::WrapperKind.
91 static cl::opt<std::string> ClABIListFile(
93 cl::desc("File listing native ABI functions and how the pass treats them"),
96 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
97 // functions (see DataFlowSanitizer::InstrumentedABI below).
98 static cl::opt<bool> ClArgsABI(
100 cl::desc("Use the argument ABI rather than the TLS ABI"),
103 // Controls whether the pass includes or ignores the labels of pointers in load
105 static cl::opt<bool> ClCombinePointerLabelsOnLoad(
106 "dfsan-combine-pointer-labels-on-load",
107 cl::desc("Combine the label of the pointer with the label of the data when "
108 "loading from memory."),
109 cl::Hidden, cl::init(true));
111 // Controls whether the pass includes or ignores the labels of pointers in
112 // stores instructions.
113 static cl::opt<bool> ClCombinePointerLabelsOnStore(
114 "dfsan-combine-pointer-labels-on-store",
115 cl::desc("Combine the label of the pointer with the label of the data when "
116 "storing in memory."),
117 cl::Hidden, cl::init(false));
119 static cl::opt<bool> ClDebugNonzeroLabels(
120 "dfsan-debug-nonzero-labels",
121 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
122 "load or return with a nonzero label"),
127 StringRef GetGlobalTypeString(const GlobalValue &G) {
128 // Types of GlobalVariables are always pointer types.
129 Type *GType = G.getType()->getElementType();
130 // For now we support blacklisting struct types only.
131 if (StructType *SGType = dyn_cast<StructType>(GType)) {
132 if (!SGType->isLiteral())
133 return SGType->getName();
135 return "<unknown type>";
139 std::unique_ptr<SpecialCaseList> SCL;
142 DFSanABIList(std::unique_ptr<SpecialCaseList> SCL) : SCL(std::move(SCL)) {}
144 /// Returns whether either this function or its source file are listed in the
146 bool isIn(const Function &F, StringRef Category) const {
147 return isIn(*F.getParent(), Category) ||
148 SCL->inSection("fun", F.getName(), Category);
151 /// Returns whether this global alias is listed in the given category.
153 /// If GA aliases a function, the alias's name is matched as a function name
154 /// would be. Similarly, aliases of globals are matched like globals.
155 bool isIn(const GlobalAlias &GA, StringRef Category) const {
156 if (isIn(*GA.getParent(), Category))
159 if (isa<FunctionType>(GA.getType()->getElementType()))
160 return SCL->inSection("fun", GA.getName(), Category);
162 return SCL->inSection("global", GA.getName(), Category) ||
163 SCL->inSection("type", GetGlobalTypeString(GA), Category);
166 /// Returns whether this module is listed in the given category.
167 bool isIn(const Module &M, StringRef Category) const {
168 return SCL->inSection("src", M.getModuleIdentifier(), Category);
172 class DataFlowSanitizer : public ModulePass {
173 friend struct DFSanFunction;
174 friend class DFSanVisitor;
180 /// Which ABI should be used for instrumented functions?
181 enum InstrumentedABI {
182 /// Argument and return value labels are passed through additional
183 /// arguments and by modifying the return type.
186 /// Argument and return value labels are passed through TLS variables
187 /// __dfsan_arg_tls and __dfsan_retval_tls.
191 /// How should calls to uninstrumented functions be handled?
193 /// This function is present in an uninstrumented form but we don't know
194 /// how it should be handled. Print a warning and call the function anyway.
195 /// Don't label the return value.
198 /// This function does not write to (user-accessible) memory, and its return
199 /// value is unlabelled.
202 /// This function does not write to (user-accessible) memory, and the label
203 /// of its return value is the union of the label of its arguments.
206 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
207 /// where F is the name of the function. This function may wrap the
208 /// original function or provide its own implementation. This is similar to
209 /// the IA_Args ABI, except that IA_Args uses a struct return type to
210 /// pass the return value shadow in a register, while WK_Custom uses an
211 /// extra pointer argument to return the shadow. This allows the wrapped
212 /// form of the function type to be expressed in C.
216 const DataLayout *DL;
219 IntegerType *ShadowTy;
220 PointerType *ShadowPtrTy;
221 IntegerType *IntptrTy;
222 ConstantInt *ZeroShadow;
223 ConstantInt *ShadowPtrMask;
224 ConstantInt *ShadowPtrMul;
227 void *(*GetArgTLSPtr)();
228 void *(*GetRetvalTLSPtr)();
230 Constant *GetRetvalTLS;
231 FunctionType *DFSanUnionFnTy;
232 FunctionType *DFSanUnionLoadFnTy;
233 FunctionType *DFSanUnimplementedFnTy;
234 FunctionType *DFSanSetLabelFnTy;
235 FunctionType *DFSanNonzeroLabelFnTy;
236 Constant *DFSanUnionFn;
237 Constant *DFSanCheckedUnionFn;
238 Constant *DFSanUnionLoadFn;
239 Constant *DFSanUnimplementedFn;
240 Constant *DFSanSetLabelFn;
241 Constant *DFSanNonzeroLabelFn;
242 MDNode *ColdCallWeights;
243 DFSanABIList ABIList;
244 DenseMap<Value *, Function *> UnwrappedFnMap;
245 AttributeSet ReadOnlyNoneAttrs;
247 Value *getShadowAddress(Value *Addr, Instruction *Pos);
248 bool isInstrumented(const Function *F);
249 bool isInstrumented(const GlobalAlias *GA);
250 FunctionType *getArgsFunctionType(FunctionType *T);
251 FunctionType *getTrampolineFunctionType(FunctionType *T);
252 FunctionType *getCustomFunctionType(FunctionType *T);
253 InstrumentedABI getInstrumentedABI();
254 WrapperKind getWrapperKind(Function *F);
255 void addGlobalNamePrefix(GlobalValue *GV);
256 Function *buildWrapperFunction(Function *F, StringRef NewFName,
257 GlobalValue::LinkageTypes NewFLink,
258 FunctionType *NewFT);
259 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
262 DataFlowSanitizer(StringRef ABIListFile = StringRef(),
263 void *(*getArgTLS)() = nullptr,
264 void *(*getRetValTLS)() = nullptr);
266 bool doInitialization(Module &M) override;
267 bool runOnModule(Module &M) override;
270 struct DFSanFunction {
271 DataFlowSanitizer &DFS;
274 DataFlowSanitizer::InstrumentedABI IA;
278 AllocaInst *LabelReturnAlloca;
279 DenseMap<Value *, Value *> ValShadowMap;
280 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
281 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
282 DenseSet<Instruction *> SkipInsts;
283 std::vector<Value *> NonZeroChecks;
286 struct CachedCombinedShadow {
290 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
291 CachedCombinedShadows;
292 DenseMap<Value *, std::set<Value *>> ShadowElements;
294 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
295 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
296 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
297 LabelReturnAlloca(nullptr) {
299 // FIXME: Need to track down the register allocator issue which causes poor
300 // performance in pathological cases with large numbers of basic blocks.
301 AvoidNewBlocks = F->size() > 1000;
303 Value *getArgTLSPtr();
304 Value *getArgTLS(unsigned Index, Instruction *Pos);
305 Value *getRetvalTLS();
306 Value *getShadow(Value *V);
307 void setShadow(Instruction *I, Value *Shadow);
308 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
309 Value *combineOperandShadows(Instruction *Inst);
310 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
312 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
316 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
319 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
321 void visitOperandShadowInst(Instruction &I);
323 void visitBinaryOperator(BinaryOperator &BO);
324 void visitCastInst(CastInst &CI);
325 void visitCmpInst(CmpInst &CI);
326 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
327 void visitLoadInst(LoadInst &LI);
328 void visitStoreInst(StoreInst &SI);
329 void visitReturnInst(ReturnInst &RI);
330 void visitCallSite(CallSite CS);
331 void visitPHINode(PHINode &PN);
332 void visitExtractElementInst(ExtractElementInst &I);
333 void visitInsertElementInst(InsertElementInst &I);
334 void visitShuffleVectorInst(ShuffleVectorInst &I);
335 void visitExtractValueInst(ExtractValueInst &I);
336 void visitInsertValueInst(InsertValueInst &I);
337 void visitAllocaInst(AllocaInst &I);
338 void visitSelectInst(SelectInst &I);
339 void visitMemSetInst(MemSetInst &I);
340 void visitMemTransferInst(MemTransferInst &I);
345 char DataFlowSanitizer::ID;
346 INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
347 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
349 ModulePass *llvm::createDataFlowSanitizerPass(StringRef ABIListFile,
350 void *(*getArgTLS)(),
351 void *(*getRetValTLS)()) {
352 return new DataFlowSanitizer(ABIListFile, getArgTLS, getRetValTLS);
355 DataFlowSanitizer::DataFlowSanitizer(StringRef ABIListFile,
356 void *(*getArgTLS)(),
357 void *(*getRetValTLS)())
358 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
359 ABIList(SpecialCaseList::createOrDie(ABIListFile.empty() ? ClABIListFile
363 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
364 llvm::SmallVector<Type *, 4> ArgTypes;
365 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
366 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
367 ArgTypes.push_back(ShadowTy);
369 ArgTypes.push_back(ShadowPtrTy);
370 Type *RetType = T->getReturnType();
371 if (!RetType->isVoidTy())
372 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
373 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
376 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
377 assert(!T->isVarArg());
378 llvm::SmallVector<Type *, 4> ArgTypes;
379 ArgTypes.push_back(T->getPointerTo());
380 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
381 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
382 ArgTypes.push_back(ShadowTy);
383 Type *RetType = T->getReturnType();
384 if (!RetType->isVoidTy())
385 ArgTypes.push_back(ShadowPtrTy);
386 return FunctionType::get(T->getReturnType(), ArgTypes, false);
389 FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
391 // The labels are passed after all the arguments so there is no need to
392 // adjust the function type.
396 llvm::SmallVector<Type *, 4> ArgTypes;
397 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
400 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
401 *i)->getElementType()))) {
402 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
403 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
405 ArgTypes.push_back(*i);
408 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
409 ArgTypes.push_back(ShadowTy);
410 Type *RetType = T->getReturnType();
411 if (!RetType->isVoidTy())
412 ArgTypes.push_back(ShadowPtrTy);
413 return FunctionType::get(T->getReturnType(), ArgTypes, false);
416 bool DataFlowSanitizer::doInitialization(Module &M) {
417 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
419 report_fatal_error("data layout missing");
420 DL = &DLP->getDataLayout();
423 Ctx = &M.getContext();
424 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
425 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
426 IntptrTy = DL->getIntPtrType(*Ctx);
427 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
428 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
429 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
431 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
433 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
434 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
436 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
437 DFSanUnimplementedFnTy = FunctionType::get(
438 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
439 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
440 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
441 DFSanSetLabelArgs, /*isVarArg=*/false);
442 DFSanNonzeroLabelFnTy = FunctionType::get(
443 Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
446 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
448 GetArgTLS = ConstantExpr::getIntToPtr(
449 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
450 PointerType::getUnqual(
451 FunctionType::get(PointerType::getUnqual(ArgTLSTy),
454 if (GetRetvalTLSPtr) {
456 GetRetvalTLS = ConstantExpr::getIntToPtr(
457 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
458 PointerType::getUnqual(
459 FunctionType::get(PointerType::getUnqual(ShadowTy),
463 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
467 bool DataFlowSanitizer::isInstrumented(const Function *F) {
468 return !ABIList.isIn(*F, "uninstrumented");
471 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
472 return !ABIList.isIn(*GA, "uninstrumented");
475 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
476 return ClArgsABI ? IA_Args : IA_TLS;
479 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
480 if (ABIList.isIn(*F, "functional"))
481 return WK_Functional;
482 if (ABIList.isIn(*F, "discard"))
484 if (ABIList.isIn(*F, "custom"))
490 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
491 std::string GVName = GV->getName(), Prefix = "dfs$";
492 GV->setName(Prefix + GVName);
494 // Try to change the name of the function in module inline asm. We only do
495 // this for specific asm directives, currently only ".symver", to try to avoid
496 // corrupting asm which happens to contain the symbol name as a substring.
497 // Note that the substitution for .symver assumes that the versioned symbol
498 // also has an instrumented name.
499 std::string Asm = GV->getParent()->getModuleInlineAsm();
500 std::string SearchStr = ".symver " + GVName + ",";
501 size_t Pos = Asm.find(SearchStr);
502 if (Pos != std::string::npos) {
503 Asm.replace(Pos, SearchStr.size(),
504 ".symver " + Prefix + GVName + "," + Prefix);
505 GV->getParent()->setModuleInlineAsm(Asm);
510 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
511 GlobalValue::LinkageTypes NewFLink,
512 FunctionType *NewFT) {
513 FunctionType *FT = F->getFunctionType();
514 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
516 NewF->copyAttributesFrom(F);
517 NewF->removeAttributes(
518 AttributeSet::ReturnIndex,
519 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
520 AttributeSet::ReturnIndex));
522 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
523 std::vector<Value *> Args;
524 unsigned n = FT->getNumParams();
525 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
526 Args.push_back(&*ai);
527 CallInst *CI = CallInst::Create(F, Args, "", BB);
528 if (FT->getReturnType()->isVoidTy())
529 ReturnInst::Create(*Ctx, BB);
531 ReturnInst::Create(*Ctx, CI, BB);
536 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
538 FunctionType *FTT = getTrampolineFunctionType(FT);
539 Constant *C = Mod->getOrInsertFunction(FName, FTT);
540 Function *F = dyn_cast<Function>(C);
541 if (F && F->isDeclaration()) {
542 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
543 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
544 std::vector<Value *> Args;
545 Function::arg_iterator AI = F->arg_begin(); ++AI;
546 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
547 Args.push_back(&*AI);
549 CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
551 if (FT->getReturnType()->isVoidTy())
552 RI = ReturnInst::Create(*Ctx, BB);
554 RI = ReturnInst::Create(*Ctx, CI, BB);
556 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
557 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
558 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
559 DFSF.ValShadowMap[ValAI] = ShadowAI;
560 DFSanVisitor(DFSF).visitCallInst(*CI);
561 if (!FT->getReturnType()->isVoidTy())
562 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
563 &F->getArgumentList().back(), RI);
569 bool DataFlowSanitizer::runOnModule(Module &M) {
573 if (ABIList.isIn(M, "skip"))
577 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
578 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
579 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
580 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
582 if (!GetRetvalTLSPtr) {
583 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
584 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
585 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
588 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
589 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
590 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
591 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
592 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
593 F->addAttribute(1, Attribute::ZExt);
594 F->addAttribute(2, Attribute::ZExt);
596 DFSanCheckedUnionFn = Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy);
597 if (Function *F = dyn_cast<Function>(DFSanCheckedUnionFn)) {
598 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
599 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
600 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
601 F->addAttribute(1, Attribute::ZExt);
602 F->addAttribute(2, Attribute::ZExt);
605 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
606 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
607 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
608 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
609 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
611 DFSanUnimplementedFn =
612 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
614 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
615 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
616 F->addAttribute(1, Attribute::ZExt);
618 DFSanNonzeroLabelFn =
619 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
621 std::vector<Function *> FnsToInstrument;
622 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
623 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
624 if (!i->isIntrinsic() &&
626 i != DFSanCheckedUnionFn &&
627 i != DFSanUnionLoadFn &&
628 i != DFSanUnimplementedFn &&
629 i != DFSanSetLabelFn &&
630 i != DFSanNonzeroLabelFn)
631 FnsToInstrument.push_back(&*i);
634 // Give function aliases prefixes when necessary, and build wrappers where the
635 // instrumentedness is inconsistent.
636 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
637 GlobalAlias *GA = &*i;
639 // Don't stop on weak. We assume people aren't playing games with the
640 // instrumentedness of overridden weak aliases.
641 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
642 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
643 if (GAInst && FInst) {
644 addGlobalNamePrefix(GA);
645 } else if (GAInst != FInst) {
646 // Non-instrumented alias of an instrumented function, or vice versa.
647 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
648 // below will take care of instrumenting it.
650 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
651 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
653 GA->eraseFromParent();
654 FnsToInstrument.push_back(NewF);
660 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
661 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
663 // First, change the ABI of every function in the module. ABI-listed
664 // functions keep their original ABI and get a wrapper function.
665 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
666 e = FnsToInstrument.end();
669 FunctionType *FT = F.getFunctionType();
671 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
672 FT->getReturnType()->isVoidTy());
674 if (isInstrumented(&F)) {
675 // Instrumented functions get a 'dfs$' prefix. This allows us to more
676 // easily identify cases of mismatching ABIs.
677 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
678 FunctionType *NewFT = getArgsFunctionType(FT);
679 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
680 NewF->copyAttributesFrom(&F);
681 NewF->removeAttributes(
682 AttributeSet::ReturnIndex,
683 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
684 AttributeSet::ReturnIndex));
685 for (Function::arg_iterator FArg = F.arg_begin(),
686 NewFArg = NewF->arg_begin(),
687 FArgEnd = F.arg_end();
688 FArg != FArgEnd; ++FArg, ++NewFArg) {
689 FArg->replaceAllUsesWith(NewFArg);
691 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
693 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
695 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
698 BA->replaceAllUsesWith(
699 BlockAddress::get(NewF, BA->getBasicBlock()));
703 F.replaceAllUsesWith(
704 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
708 addGlobalNamePrefix(NewF);
710 addGlobalNamePrefix(&F);
712 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
713 // Build a wrapper function for F. The wrapper simply calls F, and is
714 // added to FnsToInstrument so that any instrumentation according to its
715 // WrapperKind is done in the second pass below.
716 FunctionType *NewFT = getInstrumentedABI() == IA_Args
717 ? getArgsFunctionType(FT)
719 Function *NewF = buildWrapperFunction(
720 &F, std::string("dfsw$") + std::string(F.getName()),
721 GlobalValue::LinkOnceODRLinkage, NewFT);
722 if (getInstrumentedABI() == IA_TLS)
723 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
725 Value *WrappedFnCst =
726 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
727 F.replaceAllUsesWith(WrappedFnCst);
728 UnwrappedFnMap[WrappedFnCst] = &F;
731 if (!F.isDeclaration()) {
732 // This function is probably defining an interposition of an
733 // uninstrumented function and hence needs to keep the original ABI.
734 // But any functions it may call need to use the instrumented ABI, so
735 // we instrument it in a mode which preserves the original ABI.
736 FnsWithNativeABI.insert(&F);
738 // This code needs to rebuild the iterators, as they may be invalidated
739 // by the push_back, taking care that the new range does not include
740 // any functions added by this code.
741 size_t N = i - FnsToInstrument.begin(),
742 Count = e - FnsToInstrument.begin();
743 FnsToInstrument.push_back(&F);
744 i = FnsToInstrument.begin() + N;
745 e = FnsToInstrument.begin() + Count;
747 // Hopefully, nobody will try to indirectly call a vararg
749 } else if (FT->isVarArg()) {
750 UnwrappedFnMap[&F] = &F;
755 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
756 e = FnsToInstrument.end();
758 if (!*i || (*i)->isDeclaration())
761 removeUnreachableBlocks(**i);
763 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
765 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
766 // Build a copy of the list before iterating over it.
767 llvm::SmallVector<BasicBlock *, 4> BBList(
768 depth_first(&(*i)->getEntryBlock()));
770 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
773 Instruction *Inst = &(*i)->front();
775 // DFSanVisitor may split the current basic block, changing the current
776 // instruction's next pointer and moving the next instruction to the
777 // tail block from which we should continue.
778 Instruction *Next = Inst->getNextNode();
779 // DFSanVisitor may delete Inst, so keep track of whether it was a
781 bool IsTerminator = isa<TerminatorInst>(Inst);
782 if (!DFSF.SkipInsts.count(Inst))
783 DFSanVisitor(DFSF).visit(Inst);
790 // We will not necessarily be able to compute the shadow for every phi node
791 // until we have visited every block. Therefore, the code that handles phi
792 // nodes adds them to the PHIFixups list so that they can be properly
794 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
795 i = DFSF.PHIFixups.begin(),
796 e = DFSF.PHIFixups.end();
798 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
800 i->second->setIncomingValue(
801 val, DFSF.getShadow(i->first->getIncomingValue(val)));
805 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
806 // places (i.e. instructions in basic blocks we haven't even begun visiting
807 // yet). To make our life easier, do this work in a pass after the main
809 if (ClDebugNonzeroLabels) {
810 for (Value *V : DFSF.NonZeroChecks) {
812 if (Instruction *I = dyn_cast<Instruction>(V))
813 Pos = I->getNextNode();
815 Pos = DFSF.F->getEntryBlock().begin();
816 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
817 Pos = Pos->getNextNode();
818 IRBuilder<> IRB(Pos);
819 Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
820 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
821 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
822 IRBuilder<> ThenIRB(BI);
823 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
831 Value *DFSanFunction::getArgTLSPtr() {
835 return ArgTLSPtr = DFS.ArgTLS;
837 IRBuilder<> IRB(F->getEntryBlock().begin());
838 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
841 Value *DFSanFunction::getRetvalTLS() {
845 return RetvalTLSPtr = DFS.RetvalTLS;
847 IRBuilder<> IRB(F->getEntryBlock().begin());
848 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
851 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
852 IRBuilder<> IRB(Pos);
853 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
856 Value *DFSanFunction::getShadow(Value *V) {
857 if (!isa<Argument>(V) && !isa<Instruction>(V))
858 return DFS.ZeroShadow;
859 Value *&Shadow = ValShadowMap[V];
861 if (Argument *A = dyn_cast<Argument>(V)) {
863 return DFS.ZeroShadow;
865 case DataFlowSanitizer::IA_TLS: {
866 Value *ArgTLSPtr = getArgTLSPtr();
867 Instruction *ArgTLSPos =
868 DFS.ArgTLS ? &*F->getEntryBlock().begin()
869 : cast<Instruction>(ArgTLSPtr)->getNextNode();
870 IRBuilder<> IRB(ArgTLSPos);
871 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
874 case DataFlowSanitizer::IA_Args: {
875 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
876 Function::arg_iterator i = F->arg_begin();
880 assert(Shadow->getType() == DFS.ShadowTy);
884 NonZeroChecks.push_back(Shadow);
886 Shadow = DFS.ZeroShadow;
892 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
893 assert(!ValShadowMap.count(I));
894 assert(Shadow->getType() == DFS.ShadowTy);
895 ValShadowMap[I] = Shadow;
898 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
899 assert(Addr != RetvalTLS && "Reinstrumenting?");
900 IRBuilder<> IRB(Pos);
901 return IRB.CreateIntToPtr(
903 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
908 // Generates IR to compute the union of the two given shadows, inserting it
909 // before Pos. Returns the computed union Value.
910 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
911 if (V1 == DFS.ZeroShadow)
913 if (V2 == DFS.ZeroShadow)
918 auto V1Elems = ShadowElements.find(V1);
919 auto V2Elems = ShadowElements.find(V2);
920 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
921 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
922 V2Elems->second.begin(), V2Elems->second.end())) {
924 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
925 V1Elems->second.begin(), V1Elems->second.end())) {
928 } else if (V1Elems != ShadowElements.end()) {
929 if (V1Elems->second.count(V2))
931 } else if (V2Elems != ShadowElements.end()) {
932 if (V2Elems->second.count(V1))
936 auto Key = std::make_pair(V1, V2);
938 std::swap(Key.first, Key.second);
939 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
940 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
943 IRBuilder<> IRB(Pos);
944 if (AvoidNewBlocks) {
945 CallInst *Call = IRB.CreateCall2(DFS.DFSanCheckedUnionFn, V1, V2);
946 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
947 Call->addAttribute(1, Attribute::ZExt);
948 Call->addAttribute(2, Attribute::ZExt);
950 CCS.Block = Pos->getParent();
953 BasicBlock *Head = Pos->getParent();
954 Value *Ne = IRB.CreateICmpNE(V1, V2);
955 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
956 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
957 IRBuilder<> ThenIRB(BI);
958 CallInst *Call = ThenIRB.CreateCall2(DFS.DFSanUnionFn, V1, V2);
959 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
960 Call->addAttribute(1, Attribute::ZExt);
961 Call->addAttribute(2, Attribute::ZExt);
963 BasicBlock *Tail = BI->getSuccessor(0);
964 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", Tail->begin());
965 Phi->addIncoming(Call, Call->getParent());
966 Phi->addIncoming(V1, Head);
972 std::set<Value *> UnionElems;
973 if (V1Elems != ShadowElements.end()) {
974 UnionElems = V1Elems->second;
976 UnionElems.insert(V1);
978 if (V2Elems != ShadowElements.end()) {
979 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
981 UnionElems.insert(V2);
983 ShadowElements[CCS.Shadow] = std::move(UnionElems);
988 // A convenience function which folds the shadows of each of the operands
989 // of the provided instruction Inst, inserting the IR before Inst. Returns
990 // the computed union Value.
991 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
992 if (Inst->getNumOperands() == 0)
993 return DFS.ZeroShadow;
995 Value *Shadow = getShadow(Inst->getOperand(0));
996 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
997 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
1002 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1003 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1004 DFSF.setShadow(&I, CombinedShadow);
1007 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1008 // Addr has alignment Align, and take the union of each of those shadows.
1009 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1011 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1012 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1013 AllocaShadowMap.find(AI);
1014 if (i != AllocaShadowMap.end()) {
1015 IRBuilder<> IRB(Pos);
1016 return IRB.CreateLoad(i->second);
1020 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1021 SmallVector<Value *, 2> Objs;
1022 GetUnderlyingObjects(Addr, Objs, DFS.DL);
1023 bool AllConstants = true;
1024 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
1026 if (isa<Function>(*i) || isa<BlockAddress>(*i))
1028 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
1031 AllConstants = false;
1035 return DFS.ZeroShadow;
1037 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1040 return DFS.ZeroShadow;
1042 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1043 LI->setAlignment(ShadowAlign);
1047 IRBuilder<> IRB(Pos);
1048 Value *ShadowAddr1 =
1049 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
1050 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1051 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
1054 if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
1055 // Fast path for the common case where each byte has identical shadow: load
1056 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1057 // shadow is non-equal.
1058 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1059 IRBuilder<> FallbackIRB(FallbackBB);
1060 CallInst *FallbackCall = FallbackIRB.CreateCall2(
1061 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1062 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1064 // Compare each of the shadows stored in the loaded 64 bits to each other,
1065 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1066 IRBuilder<> IRB(Pos);
1068 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1069 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1070 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1071 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1072 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1073 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1074 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1076 BasicBlock *Head = Pos->getParent();
1077 BasicBlock *Tail = Head->splitBasicBlock(Pos);
1079 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1080 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1082 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1083 for (auto Child : Children)
1084 DT.changeImmediateDominator(Child, NewNode);
1087 // In the following code LastBr will refer to the previous basic block's
1088 // conditional branch instruction, whose true successor is fixed up to point
1089 // to the next block during the loop below or to the tail after the final
1091 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1092 ReplaceInstWithInst(Head->getTerminator(), LastBr);
1093 DT.addNewBlock(FallbackBB, Head);
1095 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1096 Ofs += 64 / DFS.ShadowWidth) {
1097 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
1098 DT.addNewBlock(NextBB, LastBr->getParent());
1099 IRBuilder<> NextIRB(NextBB);
1100 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
1101 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1102 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1103 LastBr->setSuccessor(0, NextBB);
1104 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1107 LastBr->setSuccessor(0, Tail);
1108 FallbackIRB.CreateBr(Tail);
1109 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1110 Shadow->addIncoming(FallbackCall, FallbackBB);
1111 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1115 IRBuilder<> IRB(Pos);
1116 CallInst *FallbackCall = IRB.CreateCall2(
1117 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1118 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1119 return FallbackCall;
1122 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1123 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
1125 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1130 if (ClPreserveAlignment) {
1131 Align = LI.getAlignment();
1133 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
1137 IRBuilder<> IRB(&LI);
1138 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1139 if (ClCombinePointerLabelsOnLoad) {
1140 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
1141 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
1143 if (Shadow != DFSF.DFS.ZeroShadow)
1144 DFSF.NonZeroChecks.push_back(Shadow);
1146 DFSF.setShadow(&LI, Shadow);
1149 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1150 Value *Shadow, Instruction *Pos) {
1151 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1152 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1153 AllocaShadowMap.find(AI);
1154 if (i != AllocaShadowMap.end()) {
1155 IRBuilder<> IRB(Pos);
1156 IRB.CreateStore(Shadow, i->second);
1161 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1162 IRBuilder<> IRB(Pos);
1163 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1164 if (Shadow == DFS.ZeroShadow) {
1165 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1166 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1167 Value *ExtShadowAddr =
1168 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1169 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1173 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1174 uint64_t Offset = 0;
1175 if (Size >= ShadowVecSize) {
1176 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1177 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1178 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1179 ShadowVec = IRB.CreateInsertElement(
1180 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1182 Value *ShadowVecAddr =
1183 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1185 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
1186 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1187 Size -= ShadowVecSize;
1189 } while (Size >= ShadowVecSize);
1190 Offset *= ShadowVecSize;
1193 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
1194 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1200 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1202 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
1207 if (ClPreserveAlignment) {
1208 Align = SI.getAlignment();
1210 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
1215 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1216 if (ClCombinePointerLabelsOnStore) {
1217 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
1218 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
1220 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
1223 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1224 visitOperandShadowInst(BO);
1227 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1229 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1231 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1232 visitOperandShadowInst(GEPI);
1235 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1236 visitOperandShadowInst(I);
1239 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1240 visitOperandShadowInst(I);
1243 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1244 visitOperandShadowInst(I);
1247 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1248 visitOperandShadowInst(I);
1251 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1252 visitOperandShadowInst(I);
1255 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1256 bool AllLoadsStores = true;
1257 for (User *U : I.users()) {
1258 if (isa<LoadInst>(U))
1261 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1262 if (SI->getPointerOperand() == &I)
1266 AllLoadsStores = false;
1269 if (AllLoadsStores) {
1270 IRBuilder<> IRB(&I);
1271 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1273 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1276 void DFSanVisitor::visitSelectInst(SelectInst &I) {
1277 Value *CondShadow = DFSF.getShadow(I.getCondition());
1278 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1279 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1281 if (isa<VectorType>(I.getCondition()->getType())) {
1284 DFSF.combineShadows(
1285 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
1288 if (TrueShadow == FalseShadow) {
1289 ShadowSel = TrueShadow;
1292 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1294 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
1298 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1299 IRBuilder<> IRB(&I);
1300 Value *ValShadow = DFSF.getShadow(I.getValue());
1302 DFSF.DFS.DFSanSetLabelFn, ValShadow,
1303 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1304 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1307 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1308 IRBuilder<> IRB(&I);
1309 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1310 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1311 Value *LenShadow = IRB.CreateMul(
1313 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1315 if (ClPreserveAlignment) {
1316 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1317 ConstantInt::get(I.getAlignmentCst()->getType(),
1318 DFSF.DFS.ShadowWidth / 8));
1320 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1321 DFSF.DFS.ShadowWidth / 8);
1323 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1324 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1325 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1326 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1327 AlignShadow, I.getVolatileCst());
1330 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
1331 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
1333 case DataFlowSanitizer::IA_TLS: {
1334 Value *S = DFSF.getShadow(RI.getReturnValue());
1335 IRBuilder<> IRB(&RI);
1336 IRB.CreateStore(S, DFSF.getRetvalTLS());
1339 case DataFlowSanitizer::IA_Args: {
1340 IRBuilder<> IRB(&RI);
1341 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1343 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1345 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1346 RI.setOperand(0, InsShadow);
1353 void DFSanVisitor::visitCallSite(CallSite CS) {
1354 Function *F = CS.getCalledFunction();
1355 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1356 visitOperandShadowInst(*CS.getInstruction());
1360 assert(!(cast<FunctionType>(
1361 CS.getCalledValue()->getType()->getPointerElementType())->isVarArg() &&
1362 dyn_cast<InvokeInst>(CS.getInstruction())));
1364 IRBuilder<> IRB(CS.getInstruction());
1366 DenseMap<Value *, Function *>::iterator i =
1367 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1368 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1369 Function *F = i->second;
1370 switch (DFSF.DFS.getWrapperKind(F)) {
1371 case DataFlowSanitizer::WK_Warning: {
1372 CS.setCalledFunction(F);
1373 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1374 IRB.CreateGlobalStringPtr(F->getName()));
1375 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1378 case DataFlowSanitizer::WK_Discard: {
1379 CS.setCalledFunction(F);
1380 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1383 case DataFlowSanitizer::WK_Functional: {
1384 CS.setCalledFunction(F);
1385 visitOperandShadowInst(*CS.getInstruction());
1388 case DataFlowSanitizer::WK_Custom: {
1389 // Don't try to handle invokes of custom functions, it's too complicated.
1390 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1392 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1393 FunctionType *FT = F->getFunctionType();
1394 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1395 std::string CustomFName = "__dfsw_";
1396 CustomFName += F->getName();
1398 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1399 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1400 CustomFn->copyAttributesFrom(F);
1402 // Custom functions returning non-void will write to the return label.
1403 if (!FT->getReturnType()->isVoidTy()) {
1404 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1405 DFSF.DFS.ReadOnlyNoneAttrs);
1409 std::vector<Value *> Args;
1411 CallSite::arg_iterator i = CS.arg_begin();
1412 for (unsigned n = CS.arg_size(); n != 0; ++i, --n) {
1413 Type *T = (*i)->getType();
1414 FunctionType *ParamFT;
1415 if (isa<PointerType>(T) &&
1416 (ParamFT = dyn_cast<FunctionType>(
1417 cast<PointerType>(T)->getElementType()))) {
1418 std::string TName = "dfst";
1419 TName += utostr(FT->getNumParams() - n);
1421 TName += F->getName();
1422 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1425 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1432 for (unsigned n = CS.arg_size(); n != 0; ++i, --n)
1433 Args.push_back(DFSF.getShadow(*i));
1435 if (!FT->getReturnType()->isVoidTy()) {
1436 if (!DFSF.LabelReturnAlloca) {
1437 DFSF.LabelReturnAlloca =
1438 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1439 DFSF.F->getEntryBlock().begin());
1441 Args.push_back(DFSF.LabelReturnAlloca);
1444 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1445 CustomCI->setCallingConv(CI->getCallingConv());
1446 CustomCI->setAttributes(CI->getAttributes());
1448 if (!FT->getReturnType()->isVoidTy()) {
1449 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1450 DFSF.setShadow(CustomCI, LabelLoad);
1453 CI->replaceAllUsesWith(CustomCI);
1454 CI->eraseFromParent();
1462 FunctionType *FT = cast<FunctionType>(
1463 CS.getCalledValue()->getType()->getPointerElementType());
1464 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1465 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1466 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1467 DFSF.getArgTLS(i, CS.getInstruction()));
1471 Instruction *Next = nullptr;
1472 if (!CS.getType()->isVoidTy()) {
1473 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1474 if (II->getNormalDest()->getSinglePredecessor()) {
1475 Next = II->getNormalDest()->begin();
1478 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1479 Next = NewBB->begin();
1482 Next = CS->getNextNode();
1485 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1486 IRBuilder<> NextIRB(Next);
1487 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1488 DFSF.SkipInsts.insert(LI);
1489 DFSF.setShadow(CS.getInstruction(), LI);
1490 DFSF.NonZeroChecks.push_back(LI);
1494 // Do all instrumentation for IA_Args down here to defer tampering with the
1495 // CFG in a way that SplitEdge may be able to detect.
1496 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1497 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
1499 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1500 std::vector<Value *> Args;
1502 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1503 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1507 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1508 Args.push_back(DFSF.getShadow(*i));
1510 if (FT->isVarArg()) {
1511 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1512 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1513 AllocaInst *VarArgShadow =
1514 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1515 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1516 for (unsigned n = 0; i != e; ++i, ++n) {
1517 IRB.CreateStore(DFSF.getShadow(*i),
1518 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1524 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1525 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1528 NewCS = IRB.CreateCall(Func, Args);
1530 NewCS.setCallingConv(CS.getCallingConv());
1531 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1532 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1533 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1534 AttributeSet::ReturnIndex)));
1537 ExtractValueInst *ExVal =
1538 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1539 DFSF.SkipInsts.insert(ExVal);
1540 ExtractValueInst *ExShadow =
1541 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1542 DFSF.SkipInsts.insert(ExShadow);
1543 DFSF.setShadow(ExVal, ExShadow);
1544 DFSF.NonZeroChecks.push_back(ExShadow);
1546 CS.getInstruction()->replaceAllUsesWith(ExVal);
1549 CS.getInstruction()->eraseFromParent();
1553 void DFSanVisitor::visitPHINode(PHINode &PN) {
1555 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1557 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1558 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1559 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1561 ShadowPN->addIncoming(UndefShadow, *i);
1564 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1565 DFSF.setShadow(&PN, ShadowPN);