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/ADT/Triple.h"
53 #include "llvm/Analysis/ValueTracking.h"
54 #include "llvm/IR/Dominators.h"
55 #include "llvm/IR/DebugInfo.h"
56 #include "llvm/IR/IRBuilder.h"
57 #include "llvm/IR/InlineAsm.h"
58 #include "llvm/IR/InstVisitor.h"
59 #include "llvm/IR/LLVMContext.h"
60 #include "llvm/IR/MDBuilder.h"
61 #include "llvm/IR/Type.h"
62 #include "llvm/IR/Value.h"
63 #include "llvm/Pass.h"
64 #include "llvm/Support/CommandLine.h"
65 #include "llvm/Support/SpecialCaseList.h"
66 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
67 #include "llvm/Transforms/Utils/Local.h"
75 // VMA size definition for architecture that support multiple sizes.
76 // AArch64 has 3 VMA sizes: 39, 42 and 48.
77 #ifndef SANITIZER_AARCH64_VMA
78 # define SANITIZER_AARCH64_VMA 39
80 # if SANITIZER_AARCH64_VMA != 39 && SANITIZER_AARCH64_VMA != 42
81 # error "invalid SANITIZER_AARCH64_VMA size"
85 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
86 // alignment requirements provided by the input IR are correct. For example,
87 // if the input IR contains a load with alignment 8, this flag will cause
88 // the shadow load to have alignment 16. This flag is disabled by default as
89 // we have unfortunately encountered too much code (including Clang itself;
90 // see PR14291) which performs misaligned access.
91 static cl::opt<bool> ClPreserveAlignment(
92 "dfsan-preserve-alignment",
93 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
96 // The ABI list files control how shadow parameters are passed. The pass treats
97 // every function labelled "uninstrumented" in the ABI list file as conforming
98 // to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
99 // additional annotations for those functions, a call to one of those functions
100 // will produce a warning message, as the labelling behaviour of the function is
101 // unknown. The other supported annotations are "functional" and "discard",
102 // which are described below under DataFlowSanitizer::WrapperKind.
103 static cl::list<std::string> ClABIListFiles(
105 cl::desc("File listing native ABI functions and how the pass treats them"),
108 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
109 // functions (see DataFlowSanitizer::InstrumentedABI below).
110 static cl::opt<bool> ClArgsABI(
112 cl::desc("Use the argument ABI rather than the TLS ABI"),
115 // Controls whether the pass includes or ignores the labels of pointers in load
117 static cl::opt<bool> ClCombinePointerLabelsOnLoad(
118 "dfsan-combine-pointer-labels-on-load",
119 cl::desc("Combine the label of the pointer with the label of the data when "
120 "loading from memory."),
121 cl::Hidden, cl::init(true));
123 // Controls whether the pass includes or ignores the labels of pointers in
124 // stores instructions.
125 static cl::opt<bool> ClCombinePointerLabelsOnStore(
126 "dfsan-combine-pointer-labels-on-store",
127 cl::desc("Combine the label of the pointer with the label of the data when "
128 "storing in memory."),
129 cl::Hidden, cl::init(false));
131 static cl::opt<bool> ClDebugNonzeroLabels(
132 "dfsan-debug-nonzero-labels",
133 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
134 "load or return with a nonzero label"),
139 StringRef GetGlobalTypeString(const GlobalValue &G) {
140 // Types of GlobalVariables are always pointer types.
141 Type *GType = G.getType()->getElementType();
142 // For now we support blacklisting struct types only.
143 if (StructType *SGType = dyn_cast<StructType>(GType)) {
144 if (!SGType->isLiteral())
145 return SGType->getName();
147 return "<unknown type>";
151 std::unique_ptr<SpecialCaseList> SCL;
156 void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
158 /// Returns whether either this function or its source file are listed in the
160 bool isIn(const Function &F, StringRef Category) const {
161 return isIn(*F.getParent(), Category) ||
162 SCL->inSection("fun", F.getName(), Category);
165 /// Returns whether this global alias is listed in the given category.
167 /// If GA aliases a function, the alias's name is matched as a function name
168 /// would be. Similarly, aliases of globals are matched like globals.
169 bool isIn(const GlobalAlias &GA, StringRef Category) const {
170 if (isIn(*GA.getParent(), Category))
173 if (isa<FunctionType>(GA.getType()->getElementType()))
174 return SCL->inSection("fun", GA.getName(), Category);
176 return SCL->inSection("global", GA.getName(), Category) ||
177 SCL->inSection("type", GetGlobalTypeString(GA), Category);
180 /// Returns whether this module is listed in the given category.
181 bool isIn(const Module &M, StringRef Category) const {
182 return SCL->inSection("src", M.getModuleIdentifier(), Category);
186 class DataFlowSanitizer : public ModulePass {
187 friend struct DFSanFunction;
188 friend class DFSanVisitor;
194 /// Which ABI should be used for instrumented functions?
195 enum InstrumentedABI {
196 /// Argument and return value labels are passed through additional
197 /// arguments and by modifying the return type.
200 /// Argument and return value labels are passed through TLS variables
201 /// __dfsan_arg_tls and __dfsan_retval_tls.
205 /// How should calls to uninstrumented functions be handled?
207 /// This function is present in an uninstrumented form but we don't know
208 /// how it should be handled. Print a warning and call the function anyway.
209 /// Don't label the return value.
212 /// This function does not write to (user-accessible) memory, and its return
213 /// value is unlabelled.
216 /// This function does not write to (user-accessible) memory, and the label
217 /// of its return value is the union of the label of its arguments.
220 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
221 /// where F is the name of the function. This function may wrap the
222 /// original function or provide its own implementation. This is similar to
223 /// the IA_Args ABI, except that IA_Args uses a struct return type to
224 /// pass the return value shadow in a register, while WK_Custom uses an
225 /// extra pointer argument to return the shadow. This allows the wrapped
226 /// form of the function type to be expressed in C.
232 IntegerType *ShadowTy;
233 PointerType *ShadowPtrTy;
234 IntegerType *IntptrTy;
235 ConstantInt *ZeroShadow;
236 ConstantInt *ShadowPtrMask;
237 ConstantInt *ShadowPtrMul;
240 void *(*GetArgTLSPtr)();
241 void *(*GetRetvalTLSPtr)();
243 Constant *GetRetvalTLS;
244 FunctionType *DFSanUnionFnTy;
245 FunctionType *DFSanUnionLoadFnTy;
246 FunctionType *DFSanUnimplementedFnTy;
247 FunctionType *DFSanSetLabelFnTy;
248 FunctionType *DFSanNonzeroLabelFnTy;
249 FunctionType *DFSanVarargWrapperFnTy;
250 Constant *DFSanUnionFn;
251 Constant *DFSanCheckedUnionFn;
252 Constant *DFSanUnionLoadFn;
253 Constant *DFSanUnimplementedFn;
254 Constant *DFSanSetLabelFn;
255 Constant *DFSanNonzeroLabelFn;
256 Constant *DFSanVarargWrapperFn;
257 MDNode *ColdCallWeights;
258 DFSanABIList ABIList;
259 DenseMap<Value *, Function *> UnwrappedFnMap;
260 AttributeSet ReadOnlyNoneAttrs;
262 Value *getShadowAddress(Value *Addr, Instruction *Pos);
263 bool isInstrumented(const Function *F);
264 bool isInstrumented(const GlobalAlias *GA);
265 FunctionType *getArgsFunctionType(FunctionType *T);
266 FunctionType *getTrampolineFunctionType(FunctionType *T);
267 FunctionType *getCustomFunctionType(FunctionType *T);
268 InstrumentedABI getInstrumentedABI();
269 WrapperKind getWrapperKind(Function *F);
270 void addGlobalNamePrefix(GlobalValue *GV);
271 Function *buildWrapperFunction(Function *F, StringRef NewFName,
272 GlobalValue::LinkageTypes NewFLink,
273 FunctionType *NewFT);
274 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
278 const std::vector<std::string> &ABIListFiles = std::vector<std::string>(),
279 void *(*getArgTLS)() = nullptr, void *(*getRetValTLS)() = nullptr);
281 bool doInitialization(Module &M) override;
282 bool runOnModule(Module &M) override;
285 struct DFSanFunction {
286 DataFlowSanitizer &DFS;
289 DataFlowSanitizer::InstrumentedABI IA;
293 AllocaInst *LabelReturnAlloca;
294 DenseMap<Value *, Value *> ValShadowMap;
295 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
296 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
297 DenseSet<Instruction *> SkipInsts;
298 std::vector<Value *> NonZeroChecks;
301 struct CachedCombinedShadow {
305 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
306 CachedCombinedShadows;
307 DenseMap<Value *, std::set<Value *>> ShadowElements;
309 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
310 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
311 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
312 LabelReturnAlloca(nullptr) {
314 // FIXME: Need to track down the register allocator issue which causes poor
315 // performance in pathological cases with large numbers of basic blocks.
316 AvoidNewBlocks = F->size() > 1000;
318 Value *getArgTLSPtr();
319 Value *getArgTLS(unsigned Index, Instruction *Pos);
320 Value *getRetvalTLS();
321 Value *getShadow(Value *V);
322 void setShadow(Instruction *I, Value *Shadow);
323 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
324 Value *combineOperandShadows(Instruction *Inst);
325 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
327 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
331 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
334 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
336 void visitOperandShadowInst(Instruction &I);
338 void visitBinaryOperator(BinaryOperator &BO);
339 void visitCastInst(CastInst &CI);
340 void visitCmpInst(CmpInst &CI);
341 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
342 void visitLoadInst(LoadInst &LI);
343 void visitStoreInst(StoreInst &SI);
344 void visitReturnInst(ReturnInst &RI);
345 void visitCallSite(CallSite CS);
346 void visitPHINode(PHINode &PN);
347 void visitExtractElementInst(ExtractElementInst &I);
348 void visitInsertElementInst(InsertElementInst &I);
349 void visitShuffleVectorInst(ShuffleVectorInst &I);
350 void visitExtractValueInst(ExtractValueInst &I);
351 void visitInsertValueInst(InsertValueInst &I);
352 void visitAllocaInst(AllocaInst &I);
353 void visitSelectInst(SelectInst &I);
354 void visitMemSetInst(MemSetInst &I);
355 void visitMemTransferInst(MemTransferInst &I);
360 char DataFlowSanitizer::ID;
361 INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
362 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
365 llvm::createDataFlowSanitizerPass(const std::vector<std::string> &ABIListFiles,
366 void *(*getArgTLS)(),
367 void *(*getRetValTLS)()) {
368 return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS);
371 DataFlowSanitizer::DataFlowSanitizer(
372 const std::vector<std::string> &ABIListFiles, void *(*getArgTLS)(),
373 void *(*getRetValTLS)())
374 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS) {
375 std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
376 AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(),
377 ClABIListFiles.end());
378 ABIList.set(SpecialCaseList::createOrDie(AllABIListFiles));
381 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
382 llvm::SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
383 ArgTypes.append(T->getNumParams(), ShadowTy);
385 ArgTypes.push_back(ShadowPtrTy);
386 Type *RetType = T->getReturnType();
387 if (!RetType->isVoidTy())
388 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
389 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
392 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
393 assert(!T->isVarArg());
394 llvm::SmallVector<Type *, 4> ArgTypes;
395 ArgTypes.push_back(T->getPointerTo());
396 ArgTypes.append(T->param_begin(), T->param_end());
397 ArgTypes.append(T->getNumParams(), ShadowTy);
398 Type *RetType = T->getReturnType();
399 if (!RetType->isVoidTy())
400 ArgTypes.push_back(ShadowPtrTy);
401 return FunctionType::get(T->getReturnType(), ArgTypes, false);
404 FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
405 llvm::SmallVector<Type *, 4> ArgTypes;
406 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
409 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
410 *i)->getElementType()))) {
411 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
412 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
414 ArgTypes.push_back(*i);
417 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
418 ArgTypes.push_back(ShadowTy);
420 ArgTypes.push_back(ShadowPtrTy);
421 Type *RetType = T->getReturnType();
422 if (!RetType->isVoidTy())
423 ArgTypes.push_back(ShadowPtrTy);
424 return FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg());
427 bool DataFlowSanitizer::doInitialization(Module &M) {
428 llvm::Triple TargetTriple(M.getTargetTriple());
429 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
430 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
431 TargetTriple.getArch() == llvm::Triple::mips64el;
432 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64 ||
433 TargetTriple.getArch() == llvm::Triple::aarch64_be;
435 const DataLayout &DL = M.getDataLayout();
438 Ctx = &M.getContext();
439 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
440 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
441 IntptrTy = DL.getIntPtrType(*Ctx);
442 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
443 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
445 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
447 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
449 #if SANITIZER_AARCH64_VMA == 39
450 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x7800000000LL);
452 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x3c000000000LL);
455 report_fatal_error("unsupported triple");
457 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
459 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
460 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
462 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
463 DFSanUnimplementedFnTy = FunctionType::get(
464 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
465 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
466 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
467 DFSanSetLabelArgs, /*isVarArg=*/false);
468 DFSanNonzeroLabelFnTy = FunctionType::get(
469 Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
470 DFSanVarargWrapperFnTy = FunctionType::get(
471 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
474 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
476 GetArgTLS = ConstantExpr::getIntToPtr(
477 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
478 PointerType::getUnqual(
479 FunctionType::get(PointerType::getUnqual(ArgTLSTy),
482 if (GetRetvalTLSPtr) {
484 GetRetvalTLS = ConstantExpr::getIntToPtr(
485 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
486 PointerType::getUnqual(
487 FunctionType::get(PointerType::getUnqual(ShadowTy),
491 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
495 bool DataFlowSanitizer::isInstrumented(const Function *F) {
496 return !ABIList.isIn(*F, "uninstrumented");
499 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
500 return !ABIList.isIn(*GA, "uninstrumented");
503 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
504 return ClArgsABI ? IA_Args : IA_TLS;
507 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
508 if (ABIList.isIn(*F, "functional"))
509 return WK_Functional;
510 if (ABIList.isIn(*F, "discard"))
512 if (ABIList.isIn(*F, "custom"))
518 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
519 std::string GVName = GV->getName(), Prefix = "dfs$";
520 GV->setName(Prefix + GVName);
522 // Try to change the name of the function in module inline asm. We only do
523 // this for specific asm directives, currently only ".symver", to try to avoid
524 // corrupting asm which happens to contain the symbol name as a substring.
525 // Note that the substitution for .symver assumes that the versioned symbol
526 // also has an instrumented name.
527 std::string Asm = GV->getParent()->getModuleInlineAsm();
528 std::string SearchStr = ".symver " + GVName + ",";
529 size_t Pos = Asm.find(SearchStr);
530 if (Pos != std::string::npos) {
531 Asm.replace(Pos, SearchStr.size(),
532 ".symver " + Prefix + GVName + "," + Prefix);
533 GV->getParent()->setModuleInlineAsm(Asm);
538 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
539 GlobalValue::LinkageTypes NewFLink,
540 FunctionType *NewFT) {
541 FunctionType *FT = F->getFunctionType();
542 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
544 NewF->copyAttributesFrom(F);
545 NewF->removeAttributes(
546 AttributeSet::ReturnIndex,
547 AttributeSet::get(F->getContext(), AttributeSet::ReturnIndex,
548 AttributeFuncs::typeIncompatible(NewFT->getReturnType())));
550 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
552 NewF->removeAttributes(
553 AttributeSet::FunctionIndex,
554 AttributeSet().addAttribute(*Ctx, AttributeSet::FunctionIndex,
556 CallInst::Create(DFSanVarargWrapperFn,
557 IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
559 new UnreachableInst(*Ctx, BB);
561 std::vector<Value *> Args;
562 unsigned n = FT->getNumParams();
563 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
564 Args.push_back(&*ai);
565 CallInst *CI = CallInst::Create(F, Args, "", BB);
566 if (FT->getReturnType()->isVoidTy())
567 ReturnInst::Create(*Ctx, BB);
569 ReturnInst::Create(*Ctx, CI, BB);
575 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
577 FunctionType *FTT = getTrampolineFunctionType(FT);
578 Constant *C = Mod->getOrInsertFunction(FName, FTT);
579 Function *F = dyn_cast<Function>(C);
580 if (F && F->isDeclaration()) {
581 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
582 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
583 std::vector<Value *> Args;
584 Function::arg_iterator AI = F->arg_begin(); ++AI;
585 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
586 Args.push_back(&*AI);
588 CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
590 if (FT->getReturnType()->isVoidTy())
591 RI = ReturnInst::Create(*Ctx, BB);
593 RI = ReturnInst::Create(*Ctx, CI, BB);
595 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
596 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
597 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
598 DFSF.ValShadowMap[&*ValAI] = &*ShadowAI;
599 DFSanVisitor(DFSF).visitCallInst(*CI);
600 if (!FT->getReturnType()->isVoidTy())
601 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
602 &F->getArgumentList().back(), RI);
608 bool DataFlowSanitizer::runOnModule(Module &M) {
609 if (ABIList.isIn(M, "skip"))
613 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
614 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
615 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
616 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
618 if (!GetRetvalTLSPtr) {
619 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
620 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
621 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
624 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
625 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
626 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
627 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
628 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
629 F->addAttribute(1, Attribute::ZExt);
630 F->addAttribute(2, Attribute::ZExt);
632 DFSanCheckedUnionFn = Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy);
633 if (Function *F = dyn_cast<Function>(DFSanCheckedUnionFn)) {
634 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
635 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
636 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
637 F->addAttribute(1, Attribute::ZExt);
638 F->addAttribute(2, Attribute::ZExt);
641 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
642 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
643 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
644 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
645 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
647 DFSanUnimplementedFn =
648 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
650 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
651 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
652 F->addAttribute(1, Attribute::ZExt);
654 DFSanNonzeroLabelFn =
655 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
656 DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
657 DFSanVarargWrapperFnTy);
659 std::vector<Function *> FnsToInstrument;
660 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
661 for (Function &i : M) {
662 if (!i.isIntrinsic() &&
663 &i != DFSanUnionFn &&
664 &i != DFSanCheckedUnionFn &&
665 &i != DFSanUnionLoadFn &&
666 &i != DFSanUnimplementedFn &&
667 &i != DFSanSetLabelFn &&
668 &i != DFSanNonzeroLabelFn &&
669 &i != DFSanVarargWrapperFn)
670 FnsToInstrument.push_back(&i);
673 // Give function aliases prefixes when necessary, and build wrappers where the
674 // instrumentedness is inconsistent.
675 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
676 GlobalAlias *GA = &*i;
678 // Don't stop on weak. We assume people aren't playing games with the
679 // instrumentedness of overridden weak aliases.
680 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
681 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
682 if (GAInst && FInst) {
683 addGlobalNamePrefix(GA);
684 } else if (GAInst != FInst) {
685 // Non-instrumented alias of an instrumented function, or vice versa.
686 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
687 // below will take care of instrumenting it.
689 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
690 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
692 GA->eraseFromParent();
693 FnsToInstrument.push_back(NewF);
699 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
700 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
702 // First, change the ABI of every function in the module. ABI-listed
703 // functions keep their original ABI and get a wrapper function.
704 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
705 e = FnsToInstrument.end();
708 FunctionType *FT = F.getFunctionType();
710 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
711 FT->getReturnType()->isVoidTy());
713 if (isInstrumented(&F)) {
714 // Instrumented functions get a 'dfs$' prefix. This allows us to more
715 // easily identify cases of mismatching ABIs.
716 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
717 FunctionType *NewFT = getArgsFunctionType(FT);
718 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
719 NewF->copyAttributesFrom(&F);
720 NewF->removeAttributes(
721 AttributeSet::ReturnIndex,
722 AttributeSet::get(NewF->getContext(), AttributeSet::ReturnIndex,
723 AttributeFuncs::typeIncompatible(NewFT->getReturnType())));
724 for (Function::arg_iterator FArg = F.arg_begin(),
725 NewFArg = NewF->arg_begin(),
726 FArgEnd = F.arg_end();
727 FArg != FArgEnd; ++FArg, ++NewFArg) {
728 FArg->replaceAllUsesWith(&*NewFArg);
730 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
732 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
734 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
737 BA->replaceAllUsesWith(
738 BlockAddress::get(NewF, BA->getBasicBlock()));
742 F.replaceAllUsesWith(
743 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
747 addGlobalNamePrefix(NewF);
749 addGlobalNamePrefix(&F);
751 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
752 // Build a wrapper function for F. The wrapper simply calls F, and is
753 // added to FnsToInstrument so that any instrumentation according to its
754 // WrapperKind is done in the second pass below.
755 FunctionType *NewFT = getInstrumentedABI() == IA_Args
756 ? getArgsFunctionType(FT)
758 Function *NewF = buildWrapperFunction(
759 &F, std::string("dfsw$") + std::string(F.getName()),
760 GlobalValue::LinkOnceODRLinkage, NewFT);
761 if (getInstrumentedABI() == IA_TLS)
762 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
764 Value *WrappedFnCst =
765 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
766 F.replaceAllUsesWith(WrappedFnCst);
768 UnwrappedFnMap[WrappedFnCst] = &F;
771 if (!F.isDeclaration()) {
772 // This function is probably defining an interposition of an
773 // uninstrumented function and hence needs to keep the original ABI.
774 // But any functions it may call need to use the instrumented ABI, so
775 // we instrument it in a mode which preserves the original ABI.
776 FnsWithNativeABI.insert(&F);
778 // This code needs to rebuild the iterators, as they may be invalidated
779 // by the push_back, taking care that the new range does not include
780 // any functions added by this code.
781 size_t N = i - FnsToInstrument.begin(),
782 Count = e - FnsToInstrument.begin();
783 FnsToInstrument.push_back(&F);
784 i = FnsToInstrument.begin() + N;
785 e = FnsToInstrument.begin() + Count;
787 // Hopefully, nobody will try to indirectly call a vararg
789 } else if (FT->isVarArg()) {
790 UnwrappedFnMap[&F] = &F;
795 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
796 e = FnsToInstrument.end();
798 if (!*i || (*i)->isDeclaration())
801 removeUnreachableBlocks(**i);
803 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
805 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
806 // Build a copy of the list before iterating over it.
807 llvm::SmallVector<BasicBlock *, 4> BBList(
808 depth_first(&(*i)->getEntryBlock()));
810 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
813 Instruction *Inst = &(*i)->front();
815 // DFSanVisitor may split the current basic block, changing the current
816 // instruction's next pointer and moving the next instruction to the
817 // tail block from which we should continue.
818 Instruction *Next = Inst->getNextNode();
819 // DFSanVisitor may delete Inst, so keep track of whether it was a
821 bool IsTerminator = isa<TerminatorInst>(Inst);
822 if (!DFSF.SkipInsts.count(Inst))
823 DFSanVisitor(DFSF).visit(Inst);
830 // We will not necessarily be able to compute the shadow for every phi node
831 // until we have visited every block. Therefore, the code that handles phi
832 // nodes adds them to the PHIFixups list so that they can be properly
834 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
835 i = DFSF.PHIFixups.begin(),
836 e = DFSF.PHIFixups.end();
838 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
840 i->second->setIncomingValue(
841 val, DFSF.getShadow(i->first->getIncomingValue(val)));
845 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
846 // places (i.e. instructions in basic blocks we haven't even begun visiting
847 // yet). To make our life easier, do this work in a pass after the main
849 if (ClDebugNonzeroLabels) {
850 for (Value *V : DFSF.NonZeroChecks) {
852 if (Instruction *I = dyn_cast<Instruction>(V))
853 Pos = I->getNextNode();
855 Pos = &DFSF.F->getEntryBlock().front();
856 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
857 Pos = Pos->getNextNode();
858 IRBuilder<> IRB(Pos);
859 Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
860 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
861 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
862 IRBuilder<> ThenIRB(BI);
863 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
871 Value *DFSanFunction::getArgTLSPtr() {
875 return ArgTLSPtr = DFS.ArgTLS;
877 IRBuilder<> IRB(&F->getEntryBlock().front());
878 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS, {});
881 Value *DFSanFunction::getRetvalTLS() {
885 return RetvalTLSPtr = DFS.RetvalTLS;
887 IRBuilder<> IRB(&F->getEntryBlock().front());
888 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS, {});
891 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
892 IRBuilder<> IRB(Pos);
893 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
896 Value *DFSanFunction::getShadow(Value *V) {
897 if (!isa<Argument>(V) && !isa<Instruction>(V))
898 return DFS.ZeroShadow;
899 Value *&Shadow = ValShadowMap[V];
901 if (Argument *A = dyn_cast<Argument>(V)) {
903 return DFS.ZeroShadow;
905 case DataFlowSanitizer::IA_TLS: {
906 Value *ArgTLSPtr = getArgTLSPtr();
907 Instruction *ArgTLSPos =
908 DFS.ArgTLS ? &*F->getEntryBlock().begin()
909 : cast<Instruction>(ArgTLSPtr)->getNextNode();
910 IRBuilder<> IRB(ArgTLSPos);
911 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
914 case DataFlowSanitizer::IA_Args: {
915 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
916 Function::arg_iterator i = F->arg_begin();
920 assert(Shadow->getType() == DFS.ShadowTy);
924 NonZeroChecks.push_back(Shadow);
926 Shadow = DFS.ZeroShadow;
932 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
933 assert(!ValShadowMap.count(I));
934 assert(Shadow->getType() == DFS.ShadowTy);
935 ValShadowMap[I] = Shadow;
938 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
939 assert(Addr != RetvalTLS && "Reinstrumenting?");
940 IRBuilder<> IRB(Pos);
941 return IRB.CreateIntToPtr(
943 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
948 // Generates IR to compute the union of the two given shadows, inserting it
949 // before Pos. Returns the computed union Value.
950 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
951 if (V1 == DFS.ZeroShadow)
953 if (V2 == DFS.ZeroShadow)
958 auto V1Elems = ShadowElements.find(V1);
959 auto V2Elems = ShadowElements.find(V2);
960 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
961 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
962 V2Elems->second.begin(), V2Elems->second.end())) {
964 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
965 V1Elems->second.begin(), V1Elems->second.end())) {
968 } else if (V1Elems != ShadowElements.end()) {
969 if (V1Elems->second.count(V2))
971 } else if (V2Elems != ShadowElements.end()) {
972 if (V2Elems->second.count(V1))
976 auto Key = std::make_pair(V1, V2);
978 std::swap(Key.first, Key.second);
979 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
980 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
983 IRBuilder<> IRB(Pos);
984 if (AvoidNewBlocks) {
985 CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {V1, V2});
986 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
987 Call->addAttribute(1, Attribute::ZExt);
988 Call->addAttribute(2, Attribute::ZExt);
990 CCS.Block = Pos->getParent();
993 BasicBlock *Head = Pos->getParent();
994 Value *Ne = IRB.CreateICmpNE(V1, V2);
995 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
996 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
997 IRBuilder<> ThenIRB(BI);
998 CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {V1, V2});
999 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1000 Call->addAttribute(1, Attribute::ZExt);
1001 Call->addAttribute(2, Attribute::ZExt);
1003 BasicBlock *Tail = BI->getSuccessor(0);
1004 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1005 Phi->addIncoming(Call, Call->getParent());
1006 Phi->addIncoming(V1, Head);
1012 std::set<Value *> UnionElems;
1013 if (V1Elems != ShadowElements.end()) {
1014 UnionElems = V1Elems->second;
1016 UnionElems.insert(V1);
1018 if (V2Elems != ShadowElements.end()) {
1019 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1021 UnionElems.insert(V2);
1023 ShadowElements[CCS.Shadow] = std::move(UnionElems);
1028 // A convenience function which folds the shadows of each of the operands
1029 // of the provided instruction Inst, inserting the IR before Inst. Returns
1030 // the computed union Value.
1031 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1032 if (Inst->getNumOperands() == 0)
1033 return DFS.ZeroShadow;
1035 Value *Shadow = getShadow(Inst->getOperand(0));
1036 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
1037 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
1042 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1043 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1044 DFSF.setShadow(&I, CombinedShadow);
1047 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1048 // Addr has alignment Align, and take the union of each of those shadows.
1049 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1051 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1052 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1053 AllocaShadowMap.find(AI);
1054 if (i != AllocaShadowMap.end()) {
1055 IRBuilder<> IRB(Pos);
1056 return IRB.CreateLoad(i->second);
1060 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1061 SmallVector<Value *, 2> Objs;
1062 GetUnderlyingObjects(Addr, Objs, Pos->getModule()->getDataLayout());
1063 bool AllConstants = true;
1064 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
1066 if (isa<Function>(*i) || isa<BlockAddress>(*i))
1068 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
1071 AllConstants = false;
1075 return DFS.ZeroShadow;
1077 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1080 return DFS.ZeroShadow;
1082 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1083 LI->setAlignment(ShadowAlign);
1087 IRBuilder<> IRB(Pos);
1088 Value *ShadowAddr1 = IRB.CreateGEP(DFS.ShadowTy, ShadowAddr,
1089 ConstantInt::get(DFS.IntptrTy, 1));
1090 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1091 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
1094 if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
1095 // Fast path for the common case where each byte has identical shadow: load
1096 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1097 // shadow is non-equal.
1098 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1099 IRBuilder<> FallbackIRB(FallbackBB);
1100 CallInst *FallbackCall = FallbackIRB.CreateCall(
1101 DFS.DFSanUnionLoadFn,
1102 {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1103 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1105 // Compare each of the shadows stored in the loaded 64 bits to each other,
1106 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1107 IRBuilder<> IRB(Pos);
1109 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1110 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1111 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1112 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1113 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1114 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1115 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1117 BasicBlock *Head = Pos->getParent();
1118 BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
1120 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1121 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1123 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1124 for (auto Child : Children)
1125 DT.changeImmediateDominator(Child, NewNode);
1128 // In the following code LastBr will refer to the previous basic block's
1129 // conditional branch instruction, whose true successor is fixed up to point
1130 // to the next block during the loop below or to the tail after the final
1132 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1133 ReplaceInstWithInst(Head->getTerminator(), LastBr);
1134 DT.addNewBlock(FallbackBB, Head);
1136 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1137 Ofs += 64 / DFS.ShadowWidth) {
1138 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
1139 DT.addNewBlock(NextBB, LastBr->getParent());
1140 IRBuilder<> NextIRB(NextBB);
1141 WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1142 ConstantInt::get(DFS.IntptrTy, 1));
1143 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1144 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1145 LastBr->setSuccessor(0, NextBB);
1146 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1149 LastBr->setSuccessor(0, Tail);
1150 FallbackIRB.CreateBr(Tail);
1151 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1152 Shadow->addIncoming(FallbackCall, FallbackBB);
1153 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1157 IRBuilder<> IRB(Pos);
1158 CallInst *FallbackCall = IRB.CreateCall(
1159 DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1160 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1161 return FallbackCall;
1164 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1165 auto &DL = LI.getModule()->getDataLayout();
1166 uint64_t Size = DL.getTypeStoreSize(LI.getType());
1168 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1173 if (ClPreserveAlignment) {
1174 Align = LI.getAlignment();
1176 Align = DL.getABITypeAlignment(LI.getType());
1180 IRBuilder<> IRB(&LI);
1181 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1182 if (ClCombinePointerLabelsOnLoad) {
1183 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
1184 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
1186 if (Shadow != DFSF.DFS.ZeroShadow)
1187 DFSF.NonZeroChecks.push_back(Shadow);
1189 DFSF.setShadow(&LI, Shadow);
1192 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1193 Value *Shadow, Instruction *Pos) {
1194 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1195 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1196 AllocaShadowMap.find(AI);
1197 if (i != AllocaShadowMap.end()) {
1198 IRBuilder<> IRB(Pos);
1199 IRB.CreateStore(Shadow, i->second);
1204 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1205 IRBuilder<> IRB(Pos);
1206 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1207 if (Shadow == DFS.ZeroShadow) {
1208 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1209 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1210 Value *ExtShadowAddr =
1211 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1212 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1216 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1217 uint64_t Offset = 0;
1218 if (Size >= ShadowVecSize) {
1219 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1220 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1221 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1222 ShadowVec = IRB.CreateInsertElement(
1223 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1225 Value *ShadowVecAddr =
1226 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1228 Value *CurShadowVecAddr =
1229 IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
1230 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1231 Size -= ShadowVecSize;
1233 } while (Size >= ShadowVecSize);
1234 Offset *= ShadowVecSize;
1237 Value *CurShadowAddr =
1238 IRB.CreateConstGEP1_32(DFS.ShadowTy, ShadowAddr, Offset);
1239 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1245 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1246 auto &DL = SI.getModule()->getDataLayout();
1247 uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
1252 if (ClPreserveAlignment) {
1253 Align = SI.getAlignment();
1255 Align = DL.getABITypeAlignment(SI.getValueOperand()->getType());
1260 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1261 if (ClCombinePointerLabelsOnStore) {
1262 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
1263 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
1265 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
1268 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1269 visitOperandShadowInst(BO);
1272 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1274 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1276 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1277 visitOperandShadowInst(GEPI);
1280 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1281 visitOperandShadowInst(I);
1284 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1285 visitOperandShadowInst(I);
1288 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1289 visitOperandShadowInst(I);
1292 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1293 visitOperandShadowInst(I);
1296 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1297 visitOperandShadowInst(I);
1300 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1301 bool AllLoadsStores = true;
1302 for (User *U : I.users()) {
1303 if (isa<LoadInst>(U))
1306 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1307 if (SI->getPointerOperand() == &I)
1311 AllLoadsStores = false;
1314 if (AllLoadsStores) {
1315 IRBuilder<> IRB(&I);
1316 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1318 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1321 void DFSanVisitor::visitSelectInst(SelectInst &I) {
1322 Value *CondShadow = DFSF.getShadow(I.getCondition());
1323 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1324 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1326 if (isa<VectorType>(I.getCondition()->getType())) {
1329 DFSF.combineShadows(
1330 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
1333 if (TrueShadow == FalseShadow) {
1334 ShadowSel = TrueShadow;
1337 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1339 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
1343 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1344 IRBuilder<> IRB(&I);
1345 Value *ValShadow = DFSF.getShadow(I.getValue());
1346 IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn,
1347 {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
1349 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
1352 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1353 IRBuilder<> IRB(&I);
1354 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1355 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1356 Value *LenShadow = IRB.CreateMul(
1358 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1359 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1360 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1361 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1362 auto *MTI = cast<MemTransferInst>(IRB.CreateCall(I.getCalledValue(),
1363 { DestShadow, SrcShadow,
1365 I.getVolatileCst() }));
1367 if (ClPreserveAlignment) {
1368 MTI->setDestAlignment(I.getDestAlignment() * (DFSF.DFS.ShadowWidth / 8));
1369 MTI->setSrcAlignment(I.getSrcAlignment() * (DFSF.DFS.ShadowWidth / 8));
1371 MTI->setDestAlignment(DFSF.DFS.ShadowWidth / 8);
1372 MTI->setSrcAlignment(DFSF.DFS.ShadowWidth / 8);
1376 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
1377 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
1379 case DataFlowSanitizer::IA_TLS: {
1380 Value *S = DFSF.getShadow(RI.getReturnValue());
1381 IRBuilder<> IRB(&RI);
1382 IRB.CreateStore(S, DFSF.getRetvalTLS());
1385 case DataFlowSanitizer::IA_Args: {
1386 IRBuilder<> IRB(&RI);
1387 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1389 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1391 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1392 RI.setOperand(0, InsShadow);
1399 void DFSanVisitor::visitCallSite(CallSite CS) {
1400 Function *F = CS.getCalledFunction();
1401 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1402 visitOperandShadowInst(*CS.getInstruction());
1406 // Calls to this function are synthesized in wrappers, and we shouldn't
1408 if (F == DFSF.DFS.DFSanVarargWrapperFn)
1411 assert(!(cast<FunctionType>(
1412 CS.getCalledValue()->getType()->getPointerElementType())->isVarArg() &&
1413 dyn_cast<InvokeInst>(CS.getInstruction())));
1415 IRBuilder<> IRB(CS.getInstruction());
1417 DenseMap<Value *, Function *>::iterator i =
1418 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1419 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1420 Function *F = i->second;
1421 switch (DFSF.DFS.getWrapperKind(F)) {
1422 case DataFlowSanitizer::WK_Warning: {
1423 CS.setCalledFunction(F);
1424 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1425 IRB.CreateGlobalStringPtr(F->getName()));
1426 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1429 case DataFlowSanitizer::WK_Discard: {
1430 CS.setCalledFunction(F);
1431 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1434 case DataFlowSanitizer::WK_Functional: {
1435 CS.setCalledFunction(F);
1436 visitOperandShadowInst(*CS.getInstruction());
1439 case DataFlowSanitizer::WK_Custom: {
1440 // Don't try to handle invokes of custom functions, it's too complicated.
1441 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1443 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1444 FunctionType *FT = F->getFunctionType();
1445 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1446 std::string CustomFName = "__dfsw_";
1447 CustomFName += F->getName();
1449 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1450 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1451 CustomFn->copyAttributesFrom(F);
1453 // Custom functions returning non-void will write to the return label.
1454 if (!FT->getReturnType()->isVoidTy()) {
1455 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1456 DFSF.DFS.ReadOnlyNoneAttrs);
1460 std::vector<Value *> Args;
1462 CallSite::arg_iterator i = CS.arg_begin();
1463 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
1464 Type *T = (*i)->getType();
1465 FunctionType *ParamFT;
1466 if (isa<PointerType>(T) &&
1467 (ParamFT = dyn_cast<FunctionType>(
1468 cast<PointerType>(T)->getElementType()))) {
1469 std::string TName = "dfst";
1470 TName += utostr(FT->getNumParams() - n);
1472 TName += F->getName();
1473 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1476 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1483 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1484 Args.push_back(DFSF.getShadow(*i));
1486 if (FT->isVarArg()) {
1487 auto *LabelVATy = ArrayType::get(DFSF.DFS.ShadowTy,
1488 CS.arg_size() - FT->getNumParams());
1489 auto *LabelVAAlloca = new AllocaInst(
1490 LabelVATy, "labelva", &DFSF.F->getEntryBlock().front());
1492 for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
1493 auto LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, n);
1494 IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1497 Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
1500 if (!FT->getReturnType()->isVoidTy()) {
1501 if (!DFSF.LabelReturnAlloca) {
1502 DFSF.LabelReturnAlloca =
1503 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1504 &DFSF.F->getEntryBlock().front());
1506 Args.push_back(DFSF.LabelReturnAlloca);
1509 for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i)
1512 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1513 CustomCI->setCallingConv(CI->getCallingConv());
1514 CustomCI->setAttributes(CI->getAttributes());
1516 if (!FT->getReturnType()->isVoidTy()) {
1517 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1518 DFSF.setShadow(CustomCI, LabelLoad);
1521 CI->replaceAllUsesWith(CustomCI);
1522 CI->eraseFromParent();
1530 FunctionType *FT = cast<FunctionType>(
1531 CS.getCalledValue()->getType()->getPointerElementType());
1532 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1533 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1534 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1535 DFSF.getArgTLS(i, CS.getInstruction()));
1539 Instruction *Next = nullptr;
1540 if (!CS.getType()->isVoidTy()) {
1541 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1542 if (II->getNormalDest()->getSinglePredecessor()) {
1543 Next = &II->getNormalDest()->front();
1546 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
1547 Next = &NewBB->front();
1550 assert(CS->getIterator() != CS->getParent()->end());
1551 Next = CS->getNextNode();
1554 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1555 IRBuilder<> NextIRB(Next);
1556 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1557 DFSF.SkipInsts.insert(LI);
1558 DFSF.setShadow(CS.getInstruction(), LI);
1559 DFSF.NonZeroChecks.push_back(LI);
1563 // Do all instrumentation for IA_Args down here to defer tampering with the
1564 // CFG in a way that SplitEdge may be able to detect.
1565 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1566 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
1568 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1569 std::vector<Value *> Args;
1571 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1572 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1576 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1577 Args.push_back(DFSF.getShadow(*i));
1579 if (FT->isVarArg()) {
1580 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1581 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1582 AllocaInst *VarArgShadow =
1583 new AllocaInst(VarArgArrayTy, "", &DFSF.F->getEntryBlock().front());
1584 Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
1585 for (unsigned n = 0; i != e; ++i, ++n) {
1588 IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
1594 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1595 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1598 NewCS = IRB.CreateCall(Func, Args);
1600 NewCS.setCallingConv(CS.getCallingConv());
1601 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1602 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1603 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType())));
1606 ExtractValueInst *ExVal =
1607 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1608 DFSF.SkipInsts.insert(ExVal);
1609 ExtractValueInst *ExShadow =
1610 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1611 DFSF.SkipInsts.insert(ExShadow);
1612 DFSF.setShadow(ExVal, ExShadow);
1613 DFSF.NonZeroChecks.push_back(ExShadow);
1615 CS.getInstruction()->replaceAllUsesWith(ExVal);
1618 CS.getInstruction()->eraseFromParent();
1622 void DFSanVisitor::visitPHINode(PHINode &PN) {
1624 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1626 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1627 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1628 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1630 ShadowPN->addIncoming(UndefShadow, *i);
1633 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1634 DFSF.setShadow(&PN, ShadowPN);