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(SpecialCaseList *SCL) : SCL(SCL) {}
144 /// Returns whether either this function or its source file are listed in the
146 bool isIn(const Function &F, const 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, const 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, const 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 *DFSanUnionLoadFn;
238 Constant *DFSanUnimplementedFn;
239 Constant *DFSanSetLabelFn;
240 Constant *DFSanNonzeroLabelFn;
241 MDNode *ColdCallWeights;
242 DFSanABIList ABIList;
243 DenseMap<Value *, Function *> UnwrappedFnMap;
244 AttributeSet ReadOnlyNoneAttrs;
246 Value *getShadowAddress(Value *Addr, Instruction *Pos);
247 bool isInstrumented(const Function *F);
248 bool isInstrumented(const GlobalAlias *GA);
249 FunctionType *getArgsFunctionType(FunctionType *T);
250 FunctionType *getTrampolineFunctionType(FunctionType *T);
251 FunctionType *getCustomFunctionType(FunctionType *T);
252 InstrumentedABI getInstrumentedABI();
253 WrapperKind getWrapperKind(Function *F);
254 void addGlobalNamePrefix(GlobalValue *GV);
255 Function *buildWrapperFunction(Function *F, StringRef NewFName,
256 GlobalValue::LinkageTypes NewFLink,
257 FunctionType *NewFT);
258 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
261 DataFlowSanitizer(StringRef ABIListFile = StringRef(),
262 void *(*getArgTLS)() = nullptr,
263 void *(*getRetValTLS)() = nullptr);
265 bool doInitialization(Module &M) override;
266 bool runOnModule(Module &M) override;
269 struct DFSanFunction {
270 DataFlowSanitizer &DFS;
273 DataFlowSanitizer::InstrumentedABI IA;
277 AllocaInst *LabelReturnAlloca;
278 DenseMap<Value *, Value *> ValShadowMap;
279 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
280 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
281 DenseSet<Instruction *> SkipInsts;
282 DenseSet<Value *> NonZeroChecks;
284 struct CachedCombinedShadow {
288 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
289 CachedCombinedShadows;
290 DenseMap<Value *, std::set<Value *>> ShadowElements;
292 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
293 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
294 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
295 LabelReturnAlloca(nullptr) {
298 Value *getArgTLSPtr();
299 Value *getArgTLS(unsigned Index, Instruction *Pos);
300 Value *getRetvalTLS();
301 Value *getShadow(Value *V);
302 void setShadow(Instruction *I, Value *Shadow);
303 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
304 Value *combineOperandShadows(Instruction *Inst);
305 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
307 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
311 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
314 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
316 void visitOperandShadowInst(Instruction &I);
318 void visitBinaryOperator(BinaryOperator &BO);
319 void visitCastInst(CastInst &CI);
320 void visitCmpInst(CmpInst &CI);
321 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
322 void visitLoadInst(LoadInst &LI);
323 void visitStoreInst(StoreInst &SI);
324 void visitReturnInst(ReturnInst &RI);
325 void visitCallSite(CallSite CS);
326 void visitPHINode(PHINode &PN);
327 void visitExtractElementInst(ExtractElementInst &I);
328 void visitInsertElementInst(InsertElementInst &I);
329 void visitShuffleVectorInst(ShuffleVectorInst &I);
330 void visitExtractValueInst(ExtractValueInst &I);
331 void visitInsertValueInst(InsertValueInst &I);
332 void visitAllocaInst(AllocaInst &I);
333 void visitSelectInst(SelectInst &I);
334 void visitMemSetInst(MemSetInst &I);
335 void visitMemTransferInst(MemTransferInst &I);
340 char DataFlowSanitizer::ID;
341 INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
342 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
344 ModulePass *llvm::createDataFlowSanitizerPass(StringRef ABIListFile,
345 void *(*getArgTLS)(),
346 void *(*getRetValTLS)()) {
347 return new DataFlowSanitizer(ABIListFile, getArgTLS, getRetValTLS);
350 DataFlowSanitizer::DataFlowSanitizer(StringRef ABIListFile,
351 void *(*getArgTLS)(),
352 void *(*getRetValTLS)())
353 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
354 ABIList(SpecialCaseList::createOrDie(ABIListFile.empty() ? ClABIListFile
358 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
359 llvm::SmallVector<Type *, 4> ArgTypes;
360 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
361 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
362 ArgTypes.push_back(ShadowTy);
364 ArgTypes.push_back(ShadowPtrTy);
365 Type *RetType = T->getReturnType();
366 if (!RetType->isVoidTy())
367 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
368 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
371 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
372 assert(!T->isVarArg());
373 llvm::SmallVector<Type *, 4> ArgTypes;
374 ArgTypes.push_back(T->getPointerTo());
375 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
376 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
377 ArgTypes.push_back(ShadowTy);
378 Type *RetType = T->getReturnType();
379 if (!RetType->isVoidTy())
380 ArgTypes.push_back(ShadowPtrTy);
381 return FunctionType::get(T->getReturnType(), ArgTypes, false);
384 FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
385 assert(!T->isVarArg());
386 llvm::SmallVector<Type *, 4> ArgTypes;
387 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
390 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
391 *i)->getElementType()))) {
392 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
393 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
395 ArgTypes.push_back(*i);
398 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
399 ArgTypes.push_back(ShadowTy);
400 Type *RetType = T->getReturnType();
401 if (!RetType->isVoidTy())
402 ArgTypes.push_back(ShadowPtrTy);
403 return FunctionType::get(T->getReturnType(), ArgTypes, false);
406 bool DataFlowSanitizer::doInitialization(Module &M) {
407 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
409 report_fatal_error("data layout missing");
410 DL = &DLP->getDataLayout();
413 Ctx = &M.getContext();
414 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
415 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
416 IntptrTy = DL->getIntPtrType(*Ctx);
417 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
418 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
419 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
421 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
423 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
424 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
426 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
427 DFSanUnimplementedFnTy = FunctionType::get(
428 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
429 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
430 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
431 DFSanSetLabelArgs, /*isVarArg=*/false);
432 DFSanNonzeroLabelFnTy = FunctionType::get(
433 Type::getVoidTy(*Ctx), ArrayRef<Type *>(), /*isVarArg=*/false);
436 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
438 GetArgTLS = ConstantExpr::getIntToPtr(
439 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
440 PointerType::getUnqual(
441 FunctionType::get(PointerType::getUnqual(ArgTLSTy),
444 if (GetRetvalTLSPtr) {
446 GetRetvalTLS = ConstantExpr::getIntToPtr(
447 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
448 PointerType::getUnqual(
449 FunctionType::get(PointerType::getUnqual(ShadowTy),
453 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
457 bool DataFlowSanitizer::isInstrumented(const Function *F) {
458 return !ABIList.isIn(*F, "uninstrumented");
461 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
462 return !ABIList.isIn(*GA, "uninstrumented");
465 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
466 return ClArgsABI ? IA_Args : IA_TLS;
469 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
470 if (ABIList.isIn(*F, "functional"))
471 return WK_Functional;
472 if (ABIList.isIn(*F, "discard"))
474 if (ABIList.isIn(*F, "custom"))
480 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
481 std::string GVName = GV->getName(), Prefix = "dfs$";
482 GV->setName(Prefix + GVName);
484 // Try to change the name of the function in module inline asm. We only do
485 // this for specific asm directives, currently only ".symver", to try to avoid
486 // corrupting asm which happens to contain the symbol name as a substring.
487 // Note that the substitution for .symver assumes that the versioned symbol
488 // also has an instrumented name.
489 std::string Asm = GV->getParent()->getModuleInlineAsm();
490 std::string SearchStr = ".symver " + GVName + ",";
491 size_t Pos = Asm.find(SearchStr);
492 if (Pos != std::string::npos) {
493 Asm.replace(Pos, SearchStr.size(),
494 ".symver " + Prefix + GVName + "," + Prefix);
495 GV->getParent()->setModuleInlineAsm(Asm);
500 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
501 GlobalValue::LinkageTypes NewFLink,
502 FunctionType *NewFT) {
503 FunctionType *FT = F->getFunctionType();
504 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
506 NewF->copyAttributesFrom(F);
507 NewF->removeAttributes(
508 AttributeSet::ReturnIndex,
509 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
510 AttributeSet::ReturnIndex));
512 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
513 std::vector<Value *> Args;
514 unsigned n = FT->getNumParams();
515 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
516 Args.push_back(&*ai);
517 CallInst *CI = CallInst::Create(F, Args, "", BB);
518 if (FT->getReturnType()->isVoidTy())
519 ReturnInst::Create(*Ctx, BB);
521 ReturnInst::Create(*Ctx, CI, BB);
526 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
528 FunctionType *FTT = getTrampolineFunctionType(FT);
529 Constant *C = Mod->getOrInsertFunction(FName, FTT);
530 Function *F = dyn_cast<Function>(C);
531 if (F && F->isDeclaration()) {
532 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
533 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
534 std::vector<Value *> Args;
535 Function::arg_iterator AI = F->arg_begin(); ++AI;
536 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
537 Args.push_back(&*AI);
539 CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
541 if (FT->getReturnType()->isVoidTy())
542 RI = ReturnInst::Create(*Ctx, BB);
544 RI = ReturnInst::Create(*Ctx, CI, BB);
546 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
547 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
548 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
549 DFSF.ValShadowMap[ValAI] = ShadowAI;
550 DFSanVisitor(DFSF).visitCallInst(*CI);
551 if (!FT->getReturnType()->isVoidTy())
552 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
553 &F->getArgumentList().back(), RI);
559 bool DataFlowSanitizer::runOnModule(Module &M) {
563 if (ABIList.isIn(M, "skip"))
567 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
568 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
569 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
570 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
572 if (!GetRetvalTLSPtr) {
573 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
574 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
575 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
578 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
579 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
580 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
581 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
582 F->addAttribute(1, Attribute::ZExt);
583 F->addAttribute(2, Attribute::ZExt);
586 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
587 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
588 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
589 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
591 DFSanUnimplementedFn =
592 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
594 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
595 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
596 F->addAttribute(1, Attribute::ZExt);
598 DFSanNonzeroLabelFn =
599 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
601 std::vector<Function *> FnsToInstrument;
602 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
603 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
604 if (!i->isIntrinsic() &&
606 i != DFSanUnionLoadFn &&
607 i != DFSanUnimplementedFn &&
608 i != DFSanSetLabelFn &&
609 i != DFSanNonzeroLabelFn)
610 FnsToInstrument.push_back(&*i);
613 // Give function aliases prefixes when necessary, and build wrappers where the
614 // instrumentedness is inconsistent.
615 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
616 GlobalAlias *GA = &*i;
618 // Don't stop on weak. We assume people aren't playing games with the
619 // instrumentedness of overridden weak aliases.
620 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
621 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
622 if (GAInst && FInst) {
623 addGlobalNamePrefix(GA);
624 } else if (GAInst != FInst) {
625 // Non-instrumented alias of an instrumented function, or vice versa.
626 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
627 // below will take care of instrumenting it.
629 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
630 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
632 GA->eraseFromParent();
633 FnsToInstrument.push_back(NewF);
639 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
640 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
642 // First, change the ABI of every function in the module. ABI-listed
643 // functions keep their original ABI and get a wrapper function.
644 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
645 e = FnsToInstrument.end();
648 FunctionType *FT = F.getFunctionType();
650 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
651 FT->getReturnType()->isVoidTy());
653 if (isInstrumented(&F)) {
654 // Instrumented functions get a 'dfs$' prefix. This allows us to more
655 // easily identify cases of mismatching ABIs.
656 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
657 FunctionType *NewFT = getArgsFunctionType(FT);
658 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
659 NewF->copyAttributesFrom(&F);
660 NewF->removeAttributes(
661 AttributeSet::ReturnIndex,
662 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
663 AttributeSet::ReturnIndex));
664 for (Function::arg_iterator FArg = F.arg_begin(),
665 NewFArg = NewF->arg_begin(),
666 FArgEnd = F.arg_end();
667 FArg != FArgEnd; ++FArg, ++NewFArg) {
668 FArg->replaceAllUsesWith(NewFArg);
670 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
672 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
674 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
677 BA->replaceAllUsesWith(
678 BlockAddress::get(NewF, BA->getBasicBlock()));
682 F.replaceAllUsesWith(
683 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
687 addGlobalNamePrefix(NewF);
689 addGlobalNamePrefix(&F);
691 // Hopefully, nobody will try to indirectly call a vararg
693 } else if (FT->isVarArg()) {
694 UnwrappedFnMap[&F] = &F;
696 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
697 // Build a wrapper function for F. The wrapper simply calls F, and is
698 // added to FnsToInstrument so that any instrumentation according to its
699 // WrapperKind is done in the second pass below.
700 FunctionType *NewFT = getInstrumentedABI() == IA_Args
701 ? getArgsFunctionType(FT)
703 Function *NewF = buildWrapperFunction(
704 &F, std::string("dfsw$") + std::string(F.getName()),
705 GlobalValue::LinkOnceODRLinkage, NewFT);
706 if (getInstrumentedABI() == IA_TLS)
707 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
709 Value *WrappedFnCst =
710 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
711 F.replaceAllUsesWith(WrappedFnCst);
712 UnwrappedFnMap[WrappedFnCst] = &F;
715 if (!F.isDeclaration()) {
716 // This function is probably defining an interposition of an
717 // uninstrumented function and hence needs to keep the original ABI.
718 // But any functions it may call need to use the instrumented ABI, so
719 // we instrument it in a mode which preserves the original ABI.
720 FnsWithNativeABI.insert(&F);
722 // This code needs to rebuild the iterators, as they may be invalidated
723 // by the push_back, taking care that the new range does not include
724 // any functions added by this code.
725 size_t N = i - FnsToInstrument.begin(),
726 Count = e - FnsToInstrument.begin();
727 FnsToInstrument.push_back(&F);
728 i = FnsToInstrument.begin() + N;
729 e = FnsToInstrument.begin() + Count;
734 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
735 e = FnsToInstrument.end();
737 if (!*i || (*i)->isDeclaration())
740 removeUnreachableBlocks(**i);
742 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
744 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
745 // Build a copy of the list before iterating over it.
746 llvm::SmallVector<BasicBlock *, 4> BBList(
747 depth_first(&(*i)->getEntryBlock()));
749 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
752 Instruction *Inst = &(*i)->front();
754 // DFSanVisitor may split the current basic block, changing the current
755 // instruction's next pointer and moving the next instruction to the
756 // tail block from which we should continue.
757 Instruction *Next = Inst->getNextNode();
758 // DFSanVisitor may delete Inst, so keep track of whether it was a
760 bool IsTerminator = isa<TerminatorInst>(Inst);
761 if (!DFSF.SkipInsts.count(Inst))
762 DFSanVisitor(DFSF).visit(Inst);
769 // We will not necessarily be able to compute the shadow for every phi node
770 // until we have visited every block. Therefore, the code that handles phi
771 // nodes adds them to the PHIFixups list so that they can be properly
773 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
774 i = DFSF.PHIFixups.begin(),
775 e = DFSF.PHIFixups.end();
777 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
779 i->second->setIncomingValue(
780 val, DFSF.getShadow(i->first->getIncomingValue(val)));
784 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
785 // places (i.e. instructions in basic blocks we haven't even begun visiting
786 // yet). To make our life easier, do this work in a pass after the main
788 if (ClDebugNonzeroLabels) {
789 for (DenseSet<Value *>::iterator i = DFSF.NonZeroChecks.begin(),
790 e = DFSF.NonZeroChecks.end();
793 if (Instruction *I = dyn_cast<Instruction>(*i))
794 Pos = I->getNextNode();
796 Pos = DFSF.F->getEntryBlock().begin();
797 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
798 Pos = Pos->getNextNode();
799 IRBuilder<> IRB(Pos);
800 Value *Ne = IRB.CreateICmpNE(*i, DFSF.DFS.ZeroShadow);
801 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
802 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
803 IRBuilder<> ThenIRB(BI);
804 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
812 Value *DFSanFunction::getArgTLSPtr() {
816 return ArgTLSPtr = DFS.ArgTLS;
818 IRBuilder<> IRB(F->getEntryBlock().begin());
819 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
822 Value *DFSanFunction::getRetvalTLS() {
826 return RetvalTLSPtr = DFS.RetvalTLS;
828 IRBuilder<> IRB(F->getEntryBlock().begin());
829 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
832 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
833 IRBuilder<> IRB(Pos);
834 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
837 Value *DFSanFunction::getShadow(Value *V) {
838 if (!isa<Argument>(V) && !isa<Instruction>(V))
839 return DFS.ZeroShadow;
840 Value *&Shadow = ValShadowMap[V];
842 if (Argument *A = dyn_cast<Argument>(V)) {
844 return DFS.ZeroShadow;
846 case DataFlowSanitizer::IA_TLS: {
847 Value *ArgTLSPtr = getArgTLSPtr();
848 Instruction *ArgTLSPos =
849 DFS.ArgTLS ? &*F->getEntryBlock().begin()
850 : cast<Instruction>(ArgTLSPtr)->getNextNode();
851 IRBuilder<> IRB(ArgTLSPos);
852 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
855 case DataFlowSanitizer::IA_Args: {
856 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
857 Function::arg_iterator i = F->arg_begin();
861 assert(Shadow->getType() == DFS.ShadowTy);
865 NonZeroChecks.insert(Shadow);
867 Shadow = DFS.ZeroShadow;
873 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
874 assert(!ValShadowMap.count(I));
875 assert(Shadow->getType() == DFS.ShadowTy);
876 ValShadowMap[I] = Shadow;
879 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
880 assert(Addr != RetvalTLS && "Reinstrumenting?");
881 IRBuilder<> IRB(Pos);
882 return IRB.CreateIntToPtr(
884 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
889 // Generates IR to compute the union of the two given shadows, inserting it
890 // before Pos. Returns the computed union Value.
891 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
892 if (V1 == DFS.ZeroShadow)
894 if (V2 == DFS.ZeroShadow)
899 auto V1Elems = ShadowElements.find(V1);
900 auto V2Elems = ShadowElements.find(V2);
901 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
902 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
903 V2Elems->second.begin(), V2Elems->second.end())) {
905 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
906 V1Elems->second.begin(), V1Elems->second.end())) {
909 } else if (V1Elems != ShadowElements.end()) {
910 if (V1Elems->second.count(V2))
912 } else if (V2Elems != ShadowElements.end()) {
913 if (V2Elems->second.count(V1))
917 auto Key = std::make_pair(V1, V2);
919 std::swap(Key.first, Key.second);
920 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
921 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
924 IRBuilder<> IRB(Pos);
925 BasicBlock *Head = Pos->getParent();
926 Value *Ne = IRB.CreateICmpNE(V1, V2);
927 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
928 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
929 IRBuilder<> ThenIRB(BI);
930 CallInst *Call = ThenIRB.CreateCall2(DFS.DFSanUnionFn, V1, V2);
931 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
932 Call->addAttribute(1, Attribute::ZExt);
933 Call->addAttribute(2, Attribute::ZExt);
935 BasicBlock *Tail = BI->getSuccessor(0);
936 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", Tail->begin());
937 Phi->addIncoming(Call, Call->getParent());
938 Phi->addIncoming(V1, Head);
943 std::set<Value *> UnionElems;
944 if (V1Elems != ShadowElements.end()) {
945 UnionElems = V1Elems->second;
947 UnionElems.insert(V1);
949 if (V2Elems != ShadowElements.end()) {
950 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
952 UnionElems.insert(V2);
954 ShadowElements[Phi] = std::move(UnionElems);
959 // A convenience function which folds the shadows of each of the operands
960 // of the provided instruction Inst, inserting the IR before Inst. Returns
961 // the computed union Value.
962 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
963 if (Inst->getNumOperands() == 0)
964 return DFS.ZeroShadow;
966 Value *Shadow = getShadow(Inst->getOperand(0));
967 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
968 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
973 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
974 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
975 DFSF.setShadow(&I, CombinedShadow);
978 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
979 // Addr has alignment Align, and take the union of each of those shadows.
980 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
982 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
983 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
984 AllocaShadowMap.find(AI);
985 if (i != AllocaShadowMap.end()) {
986 IRBuilder<> IRB(Pos);
987 return IRB.CreateLoad(i->second);
991 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
992 SmallVector<Value *, 2> Objs;
993 GetUnderlyingObjects(Addr, Objs, DFS.DL);
994 bool AllConstants = true;
995 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
997 if (isa<Function>(*i) || isa<BlockAddress>(*i))
999 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
1002 AllConstants = false;
1006 return DFS.ZeroShadow;
1008 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1011 return DFS.ZeroShadow;
1013 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1014 LI->setAlignment(ShadowAlign);
1018 IRBuilder<> IRB(Pos);
1019 Value *ShadowAddr1 =
1020 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
1021 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1022 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
1025 if (Size % (64 / DFS.ShadowWidth) == 0) {
1026 // Fast path for the common case where each byte has identical shadow: load
1027 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1028 // shadow is non-equal.
1029 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1030 IRBuilder<> FallbackIRB(FallbackBB);
1031 CallInst *FallbackCall = FallbackIRB.CreateCall2(
1032 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1033 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1035 // Compare each of the shadows stored in the loaded 64 bits to each other,
1036 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1037 IRBuilder<> IRB(Pos);
1039 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1040 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1041 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1042 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1043 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1044 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1045 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1047 BasicBlock *Head = Pos->getParent();
1048 BasicBlock *Tail = Head->splitBasicBlock(Pos);
1050 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1051 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1053 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1054 for (auto Child : Children)
1055 DT.changeImmediateDominator(Child, NewNode);
1058 // In the following code LastBr will refer to the previous basic block's
1059 // conditional branch instruction, whose true successor is fixed up to point
1060 // to the next block during the loop below or to the tail after the final
1062 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1063 ReplaceInstWithInst(Head->getTerminator(), LastBr);
1064 DT.addNewBlock(FallbackBB, Head);
1066 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1067 Ofs += 64 / DFS.ShadowWidth) {
1068 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
1069 DT.addNewBlock(NextBB, LastBr->getParent());
1070 IRBuilder<> NextIRB(NextBB);
1071 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
1072 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1073 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1074 LastBr->setSuccessor(0, NextBB);
1075 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1078 LastBr->setSuccessor(0, Tail);
1079 FallbackIRB.CreateBr(Tail);
1080 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1081 Shadow->addIncoming(FallbackCall, FallbackBB);
1082 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1086 IRBuilder<> IRB(Pos);
1087 CallInst *FallbackCall = IRB.CreateCall2(
1088 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1089 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1090 return FallbackCall;
1093 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1094 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
1096 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1101 if (ClPreserveAlignment) {
1102 Align = LI.getAlignment();
1104 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
1108 IRBuilder<> IRB(&LI);
1109 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1110 if (ClCombinePointerLabelsOnLoad) {
1111 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
1112 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
1114 if (Shadow != DFSF.DFS.ZeroShadow)
1115 DFSF.NonZeroChecks.insert(Shadow);
1117 DFSF.setShadow(&LI, Shadow);
1120 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1121 Value *Shadow, Instruction *Pos) {
1122 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1123 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1124 AllocaShadowMap.find(AI);
1125 if (i != AllocaShadowMap.end()) {
1126 IRBuilder<> IRB(Pos);
1127 IRB.CreateStore(Shadow, i->second);
1132 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1133 IRBuilder<> IRB(Pos);
1134 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1135 if (Shadow == DFS.ZeroShadow) {
1136 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1137 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1138 Value *ExtShadowAddr =
1139 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1140 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1144 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1145 uint64_t Offset = 0;
1146 if (Size >= ShadowVecSize) {
1147 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1148 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1149 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1150 ShadowVec = IRB.CreateInsertElement(
1151 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1153 Value *ShadowVecAddr =
1154 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1156 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
1157 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1158 Size -= ShadowVecSize;
1160 } while (Size >= ShadowVecSize);
1161 Offset *= ShadowVecSize;
1164 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
1165 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1171 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1173 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
1178 if (ClPreserveAlignment) {
1179 Align = SI.getAlignment();
1181 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
1186 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1187 if (ClCombinePointerLabelsOnStore) {
1188 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
1189 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
1191 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
1194 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1195 visitOperandShadowInst(BO);
1198 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1200 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1202 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1203 visitOperandShadowInst(GEPI);
1206 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1207 visitOperandShadowInst(I);
1210 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1211 visitOperandShadowInst(I);
1214 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1215 visitOperandShadowInst(I);
1218 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1219 visitOperandShadowInst(I);
1222 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1223 visitOperandShadowInst(I);
1226 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1227 bool AllLoadsStores = true;
1228 for (User *U : I.users()) {
1229 if (isa<LoadInst>(U))
1232 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1233 if (SI->getPointerOperand() == &I)
1237 AllLoadsStores = false;
1240 if (AllLoadsStores) {
1241 IRBuilder<> IRB(&I);
1242 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1244 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1247 void DFSanVisitor::visitSelectInst(SelectInst &I) {
1248 Value *CondShadow = DFSF.getShadow(I.getCondition());
1249 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1250 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1252 if (isa<VectorType>(I.getCondition()->getType())) {
1255 DFSF.combineShadows(
1256 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
1259 if (TrueShadow == FalseShadow) {
1260 ShadowSel = TrueShadow;
1263 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1265 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
1269 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1270 IRBuilder<> IRB(&I);
1271 Value *ValShadow = DFSF.getShadow(I.getValue());
1273 DFSF.DFS.DFSanSetLabelFn, ValShadow,
1274 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1275 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1278 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1279 IRBuilder<> IRB(&I);
1280 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1281 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1282 Value *LenShadow = IRB.CreateMul(
1284 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1286 if (ClPreserveAlignment) {
1287 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1288 ConstantInt::get(I.getAlignmentCst()->getType(),
1289 DFSF.DFS.ShadowWidth / 8));
1291 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1292 DFSF.DFS.ShadowWidth / 8);
1294 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1295 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1296 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1297 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1298 AlignShadow, I.getVolatileCst());
1301 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
1302 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
1304 case DataFlowSanitizer::IA_TLS: {
1305 Value *S = DFSF.getShadow(RI.getReturnValue());
1306 IRBuilder<> IRB(&RI);
1307 IRB.CreateStore(S, DFSF.getRetvalTLS());
1310 case DataFlowSanitizer::IA_Args: {
1311 IRBuilder<> IRB(&RI);
1312 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1314 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1316 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1317 RI.setOperand(0, InsShadow);
1324 void DFSanVisitor::visitCallSite(CallSite CS) {
1325 Function *F = CS.getCalledFunction();
1326 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1327 visitOperandShadowInst(*CS.getInstruction());
1331 IRBuilder<> IRB(CS.getInstruction());
1333 DenseMap<Value *, Function *>::iterator i =
1334 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1335 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1336 Function *F = i->second;
1337 switch (DFSF.DFS.getWrapperKind(F)) {
1338 case DataFlowSanitizer::WK_Warning: {
1339 CS.setCalledFunction(F);
1340 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1341 IRB.CreateGlobalStringPtr(F->getName()));
1342 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1345 case DataFlowSanitizer::WK_Discard: {
1346 CS.setCalledFunction(F);
1347 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1350 case DataFlowSanitizer::WK_Functional: {
1351 CS.setCalledFunction(F);
1352 visitOperandShadowInst(*CS.getInstruction());
1355 case DataFlowSanitizer::WK_Custom: {
1356 // Don't try to handle invokes of custom functions, it's too complicated.
1357 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1359 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1360 FunctionType *FT = F->getFunctionType();
1361 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1362 std::string CustomFName = "__dfsw_";
1363 CustomFName += F->getName();
1365 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1366 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1367 CustomFn->copyAttributesFrom(F);
1369 // Custom functions returning non-void will write to the return label.
1370 if (!FT->getReturnType()->isVoidTy()) {
1371 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1372 DFSF.DFS.ReadOnlyNoneAttrs);
1376 std::vector<Value *> Args;
1378 CallSite::arg_iterator i = CS.arg_begin();
1379 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
1380 Type *T = (*i)->getType();
1381 FunctionType *ParamFT;
1382 if (isa<PointerType>(T) &&
1383 (ParamFT = dyn_cast<FunctionType>(
1384 cast<PointerType>(T)->getElementType()))) {
1385 std::string TName = "dfst";
1386 TName += utostr(FT->getNumParams() - n);
1388 TName += F->getName();
1389 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1392 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1399 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1400 Args.push_back(DFSF.getShadow(*i));
1402 if (!FT->getReturnType()->isVoidTy()) {
1403 if (!DFSF.LabelReturnAlloca) {
1404 DFSF.LabelReturnAlloca =
1405 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1406 DFSF.F->getEntryBlock().begin());
1408 Args.push_back(DFSF.LabelReturnAlloca);
1411 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1412 CustomCI->setCallingConv(CI->getCallingConv());
1413 CustomCI->setAttributes(CI->getAttributes());
1415 if (!FT->getReturnType()->isVoidTy()) {
1416 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1417 DFSF.setShadow(CustomCI, LabelLoad);
1420 CI->replaceAllUsesWith(CustomCI);
1421 CI->eraseFromParent();
1429 FunctionType *FT = cast<FunctionType>(
1430 CS.getCalledValue()->getType()->getPointerElementType());
1431 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1432 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1433 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1434 DFSF.getArgTLS(i, CS.getInstruction()));
1438 Instruction *Next = nullptr;
1439 if (!CS.getType()->isVoidTy()) {
1440 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1441 if (II->getNormalDest()->getSinglePredecessor()) {
1442 Next = II->getNormalDest()->begin();
1445 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1446 Next = NewBB->begin();
1449 Next = CS->getNextNode();
1452 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1453 IRBuilder<> NextIRB(Next);
1454 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1455 DFSF.SkipInsts.insert(LI);
1456 DFSF.setShadow(CS.getInstruction(), LI);
1457 DFSF.NonZeroChecks.insert(LI);
1461 // Do all instrumentation for IA_Args down here to defer tampering with the
1462 // CFG in a way that SplitEdge may be able to detect.
1463 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1464 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
1466 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1467 std::vector<Value *> Args;
1469 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1470 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1474 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1475 Args.push_back(DFSF.getShadow(*i));
1477 if (FT->isVarArg()) {
1478 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1479 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1480 AllocaInst *VarArgShadow =
1481 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1482 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1483 for (unsigned n = 0; i != e; ++i, ++n) {
1484 IRB.CreateStore(DFSF.getShadow(*i),
1485 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1491 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1492 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1495 NewCS = IRB.CreateCall(Func, Args);
1497 NewCS.setCallingConv(CS.getCallingConv());
1498 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1499 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1500 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1501 AttributeSet::ReturnIndex)));
1504 ExtractValueInst *ExVal =
1505 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1506 DFSF.SkipInsts.insert(ExVal);
1507 ExtractValueInst *ExShadow =
1508 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1509 DFSF.SkipInsts.insert(ExShadow);
1510 DFSF.setShadow(ExVal, ExShadow);
1511 DFSF.NonZeroChecks.insert(ExShadow);
1513 CS.getInstruction()->replaceAllUsesWith(ExVal);
1516 CS.getInstruction()->eraseFromParent();
1520 void DFSanVisitor::visitPHINode(PHINode &PN) {
1522 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1524 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1525 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1526 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1528 ShadowPN->addIncoming(UndefShadow, *i);
1531 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1532 DFSF.setShadow(&PN, ShadowPN);