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 // External symbol to be used when generating the shadow address for
76 // architectures with multiple VMAs. Instead of using a constant integer
77 // the runtime will set the external mask based on the VMA range.
78 static const char *const kDFSanExternShadowPtrMask = "__dfsan_shadow_ptr_mask";
80 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
81 // alignment requirements provided by the input IR are correct. For example,
82 // if the input IR contains a load with alignment 8, this flag will cause
83 // the shadow load to have alignment 16. This flag is disabled by default as
84 // we have unfortunately encountered too much code (including Clang itself;
85 // see PR14291) which performs misaligned access.
86 static cl::opt<bool> ClPreserveAlignment(
87 "dfsan-preserve-alignment",
88 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
91 // The ABI list files control how shadow parameters are passed. The pass treats
92 // every function labelled "uninstrumented" in the ABI list file as conforming
93 // to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
94 // additional annotations for those functions, a call to one of those functions
95 // will produce a warning message, as the labelling behaviour of the function is
96 // unknown. The other supported annotations are "functional" and "discard",
97 // which are described below under DataFlowSanitizer::WrapperKind.
98 static cl::list<std::string> ClABIListFiles(
100 cl::desc("File listing native ABI functions and how the pass treats them"),
103 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
104 // functions (see DataFlowSanitizer::InstrumentedABI below).
105 static cl::opt<bool> ClArgsABI(
107 cl::desc("Use the argument ABI rather than the TLS ABI"),
110 // Controls whether the pass includes or ignores the labels of pointers in load
112 static cl::opt<bool> ClCombinePointerLabelsOnLoad(
113 "dfsan-combine-pointer-labels-on-load",
114 cl::desc("Combine the label of the pointer with the label of the data when "
115 "loading from memory."),
116 cl::Hidden, cl::init(true));
118 // Controls whether the pass includes or ignores the labels of pointers in
119 // stores instructions.
120 static cl::opt<bool> ClCombinePointerLabelsOnStore(
121 "dfsan-combine-pointer-labels-on-store",
122 cl::desc("Combine the label of the pointer with the label of the data when "
123 "storing in memory."),
124 cl::Hidden, cl::init(false));
126 static cl::opt<bool> ClDebugNonzeroLabels(
127 "dfsan-debug-nonzero-labels",
128 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
129 "load or return with a nonzero label"),
135 StringRef GetGlobalTypeString(const GlobalValue &G) {
136 // Types of GlobalVariables are always pointer types.
137 Type *GType = G.getValueType();
138 // For now we support blacklisting struct types only.
139 if (StructType *SGType = dyn_cast<StructType>(GType)) {
140 if (!SGType->isLiteral())
141 return SGType->getName();
143 return "<unknown type>";
147 std::unique_ptr<SpecialCaseList> SCL;
152 void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
154 /// Returns whether either this function or its source file are listed in the
156 bool isIn(const Function &F, StringRef Category) const {
157 return isIn(*F.getParent(), Category) ||
158 SCL->inSection("fun", F.getName(), Category);
161 /// Returns whether this global alias is listed in the given category.
163 /// If GA aliases a function, the alias's name is matched as a function name
164 /// would be. Similarly, aliases of globals are matched like globals.
165 bool isIn(const GlobalAlias &GA, StringRef Category) const {
166 if (isIn(*GA.getParent(), Category))
169 if (isa<FunctionType>(GA.getValueType()))
170 return SCL->inSection("fun", GA.getName(), Category);
172 return SCL->inSection("global", GA.getName(), Category) ||
173 SCL->inSection("type", GetGlobalTypeString(GA), Category);
176 /// Returns whether this module is listed in the given category.
177 bool isIn(const Module &M, StringRef Category) const {
178 return SCL->inSection("src", M.getModuleIdentifier(), Category);
182 class DataFlowSanitizer : public ModulePass {
183 friend struct DFSanFunction;
184 friend class DFSanVisitor;
190 /// Which ABI should be used for instrumented functions?
191 enum InstrumentedABI {
192 /// Argument and return value labels are passed through additional
193 /// arguments and by modifying the return type.
196 /// Argument and return value labels are passed through TLS variables
197 /// __dfsan_arg_tls and __dfsan_retval_tls.
201 /// How should calls to uninstrumented functions be handled?
203 /// This function is present in an uninstrumented form but we don't know
204 /// how it should be handled. Print a warning and call the function anyway.
205 /// Don't label the return value.
208 /// This function does not write to (user-accessible) memory, and its return
209 /// value is unlabelled.
212 /// This function does not write to (user-accessible) memory, and the label
213 /// of its return value is the union of the label of its arguments.
216 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
217 /// where F is the name of the function. This function may wrap the
218 /// original function or provide its own implementation. This is similar to
219 /// the IA_Args ABI, except that IA_Args uses a struct return type to
220 /// pass the return value shadow in a register, while WK_Custom uses an
221 /// extra pointer argument to return the shadow. This allows the wrapped
222 /// form of the function type to be expressed in C.
228 IntegerType *ShadowTy;
229 PointerType *ShadowPtrTy;
230 IntegerType *IntptrTy;
231 ConstantInt *ZeroShadow;
232 ConstantInt *ShadowPtrMask;
233 ConstantInt *ShadowPtrMul;
236 void *(*GetArgTLSPtr)();
237 void *(*GetRetvalTLSPtr)();
239 Constant *GetRetvalTLS;
240 Constant *ExternalShadowMask;
241 FunctionType *DFSanUnionFnTy;
242 FunctionType *DFSanUnionLoadFnTy;
243 FunctionType *DFSanUnimplementedFnTy;
244 FunctionType *DFSanSetLabelFnTy;
245 FunctionType *DFSanNonzeroLabelFnTy;
246 FunctionType *DFSanVarargWrapperFnTy;
247 Constant *DFSanUnionFn;
248 Constant *DFSanCheckedUnionFn;
249 Constant *DFSanUnionLoadFn;
250 Constant *DFSanUnimplementedFn;
251 Constant *DFSanSetLabelFn;
252 Constant *DFSanNonzeroLabelFn;
253 Constant *DFSanVarargWrapperFn;
254 MDNode *ColdCallWeights;
255 DFSanABIList ABIList;
256 DenseMap<Value *, Function *> UnwrappedFnMap;
257 AttrBuilder ReadOnlyNoneAttrs;
258 bool DFSanRuntimeShadowMask;
260 Value *getShadowAddress(Value *Addr, Instruction *Pos);
261 bool isInstrumented(const Function *F);
262 bool isInstrumented(const GlobalAlias *GA);
263 FunctionType *getArgsFunctionType(FunctionType *T);
264 FunctionType *getTrampolineFunctionType(FunctionType *T);
265 FunctionType *getCustomFunctionType(FunctionType *T);
266 InstrumentedABI getInstrumentedABI();
267 WrapperKind getWrapperKind(Function *F);
268 void addGlobalNamePrefix(GlobalValue *GV);
269 Function *buildWrapperFunction(Function *F, StringRef NewFName,
270 GlobalValue::LinkageTypes NewFLink,
271 FunctionType *NewFT);
272 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
276 const std::vector<std::string> &ABIListFiles = std::vector<std::string>(),
277 void *(*getArgTLS)() = nullptr, void *(*getRetValTLS)() = nullptr);
279 bool doInitialization(Module &M) override;
280 bool runOnModule(Module &M) override;
283 struct DFSanFunction {
284 DataFlowSanitizer &DFS;
287 DataFlowSanitizer::InstrumentedABI IA;
291 AllocaInst *LabelReturnAlloca;
292 DenseMap<Value *, Value *> ValShadowMap;
293 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
294 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
295 DenseSet<Instruction *> SkipInsts;
296 std::vector<Value *> NonZeroChecks;
299 struct CachedCombinedShadow {
303 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
304 CachedCombinedShadows;
305 DenseMap<Value *, std::set<Value *>> ShadowElements;
307 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
308 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
309 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
310 LabelReturnAlloca(nullptr) {
312 // FIXME: Need to track down the register allocator issue which causes poor
313 // performance in pathological cases with large numbers of basic blocks.
314 AvoidNewBlocks = F->size() > 1000;
316 Value *getArgTLSPtr();
317 Value *getArgTLS(unsigned Index, Instruction *Pos);
318 Value *getRetvalTLS();
319 Value *getShadow(Value *V);
320 void setShadow(Instruction *I, Value *Shadow);
321 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
322 Value *combineOperandShadows(Instruction *Inst);
323 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
325 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
329 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
332 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
334 const DataLayout &getDataLayout() const {
335 return DFSF.F->getParent()->getDataLayout();
338 void visitOperandShadowInst(Instruction &I);
340 void visitBinaryOperator(BinaryOperator &BO);
341 void visitCastInst(CastInst &CI);
342 void visitCmpInst(CmpInst &CI);
343 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
344 void visitLoadInst(LoadInst &LI);
345 void visitStoreInst(StoreInst &SI);
346 void visitReturnInst(ReturnInst &RI);
347 void visitCallSite(CallSite CS);
348 void visitPHINode(PHINode &PN);
349 void visitExtractElementInst(ExtractElementInst &I);
350 void visitInsertElementInst(InsertElementInst &I);
351 void visitShuffleVectorInst(ShuffleVectorInst &I);
352 void visitExtractValueInst(ExtractValueInst &I);
353 void visitInsertValueInst(InsertValueInst &I);
354 void visitAllocaInst(AllocaInst &I);
355 void visitSelectInst(SelectInst &I);
356 void visitMemSetInst(MemSetInst &I);
357 void visitMemTransferInst(MemTransferInst &I);
362 char DataFlowSanitizer::ID;
363 INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
364 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
367 llvm::createDataFlowSanitizerPass(const std::vector<std::string> &ABIListFiles,
368 void *(*getArgTLS)(),
369 void *(*getRetValTLS)()) {
370 return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS);
373 DataFlowSanitizer::DataFlowSanitizer(
374 const std::vector<std::string> &ABIListFiles, void *(*getArgTLS)(),
375 void *(*getRetValTLS)())
376 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
377 DFSanRuntimeShadowMask(false) {
378 std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
379 AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(),
380 ClABIListFiles.end());
381 ABIList.set(SpecialCaseList::createOrDie(AllABIListFiles));
384 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
385 llvm::SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
386 ArgTypes.append(T->getNumParams(), ShadowTy);
388 ArgTypes.push_back(ShadowPtrTy);
389 Type *RetType = T->getReturnType();
390 if (!RetType->isVoidTy())
391 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
392 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
395 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
396 assert(!T->isVarArg());
397 llvm::SmallVector<Type *, 4> ArgTypes;
398 ArgTypes.push_back(T->getPointerTo());
399 ArgTypes.append(T->param_begin(), T->param_end());
400 ArgTypes.append(T->getNumParams(), ShadowTy);
401 Type *RetType = T->getReturnType();
402 if (!RetType->isVoidTy())
403 ArgTypes.push_back(ShadowPtrTy);
404 return FunctionType::get(T->getReturnType(), ArgTypes, false);
407 FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
408 llvm::SmallVector<Type *, 4> ArgTypes;
409 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
412 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
413 *i)->getElementType()))) {
414 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
415 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
417 ArgTypes.push_back(*i);
420 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
421 ArgTypes.push_back(ShadowTy);
423 ArgTypes.push_back(ShadowPtrTy);
424 Type *RetType = T->getReturnType();
425 if (!RetType->isVoidTy())
426 ArgTypes.push_back(ShadowPtrTy);
427 return FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg());
430 bool DataFlowSanitizer::doInitialization(Module &M) {
431 llvm::Triple TargetTriple(M.getTargetTriple());
432 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
433 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
434 TargetTriple.getArch() == llvm::Triple::mips64el;
435 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64 ||
436 TargetTriple.getArch() == llvm::Triple::aarch64_be;
438 const DataLayout &DL = M.getDataLayout();
441 Ctx = &M.getContext();
442 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
443 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
444 IntptrTy = DL.getIntPtrType(*Ctx);
445 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
446 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
448 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
450 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
451 // AArch64 supports multiple VMAs and the shadow mask is set at runtime.
453 DFSanRuntimeShadowMask = true;
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 AttributeList::ReturnIndex,
547 AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
549 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
551 NewF->removeAttributes(AttributeList::FunctionIndex,
552 AttrBuilder().addAttribute("split-stack"));
553 CallInst::Create(DFSanVarargWrapperFn,
554 IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
556 new UnreachableInst(*Ctx, BB);
558 std::vector<Value *> Args;
559 unsigned n = FT->getNumParams();
560 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
561 Args.push_back(&*ai);
562 CallInst *CI = CallInst::Create(F, Args, "", BB);
563 if (FT->getReturnType()->isVoidTy())
564 ReturnInst::Create(*Ctx, BB);
566 ReturnInst::Create(*Ctx, CI, BB);
572 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
574 FunctionType *FTT = getTrampolineFunctionType(FT);
575 Constant *C = Mod->getOrInsertFunction(FName, FTT);
576 Function *F = dyn_cast<Function>(C);
577 if (F && F->isDeclaration()) {
578 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
579 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
580 std::vector<Value *> Args;
581 Function::arg_iterator AI = F->arg_begin(); ++AI;
582 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
583 Args.push_back(&*AI);
584 CallInst *CI = CallInst::Create(&*F->arg_begin(), Args, "", BB);
586 if (FT->getReturnType()->isVoidTy())
587 RI = ReturnInst::Create(*Ctx, BB);
589 RI = ReturnInst::Create(*Ctx, CI, BB);
591 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
592 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
593 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
594 DFSF.ValShadowMap[&*ValAI] = &*ShadowAI;
595 DFSanVisitor(DFSF).visitCallInst(*CI);
596 if (!FT->getReturnType()->isVoidTy())
597 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
598 &*std::prev(F->arg_end()), RI);
604 bool DataFlowSanitizer::runOnModule(Module &M) {
605 if (ABIList.isIn(M, "skip"))
609 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
610 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
611 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
612 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
614 if (!GetRetvalTLSPtr) {
615 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
616 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
617 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
621 Mod->getOrInsertGlobal(kDFSanExternShadowPtrMask, IntptrTy);
623 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
624 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
625 F->addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
626 F->addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
627 F->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
628 F->addParamAttr(0, Attribute::ZExt);
629 F->addParamAttr(1, Attribute::ZExt);
631 DFSanCheckedUnionFn = Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy);
632 if (Function *F = dyn_cast<Function>(DFSanCheckedUnionFn)) {
633 F->addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
634 F->addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
635 F->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
636 F->addParamAttr(0, Attribute::ZExt);
637 F->addParamAttr(1, Attribute::ZExt);
640 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
641 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
642 F->addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
643 F->addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
644 F->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
646 DFSanUnimplementedFn =
647 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
649 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
650 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
651 F->addParamAttr(0, Attribute::ZExt);
653 DFSanNonzeroLabelFn =
654 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
655 DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
656 DFSanVarargWrapperFnTy);
658 std::vector<Function *> FnsToInstrument;
659 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
660 for (Function &i : M) {
661 if (!i.isIntrinsic() &&
662 &i != DFSanUnionFn &&
663 &i != DFSanCheckedUnionFn &&
664 &i != DFSanUnionLoadFn &&
665 &i != DFSanUnimplementedFn &&
666 &i != DFSanSetLabelFn &&
667 &i != DFSanNonzeroLabelFn &&
668 &i != DFSanVarargWrapperFn)
669 FnsToInstrument.push_back(&i);
672 // Give function aliases prefixes when necessary, and build wrappers where the
673 // instrumentedness is inconsistent.
674 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
675 GlobalAlias *GA = &*i;
677 // Don't stop on weak. We assume people aren't playing games with the
678 // instrumentedness of overridden weak aliases.
679 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
680 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
681 if (GAInst && FInst) {
682 addGlobalNamePrefix(GA);
683 } else if (GAInst != FInst) {
684 // Non-instrumented alias of an instrumented function, or vice versa.
685 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
686 // below will take care of instrumenting it.
688 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
689 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
691 GA->eraseFromParent();
692 FnsToInstrument.push_back(NewF);
697 ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
698 .addAttribute(Attribute::ReadNone);
700 // First, change the ABI of every function in the module. ABI-listed
701 // functions keep their original ABI and get a wrapper function.
702 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
703 e = FnsToInstrument.end();
706 FunctionType *FT = F.getFunctionType();
708 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
709 FT->getReturnType()->isVoidTy());
711 if (isInstrumented(&F)) {
712 // Instrumented functions get a 'dfs$' prefix. This allows us to more
713 // easily identify cases of mismatching ABIs.
714 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
715 FunctionType *NewFT = getArgsFunctionType(FT);
716 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
717 NewF->copyAttributesFrom(&F);
718 NewF->removeAttributes(
719 AttributeList::ReturnIndex,
720 AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
721 for (Function::arg_iterator FArg = F.arg_begin(),
722 NewFArg = NewF->arg_begin(),
723 FArgEnd = F.arg_end();
724 FArg != FArgEnd; ++FArg, ++NewFArg) {
725 FArg->replaceAllUsesWith(&*NewFArg);
727 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
729 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
731 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
734 BA->replaceAllUsesWith(
735 BlockAddress::get(NewF, BA->getBasicBlock()));
739 F.replaceAllUsesWith(
740 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
744 addGlobalNamePrefix(NewF);
746 addGlobalNamePrefix(&F);
748 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
749 // Build a wrapper function for F. The wrapper simply calls F, and is
750 // added to FnsToInstrument so that any instrumentation according to its
751 // WrapperKind is done in the second pass below.
752 FunctionType *NewFT = getInstrumentedABI() == IA_Args
753 ? getArgsFunctionType(FT)
755 Function *NewF = buildWrapperFunction(
756 &F, std::string("dfsw$") + std::string(F.getName()),
757 GlobalValue::LinkOnceODRLinkage, NewFT);
758 if (getInstrumentedABI() == IA_TLS)
759 NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs);
761 Value *WrappedFnCst =
762 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
763 F.replaceAllUsesWith(WrappedFnCst);
765 UnwrappedFnMap[WrappedFnCst] = &F;
768 if (!F.isDeclaration()) {
769 // This function is probably defining an interposition of an
770 // uninstrumented function and hence needs to keep the original ABI.
771 // But any functions it may call need to use the instrumented ABI, so
772 // we instrument it in a mode which preserves the original ABI.
773 FnsWithNativeABI.insert(&F);
775 // This code needs to rebuild the iterators, as they may be invalidated
776 // by the push_back, taking care that the new range does not include
777 // any functions added by this code.
778 size_t N = i - FnsToInstrument.begin(),
779 Count = e - FnsToInstrument.begin();
780 FnsToInstrument.push_back(&F);
781 i = FnsToInstrument.begin() + N;
782 e = FnsToInstrument.begin() + Count;
784 // Hopefully, nobody will try to indirectly call a vararg
786 } else if (FT->isVarArg()) {
787 UnwrappedFnMap[&F] = &F;
792 for (Function *i : FnsToInstrument) {
793 if (!i || i->isDeclaration())
796 removeUnreachableBlocks(*i);
798 DFSanFunction DFSF(*this, i, FnsWithNativeABI.count(i));
800 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
801 // Build a copy of the list before iterating over it.
802 llvm::SmallVector<BasicBlock *, 4> BBList(depth_first(&i->getEntryBlock()));
804 for (BasicBlock *i : BBList) {
805 Instruction *Inst = &i->front();
807 // DFSanVisitor may split the current basic block, changing the current
808 // instruction's next pointer and moving the next instruction to the
809 // tail block from which we should continue.
810 Instruction *Next = Inst->getNextNode();
811 // DFSanVisitor may delete Inst, so keep track of whether it was a
813 bool IsTerminator = isa<TerminatorInst>(Inst);
814 if (!DFSF.SkipInsts.count(Inst))
815 DFSanVisitor(DFSF).visit(Inst);
822 // We will not necessarily be able to compute the shadow for every phi node
823 // until we have visited every block. Therefore, the code that handles phi
824 // nodes adds them to the PHIFixups list so that they can be properly
826 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
827 i = DFSF.PHIFixups.begin(),
828 e = DFSF.PHIFixups.end();
830 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
832 i->second->setIncomingValue(
833 val, DFSF.getShadow(i->first->getIncomingValue(val)));
837 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
838 // places (i.e. instructions in basic blocks we haven't even begun visiting
839 // yet). To make our life easier, do this work in a pass after the main
841 if (ClDebugNonzeroLabels) {
842 for (Value *V : DFSF.NonZeroChecks) {
844 if (Instruction *I = dyn_cast<Instruction>(V))
845 Pos = I->getNextNode();
847 Pos = &DFSF.F->getEntryBlock().front();
848 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
849 Pos = Pos->getNextNode();
850 IRBuilder<> IRB(Pos);
851 Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
852 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
853 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
854 IRBuilder<> ThenIRB(BI);
855 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
863 Value *DFSanFunction::getArgTLSPtr() {
867 return ArgTLSPtr = DFS.ArgTLS;
869 IRBuilder<> IRB(&F->getEntryBlock().front());
870 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS, {});
873 Value *DFSanFunction::getRetvalTLS() {
877 return RetvalTLSPtr = DFS.RetvalTLS;
879 IRBuilder<> IRB(&F->getEntryBlock().front());
880 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS, {});
883 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
884 IRBuilder<> IRB(Pos);
885 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
888 Value *DFSanFunction::getShadow(Value *V) {
889 if (!isa<Argument>(V) && !isa<Instruction>(V))
890 return DFS.ZeroShadow;
891 Value *&Shadow = ValShadowMap[V];
893 if (Argument *A = dyn_cast<Argument>(V)) {
895 return DFS.ZeroShadow;
897 case DataFlowSanitizer::IA_TLS: {
898 Value *ArgTLSPtr = getArgTLSPtr();
899 Instruction *ArgTLSPos =
900 DFS.ArgTLS ? &*F->getEntryBlock().begin()
901 : cast<Instruction>(ArgTLSPtr)->getNextNode();
902 IRBuilder<> IRB(ArgTLSPos);
903 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
906 case DataFlowSanitizer::IA_Args: {
907 unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2;
908 Function::arg_iterator i = F->arg_begin();
912 assert(Shadow->getType() == DFS.ShadowTy);
916 NonZeroChecks.push_back(Shadow);
918 Shadow = DFS.ZeroShadow;
924 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
925 assert(!ValShadowMap.count(I));
926 assert(Shadow->getType() == DFS.ShadowTy);
927 ValShadowMap[I] = Shadow;
930 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
931 assert(Addr != RetvalTLS && "Reinstrumenting?");
932 IRBuilder<> IRB(Pos);
933 Value *ShadowPtrMaskValue;
934 if (DFSanRuntimeShadowMask)
935 ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask);
937 ShadowPtrMaskValue = ShadowPtrMask;
938 return IRB.CreateIntToPtr(
940 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy),
941 IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy)),
946 // Generates IR to compute the union of the two given shadows, inserting it
947 // before Pos. Returns the computed union Value.
948 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
949 if (V1 == DFS.ZeroShadow)
951 if (V2 == DFS.ZeroShadow)
956 auto V1Elems = ShadowElements.find(V1);
957 auto V2Elems = ShadowElements.find(V2);
958 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
959 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
960 V2Elems->second.begin(), V2Elems->second.end())) {
962 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
963 V1Elems->second.begin(), V1Elems->second.end())) {
966 } else if (V1Elems != ShadowElements.end()) {
967 if (V1Elems->second.count(V2))
969 } else if (V2Elems != ShadowElements.end()) {
970 if (V2Elems->second.count(V1))
974 auto Key = std::make_pair(V1, V2);
976 std::swap(Key.first, Key.second);
977 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
978 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
981 IRBuilder<> IRB(Pos);
982 if (AvoidNewBlocks) {
983 CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {V1, V2});
984 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
985 Call->addParamAttr(0, Attribute::ZExt);
986 Call->addParamAttr(1, Attribute::ZExt);
988 CCS.Block = Pos->getParent();
991 BasicBlock *Head = Pos->getParent();
992 Value *Ne = IRB.CreateICmpNE(V1, V2);
993 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
994 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
995 IRBuilder<> ThenIRB(BI);
996 CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {V1, V2});
997 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
998 Call->addParamAttr(0, Attribute::ZExt);
999 Call->addParamAttr(1, Attribute::ZExt);
1001 BasicBlock *Tail = BI->getSuccessor(0);
1002 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1003 Phi->addIncoming(Call, Call->getParent());
1004 Phi->addIncoming(V1, Head);
1010 std::set<Value *> UnionElems;
1011 if (V1Elems != ShadowElements.end()) {
1012 UnionElems = V1Elems->second;
1014 UnionElems.insert(V1);
1016 if (V2Elems != ShadowElements.end()) {
1017 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1019 UnionElems.insert(V2);
1021 ShadowElements[CCS.Shadow] = std::move(UnionElems);
1026 // A convenience function which folds the shadows of each of the operands
1027 // of the provided instruction Inst, inserting the IR before Inst. Returns
1028 // the computed union Value.
1029 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1030 if (Inst->getNumOperands() == 0)
1031 return DFS.ZeroShadow;
1033 Value *Shadow = getShadow(Inst->getOperand(0));
1034 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
1035 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
1040 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1041 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1042 DFSF.setShadow(&I, CombinedShadow);
1045 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1046 // Addr has alignment Align, and take the union of each of those shadows.
1047 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1049 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1050 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1051 AllocaShadowMap.find(AI);
1052 if (i != AllocaShadowMap.end()) {
1053 IRBuilder<> IRB(Pos);
1054 return IRB.CreateLoad(i->second);
1058 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1059 SmallVector<Value *, 2> Objs;
1060 GetUnderlyingObjects(Addr, Objs, Pos->getModule()->getDataLayout());
1061 bool AllConstants = true;
1062 for (Value *Obj : Objs) {
1063 if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
1065 if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
1068 AllConstants = false;
1072 return DFS.ZeroShadow;
1074 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1077 return DFS.ZeroShadow;
1079 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1080 LI->setAlignment(ShadowAlign);
1084 IRBuilder<> IRB(Pos);
1085 Value *ShadowAddr1 = IRB.CreateGEP(DFS.ShadowTy, ShadowAddr,
1086 ConstantInt::get(DFS.IntptrTy, 1));
1087 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1088 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
1091 if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
1092 // Fast path for the common case where each byte has identical shadow: load
1093 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1094 // shadow is non-equal.
1095 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1096 IRBuilder<> FallbackIRB(FallbackBB);
1097 CallInst *FallbackCall = FallbackIRB.CreateCall(
1098 DFS.DFSanUnionLoadFn,
1099 {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1100 FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1102 // Compare each of the shadows stored in the loaded 64 bits to each other,
1103 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1104 IRBuilder<> IRB(Pos);
1106 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1107 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1108 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1109 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1110 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1111 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1112 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1114 BasicBlock *Head = Pos->getParent();
1115 BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
1117 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1118 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1120 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1121 for (auto Child : Children)
1122 DT.changeImmediateDominator(Child, NewNode);
1125 // In the following code LastBr will refer to the previous basic block's
1126 // conditional branch instruction, whose true successor is fixed up to point
1127 // to the next block during the loop below or to the tail after the final
1129 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1130 ReplaceInstWithInst(Head->getTerminator(), LastBr);
1131 DT.addNewBlock(FallbackBB, Head);
1133 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1134 Ofs += 64 / DFS.ShadowWidth) {
1135 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
1136 DT.addNewBlock(NextBB, LastBr->getParent());
1137 IRBuilder<> NextIRB(NextBB);
1138 WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1139 ConstantInt::get(DFS.IntptrTy, 1));
1140 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1141 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1142 LastBr->setSuccessor(0, NextBB);
1143 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1146 LastBr->setSuccessor(0, Tail);
1147 FallbackIRB.CreateBr(Tail);
1148 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1149 Shadow->addIncoming(FallbackCall, FallbackBB);
1150 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1154 IRBuilder<> IRB(Pos);
1155 CallInst *FallbackCall = IRB.CreateCall(
1156 DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1157 FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1158 return FallbackCall;
1161 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1162 auto &DL = LI.getModule()->getDataLayout();
1163 uint64_t Size = DL.getTypeStoreSize(LI.getType());
1165 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1170 if (ClPreserveAlignment) {
1171 Align = LI.getAlignment();
1173 Align = DL.getABITypeAlignment(LI.getType());
1177 IRBuilder<> IRB(&LI);
1178 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1179 if (ClCombinePointerLabelsOnLoad) {
1180 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
1181 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
1183 if (Shadow != DFSF.DFS.ZeroShadow)
1184 DFSF.NonZeroChecks.push_back(Shadow);
1186 DFSF.setShadow(&LI, Shadow);
1189 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1190 Value *Shadow, Instruction *Pos) {
1191 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1192 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1193 AllocaShadowMap.find(AI);
1194 if (i != AllocaShadowMap.end()) {
1195 IRBuilder<> IRB(Pos);
1196 IRB.CreateStore(Shadow, i->second);
1201 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1202 IRBuilder<> IRB(Pos);
1203 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1204 if (Shadow == DFS.ZeroShadow) {
1205 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1206 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1207 Value *ExtShadowAddr =
1208 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1209 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1213 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1214 uint64_t Offset = 0;
1215 if (Size >= ShadowVecSize) {
1216 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1217 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1218 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1219 ShadowVec = IRB.CreateInsertElement(
1220 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1222 Value *ShadowVecAddr =
1223 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1225 Value *CurShadowVecAddr =
1226 IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
1227 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1228 Size -= ShadowVecSize;
1230 } while (Size >= ShadowVecSize);
1231 Offset *= ShadowVecSize;
1234 Value *CurShadowAddr =
1235 IRB.CreateConstGEP1_32(DFS.ShadowTy, ShadowAddr, Offset);
1236 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1242 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1243 auto &DL = SI.getModule()->getDataLayout();
1244 uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
1249 if (ClPreserveAlignment) {
1250 Align = SI.getAlignment();
1252 Align = DL.getABITypeAlignment(SI.getValueOperand()->getType());
1257 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1258 if (ClCombinePointerLabelsOnStore) {
1259 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
1260 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
1262 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
1265 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1266 visitOperandShadowInst(BO);
1269 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1271 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1273 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1274 visitOperandShadowInst(GEPI);
1277 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1278 visitOperandShadowInst(I);
1281 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1282 visitOperandShadowInst(I);
1285 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1286 visitOperandShadowInst(I);
1289 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1290 visitOperandShadowInst(I);
1293 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1294 visitOperandShadowInst(I);
1297 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1298 bool AllLoadsStores = true;
1299 for (User *U : I.users()) {
1300 if (isa<LoadInst>(U))
1303 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1304 if (SI->getPointerOperand() == &I)
1308 AllLoadsStores = false;
1311 if (AllLoadsStores) {
1312 IRBuilder<> IRB(&I);
1313 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1315 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1318 void DFSanVisitor::visitSelectInst(SelectInst &I) {
1319 Value *CondShadow = DFSF.getShadow(I.getCondition());
1320 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1321 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1323 if (isa<VectorType>(I.getCondition()->getType())) {
1326 DFSF.combineShadows(
1327 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
1330 if (TrueShadow == FalseShadow) {
1331 ShadowSel = TrueShadow;
1334 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1336 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
1340 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1341 IRBuilder<> IRB(&I);
1342 Value *ValShadow = DFSF.getShadow(I.getValue());
1343 IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn,
1344 {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
1346 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
1349 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1350 IRBuilder<> IRB(&I);
1351 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1352 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1353 Value *LenShadow = IRB.CreateMul(
1355 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1357 if (ClPreserveAlignment) {
1358 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1359 ConstantInt::get(I.getAlignmentCst()->getType(),
1360 DFSF.DFS.ShadowWidth / 8));
1362 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1363 DFSF.DFS.ShadowWidth / 8);
1365 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1366 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1367 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1368 IRB.CreateCall(I.getCalledValue(), {DestShadow, SrcShadow, LenShadow,
1369 AlignShadow, I.getVolatileCst()});
1372 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
1373 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
1375 case DataFlowSanitizer::IA_TLS: {
1376 Value *S = DFSF.getShadow(RI.getReturnValue());
1377 IRBuilder<> IRB(&RI);
1378 IRB.CreateStore(S, DFSF.getRetvalTLS());
1381 case DataFlowSanitizer::IA_Args: {
1382 IRBuilder<> IRB(&RI);
1383 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1385 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1387 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1388 RI.setOperand(0, InsShadow);
1395 void DFSanVisitor::visitCallSite(CallSite CS) {
1396 Function *F = CS.getCalledFunction();
1397 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1398 visitOperandShadowInst(*CS.getInstruction());
1402 // Calls to this function are synthesized in wrappers, and we shouldn't
1404 if (F == DFSF.DFS.DFSanVarargWrapperFn)
1407 IRBuilder<> IRB(CS.getInstruction());
1409 DenseMap<Value *, Function *>::iterator i =
1410 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1411 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1412 Function *F = i->second;
1413 switch (DFSF.DFS.getWrapperKind(F)) {
1414 case DataFlowSanitizer::WK_Warning: {
1415 CS.setCalledFunction(F);
1416 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1417 IRB.CreateGlobalStringPtr(F->getName()));
1418 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1421 case DataFlowSanitizer::WK_Discard: {
1422 CS.setCalledFunction(F);
1423 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1426 case DataFlowSanitizer::WK_Functional: {
1427 CS.setCalledFunction(F);
1428 visitOperandShadowInst(*CS.getInstruction());
1431 case DataFlowSanitizer::WK_Custom: {
1432 // Don't try to handle invokes of custom functions, it's too complicated.
1433 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1435 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1436 FunctionType *FT = F->getFunctionType();
1437 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1438 std::string CustomFName = "__dfsw_";
1439 CustomFName += F->getName();
1441 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1442 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1443 CustomFn->copyAttributesFrom(F);
1445 // Custom functions returning non-void will write to the return label.
1446 if (!FT->getReturnType()->isVoidTy()) {
1447 CustomFn->removeAttributes(AttributeList::FunctionIndex,
1448 DFSF.DFS.ReadOnlyNoneAttrs);
1452 std::vector<Value *> Args;
1454 CallSite::arg_iterator i = CS.arg_begin();
1455 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
1456 Type *T = (*i)->getType();
1457 FunctionType *ParamFT;
1458 if (isa<PointerType>(T) &&
1459 (ParamFT = dyn_cast<FunctionType>(
1460 cast<PointerType>(T)->getElementType()))) {
1461 std::string TName = "dfst";
1462 TName += utostr(FT->getNumParams() - n);
1464 TName += F->getName();
1465 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1468 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1475 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1476 Args.push_back(DFSF.getShadow(*i));
1478 if (FT->isVarArg()) {
1479 auto *LabelVATy = ArrayType::get(DFSF.DFS.ShadowTy,
1480 CS.arg_size() - FT->getNumParams());
1481 auto *LabelVAAlloca = new AllocaInst(
1482 LabelVATy, getDataLayout().getAllocaAddrSpace(),
1483 "labelva", &DFSF.F->getEntryBlock().front());
1485 for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
1486 auto LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, n);
1487 IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1490 Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
1493 if (!FT->getReturnType()->isVoidTy()) {
1494 if (!DFSF.LabelReturnAlloca) {
1495 DFSF.LabelReturnAlloca =
1496 new AllocaInst(DFSF.DFS.ShadowTy,
1497 getDataLayout().getAllocaAddrSpace(),
1498 "labelreturn", &DFSF.F->getEntryBlock().front());
1500 Args.push_back(DFSF.LabelReturnAlloca);
1503 for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i)
1506 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1507 CustomCI->setCallingConv(CI->getCallingConv());
1508 CustomCI->setAttributes(CI->getAttributes());
1510 if (!FT->getReturnType()->isVoidTy()) {
1511 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1512 DFSF.setShadow(CustomCI, LabelLoad);
1515 CI->replaceAllUsesWith(CustomCI);
1516 CI->eraseFromParent();
1524 FunctionType *FT = cast<FunctionType>(
1525 CS.getCalledValue()->getType()->getPointerElementType());
1526 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1527 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1528 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1529 DFSF.getArgTLS(i, CS.getInstruction()));
1533 Instruction *Next = nullptr;
1534 if (!CS.getType()->isVoidTy()) {
1535 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1536 if (II->getNormalDest()->getSinglePredecessor()) {
1537 Next = &II->getNormalDest()->front();
1540 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
1541 Next = &NewBB->front();
1544 assert(CS->getIterator() != CS->getParent()->end());
1545 Next = CS->getNextNode();
1548 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1549 IRBuilder<> NextIRB(Next);
1550 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1551 DFSF.SkipInsts.insert(LI);
1552 DFSF.setShadow(CS.getInstruction(), LI);
1553 DFSF.NonZeroChecks.push_back(LI);
1557 // Do all instrumentation for IA_Args down here to defer tampering with the
1558 // CFG in a way that SplitEdge may be able to detect.
1559 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1560 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
1562 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1563 std::vector<Value *> Args;
1565 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1566 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1570 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1571 Args.push_back(DFSF.getShadow(*i));
1573 if (FT->isVarArg()) {
1574 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1575 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1576 AllocaInst *VarArgShadow =
1577 new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
1578 "", &DFSF.F->getEntryBlock().front());
1579 Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
1580 for (unsigned n = 0; i != e; ++i, ++n) {
1583 IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
1589 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1590 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1593 NewCS = IRB.CreateCall(Func, Args);
1595 NewCS.setCallingConv(CS.getCallingConv());
1596 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1597 *DFSF.DFS.Ctx, AttributeList::ReturnIndex,
1598 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType())));
1601 ExtractValueInst *ExVal =
1602 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1603 DFSF.SkipInsts.insert(ExVal);
1604 ExtractValueInst *ExShadow =
1605 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1606 DFSF.SkipInsts.insert(ExShadow);
1607 DFSF.setShadow(ExVal, ExShadow);
1608 DFSF.NonZeroChecks.push_back(ExShadow);
1610 CS.getInstruction()->replaceAllUsesWith(ExVal);
1613 CS.getInstruction()->eraseFromParent();
1617 void DFSanVisitor::visitPHINode(PHINode &PN) {
1619 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1621 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1622 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1623 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1625 ShadowPN->addIncoming(UndefShadow, *i);
1628 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1629 DFSF.setShadow(&PN, ShadowPN);