1 //===-- DataFlowSanitizer.cpp - dynamic data flow analysis ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// \file 10 /// This file is a part of DataFlowSanitizer, a generalised dynamic data flow 11 /// analysis. 12 /// 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. 17 /// 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: 22 /// 23 /// +--------------------+ 0x800000000000 (top of memory) 24 /// | application memory | 25 /// +--------------------+ 0x700000008000 (kAppAddr) 26 /// | | 27 /// | unused | 28 /// | | 29 /// +--------------------+ 0x200200000000 (kUnusedAddr) 30 /// | union table | 31 /// +--------------------+ 0x200000000000 (kUnionTableAddr) 32 /// | shadow memory | 33 /// +--------------------+ 0x000000010000 (kShadowAddr) 34 /// | reserved by kernel | 35 /// +--------------------+ 0x000000000000 36 /// 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. 43 /// 44 /// For more information, please refer to the design document: 45 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html 46 47 #include "llvm/Transforms/Instrumentation.h" 48 #include "llvm/ADT/DenseMap.h" 49 #include "llvm/ADT/DenseSet.h" 50 #include "llvm/ADT/DepthFirstIterator.h" 51 #include "llvm/ADT/StringExtras.h" 52 #include "llvm/Analysis/ValueTracking.h" 53 #include "llvm/IR/IRBuilder.h" 54 #include "llvm/IR/InlineAsm.h" 55 #include "llvm/IR/LLVMContext.h" 56 #include "llvm/IR/MDBuilder.h" 57 #include "llvm/IR/Type.h" 58 #include "llvm/IR/Value.h" 59 #include "llvm/InstVisitor.h" 60 #include "llvm/Pass.h" 61 #include "llvm/Support/CommandLine.h" 62 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 63 #include "llvm/Transforms/Utils/Local.h" 64 #include "llvm/Transforms/Utils/SpecialCaseList.h" 65 #include <iterator> 66 67 using namespace llvm; 68 69 // The -dfsan-preserve-alignment flag controls whether this pass assumes that 70 // alignment requirements provided by the input IR are correct. For example, 71 // if the input IR contains a load with alignment 8, this flag will cause 72 // the shadow load to have alignment 16. This flag is disabled by default as 73 // we have unfortunately encountered too much code (including Clang itself; 74 // see PR14291) which performs misaligned access. 75 static cl::opt<bool> ClPreserveAlignment( 76 "dfsan-preserve-alignment", 77 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden, 78 cl::init(false)); 79 80 // The ABI list file controls how shadow parameters are passed. The pass treats 81 // every function labelled "uninstrumented" in the ABI list file as conforming 82 // to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains 83 // additional annotations for those functions, a call to one of those functions 84 // will produce a warning message, as the labelling behaviour of the function is 85 // unknown. The other supported annotations are "functional" and "discard", 86 // which are described below under DataFlowSanitizer::WrapperKind. 87 static cl::opt<std::string> ClABIListFile( 88 "dfsan-abilist", 89 cl::desc("File listing native ABI functions and how the pass treats them"), 90 cl::Hidden); 91 92 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented 93 // functions (see DataFlowSanitizer::InstrumentedABI below). 94 static cl::opt<bool> ClArgsABI( 95 "dfsan-args-abi", 96 cl::desc("Use the argument ABI rather than the TLS ABI"), 97 cl::Hidden); 98 99 // Controls whether the pass includes or ignores the labels of pointers in load 100 // instructions. 101 static cl::opt<bool> ClCombinePointerLabelsOnLoad( 102 "dfsan-combine-pointer-labels-on-load", 103 cl::desc("Combine the label of the pointer with the label of the data when " 104 "loading from memory."), 105 cl::Hidden, cl::init(true)); 106 107 // Controls whether the pass includes or ignores the labels of pointers in 108 // stores instructions. 109 static cl::opt<bool> ClCombinePointerLabelsOnStore( 110 "dfsan-combine-pointer-labels-on-store", 111 cl::desc("Combine the label of the pointer with the label of the data when " 112 "storing in memory."), 113 cl::Hidden, cl::init(false)); 114 115 static cl::opt<bool> ClDebugNonzeroLabels( 116 "dfsan-debug-nonzero-labels", 117 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, " 118 "load or return with a nonzero label"), 119 cl::Hidden); 120 121 namespace { 122 123 class DataFlowSanitizer : public ModulePass { 124 friend struct DFSanFunction; 125 friend class DFSanVisitor; 126 127 enum { 128 ShadowWidth = 16 129 }; 130 131 /// Which ABI should be used for instrumented functions? 132 enum InstrumentedABI { 133 /// Argument and return value labels are passed through additional 134 /// arguments and by modifying the return type. 135 IA_Args, 136 137 /// Argument and return value labels are passed through TLS variables 138 /// __dfsan_arg_tls and __dfsan_retval_tls. 139 IA_TLS 140 }; 141 142 /// How should calls to uninstrumented functions be handled? 143 enum WrapperKind { 144 /// This function is present in an uninstrumented form but we don't know 145 /// how it should be handled. Print a warning and call the function anyway. 146 /// Don't label the return value. 147 WK_Warning, 148 149 /// This function does not write to (user-accessible) memory, and its return 150 /// value is unlabelled. 151 WK_Discard, 152 153 /// This function does not write to (user-accessible) memory, and the label 154 /// of its return value is the union of the label of its arguments. 155 WK_Functional, 156 157 /// Instead of calling the function, a custom wrapper __dfsw_F is called, 158 /// where F is the name of the function. This function may wrap the 159 /// original function or provide its own implementation. This is similar to 160 /// the IA_Args ABI, except that IA_Args uses a struct return type to 161 /// pass the return value shadow in a register, while WK_Custom uses an 162 /// extra pointer argument to return the shadow. This allows the wrapped 163 /// form of the function type to be expressed in C. 164 WK_Custom 165 }; 166 167 const DataLayout *DL; 168 Module *Mod; 169 LLVMContext *Ctx; 170 IntegerType *ShadowTy; 171 PointerType *ShadowPtrTy; 172 IntegerType *IntptrTy; 173 ConstantInt *ZeroShadow; 174 ConstantInt *ShadowPtrMask; 175 ConstantInt *ShadowPtrMul; 176 Constant *ArgTLS; 177 Constant *RetvalTLS; 178 void *(*GetArgTLSPtr)(); 179 void *(*GetRetvalTLSPtr)(); 180 Constant *GetArgTLS; 181 Constant *GetRetvalTLS; 182 FunctionType *DFSanUnionFnTy; 183 FunctionType *DFSanUnionLoadFnTy; 184 FunctionType *DFSanUnimplementedFnTy; 185 FunctionType *DFSanSetLabelFnTy; 186 FunctionType *DFSanNonzeroLabelFnTy; 187 Constant *DFSanUnionFn; 188 Constant *DFSanUnionLoadFn; 189 Constant *DFSanUnimplementedFn; 190 Constant *DFSanSetLabelFn; 191 Constant *DFSanNonzeroLabelFn; 192 MDNode *ColdCallWeights; 193 OwningPtr<SpecialCaseList> ABIList; 194 DenseMap<Value *, Function *> UnwrappedFnMap; 195 AttributeSet ReadOnlyNoneAttrs; 196 197 Value *getShadowAddress(Value *Addr, Instruction *Pos); 198 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos); 199 bool isInstrumented(const Function *F); 200 bool isInstrumented(const GlobalAlias *GA); 201 FunctionType *getArgsFunctionType(FunctionType *T); 202 FunctionType *getTrampolineFunctionType(FunctionType *T); 203 FunctionType *getCustomFunctionType(FunctionType *T); 204 InstrumentedABI getInstrumentedABI(); 205 WrapperKind getWrapperKind(Function *F); 206 void addGlobalNamePrefix(GlobalValue *GV); 207 Function *buildWrapperFunction(Function *F, StringRef NewFName, 208 GlobalValue::LinkageTypes NewFLink, 209 FunctionType *NewFT); 210 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName); 211 212 public: 213 DataFlowSanitizer(StringRef ABIListFile = StringRef(), 214 void *(*getArgTLS)() = 0, void *(*getRetValTLS)() = 0); 215 static char ID; 216 bool doInitialization(Module &M); 217 bool runOnModule(Module &M); 218 }; 219 220 struct DFSanFunction { 221 DataFlowSanitizer &DFS; 222 Function *F; 223 DataFlowSanitizer::InstrumentedABI IA; 224 bool IsNativeABI; 225 Value *ArgTLSPtr; 226 Value *RetvalTLSPtr; 227 AllocaInst *LabelReturnAlloca; 228 DenseMap<Value *, Value *> ValShadowMap; 229 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap; 230 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups; 231 DenseSet<Instruction *> SkipInsts; 232 DenseSet<Value *> NonZeroChecks; 233 234 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI) 235 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()), 236 IsNativeABI(IsNativeABI), ArgTLSPtr(0), RetvalTLSPtr(0), 237 LabelReturnAlloca(0) {} 238 Value *getArgTLSPtr(); 239 Value *getArgTLS(unsigned Index, Instruction *Pos); 240 Value *getRetvalTLS(); 241 Value *getShadow(Value *V); 242 void setShadow(Instruction *I, Value *Shadow); 243 Value *combineOperandShadows(Instruction *Inst); 244 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align, 245 Instruction *Pos); 246 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow, 247 Instruction *Pos); 248 }; 249 250 class DFSanVisitor : public InstVisitor<DFSanVisitor> { 251 public: 252 DFSanFunction &DFSF; 253 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {} 254 255 void visitOperandShadowInst(Instruction &I); 256 257 void visitBinaryOperator(BinaryOperator &BO); 258 void visitCastInst(CastInst &CI); 259 void visitCmpInst(CmpInst &CI); 260 void visitGetElementPtrInst(GetElementPtrInst &GEPI); 261 void visitLoadInst(LoadInst &LI); 262 void visitStoreInst(StoreInst &SI); 263 void visitReturnInst(ReturnInst &RI); 264 void visitCallSite(CallSite CS); 265 void visitPHINode(PHINode &PN); 266 void visitExtractElementInst(ExtractElementInst &I); 267 void visitInsertElementInst(InsertElementInst &I); 268 void visitShuffleVectorInst(ShuffleVectorInst &I); 269 void visitExtractValueInst(ExtractValueInst &I); 270 void visitInsertValueInst(InsertValueInst &I); 271 void visitAllocaInst(AllocaInst &I); 272 void visitSelectInst(SelectInst &I); 273 void visitMemSetInst(MemSetInst &I); 274 void visitMemTransferInst(MemTransferInst &I); 275 }; 276 277 } 278 279 char DataFlowSanitizer::ID; 280 INITIALIZE_PASS(DataFlowSanitizer, "dfsan", 281 "DataFlowSanitizer: dynamic data flow analysis.", false, false) 282 283 ModulePass *llvm::createDataFlowSanitizerPass(StringRef ABIListFile, 284 void *(*getArgTLS)(), 285 void *(*getRetValTLS)()) { 286 return new DataFlowSanitizer(ABIListFile, getArgTLS, getRetValTLS); 287 } 288 289 DataFlowSanitizer::DataFlowSanitizer(StringRef ABIListFile, 290 void *(*getArgTLS)(), 291 void *(*getRetValTLS)()) 292 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS), 293 ABIList(SpecialCaseList::createOrDie(ABIListFile.empty() ? ClABIListFile 294 : ABIListFile)) { 295 } 296 297 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) { 298 llvm::SmallVector<Type *, 4> ArgTypes; 299 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes)); 300 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i) 301 ArgTypes.push_back(ShadowTy); 302 if (T->isVarArg()) 303 ArgTypes.push_back(ShadowPtrTy); 304 Type *RetType = T->getReturnType(); 305 if (!RetType->isVoidTy()) 306 RetType = StructType::get(RetType, ShadowTy, (Type *)0); 307 return FunctionType::get(RetType, ArgTypes, T->isVarArg()); 308 } 309 310 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) { 311 assert(!T->isVarArg()); 312 llvm::SmallVector<Type *, 4> ArgTypes; 313 ArgTypes.push_back(T->getPointerTo()); 314 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes)); 315 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i) 316 ArgTypes.push_back(ShadowTy); 317 Type *RetType = T->getReturnType(); 318 if (!RetType->isVoidTy()) 319 ArgTypes.push_back(ShadowPtrTy); 320 return FunctionType::get(T->getReturnType(), ArgTypes, false); 321 } 322 323 FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) { 324 assert(!T->isVarArg()); 325 llvm::SmallVector<Type *, 4> ArgTypes; 326 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end(); 327 i != e; ++i) { 328 FunctionType *FT; 329 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>( 330 *i)->getElementType()))) { 331 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo()); 332 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx)); 333 } else { 334 ArgTypes.push_back(*i); 335 } 336 } 337 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i) 338 ArgTypes.push_back(ShadowTy); 339 Type *RetType = T->getReturnType(); 340 if (!RetType->isVoidTy()) 341 ArgTypes.push_back(ShadowPtrTy); 342 return FunctionType::get(T->getReturnType(), ArgTypes, false); 343 } 344 345 bool DataFlowSanitizer::doInitialization(Module &M) { 346 DL = getAnalysisIfAvailable<DataLayout>(); 347 if (!DL) 348 return false; 349 350 Mod = &M; 351 Ctx = &M.getContext(); 352 ShadowTy = IntegerType::get(*Ctx, ShadowWidth); 353 ShadowPtrTy = PointerType::getUnqual(ShadowTy); 354 IntptrTy = DL->getIntPtrType(*Ctx); 355 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0); 356 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL); 357 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8); 358 359 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy }; 360 DFSanUnionFnTy = 361 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false); 362 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy }; 363 DFSanUnionLoadFnTy = 364 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false); 365 DFSanUnimplementedFnTy = FunctionType::get( 366 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false); 367 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy }; 368 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx), 369 DFSanSetLabelArgs, /*isVarArg=*/false); 370 DFSanNonzeroLabelFnTy = FunctionType::get( 371 Type::getVoidTy(*Ctx), ArrayRef<Type *>(), /*isVarArg=*/false); 372 373 if (GetArgTLSPtr) { 374 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64); 375 ArgTLS = 0; 376 GetArgTLS = ConstantExpr::getIntToPtr( 377 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)), 378 PointerType::getUnqual( 379 FunctionType::get(PointerType::getUnqual(ArgTLSTy), (Type *)0))); 380 } 381 if (GetRetvalTLSPtr) { 382 RetvalTLS = 0; 383 GetRetvalTLS = ConstantExpr::getIntToPtr( 384 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)), 385 PointerType::getUnqual( 386 FunctionType::get(PointerType::getUnqual(ShadowTy), (Type *)0))); 387 } 388 389 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000); 390 return true; 391 } 392 393 bool DataFlowSanitizer::isInstrumented(const Function *F) { 394 return !ABIList->isIn(*F, "uninstrumented"); 395 } 396 397 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) { 398 return !ABIList->isIn(*GA, "uninstrumented"); 399 } 400 401 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() { 402 return ClArgsABI ? IA_Args : IA_TLS; 403 } 404 405 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) { 406 if (ABIList->isIn(*F, "functional")) 407 return WK_Functional; 408 if (ABIList->isIn(*F, "discard")) 409 return WK_Discard; 410 if (ABIList->isIn(*F, "custom")) 411 return WK_Custom; 412 413 return WK_Warning; 414 } 415 416 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) { 417 std::string GVName = GV->getName(), Prefix = "dfs$"; 418 GV->setName(Prefix + GVName); 419 420 // Try to change the name of the function in module inline asm. We only do 421 // this for specific asm directives, currently only ".symver", to try to avoid 422 // corrupting asm which happens to contain the symbol name as a substring. 423 // Note that the substitution for .symver assumes that the versioned symbol 424 // also has an instrumented name. 425 std::string Asm = GV->getParent()->getModuleInlineAsm(); 426 std::string SearchStr = ".symver " + GVName + ","; 427 size_t Pos = Asm.find(SearchStr); 428 if (Pos != std::string::npos) { 429 Asm.replace(Pos, SearchStr.size(), 430 ".symver " + Prefix + GVName + "," + Prefix); 431 GV->getParent()->setModuleInlineAsm(Asm); 432 } 433 } 434 435 Function * 436 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName, 437 GlobalValue::LinkageTypes NewFLink, 438 FunctionType *NewFT) { 439 FunctionType *FT = F->getFunctionType(); 440 Function *NewF = Function::Create(NewFT, NewFLink, NewFName, 441 F->getParent()); 442 NewF->copyAttributesFrom(F); 443 NewF->removeAttributes( 444 AttributeSet::ReturnIndex, 445 AttributeFuncs::typeIncompatible(NewFT->getReturnType(), 446 AttributeSet::ReturnIndex)); 447 448 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF); 449 std::vector<Value *> Args; 450 unsigned n = FT->getNumParams(); 451 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n) 452 Args.push_back(&*ai); 453 CallInst *CI = CallInst::Create(F, Args, "", BB); 454 if (FT->getReturnType()->isVoidTy()) 455 ReturnInst::Create(*Ctx, BB); 456 else 457 ReturnInst::Create(*Ctx, CI, BB); 458 459 return NewF; 460 } 461 462 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT, 463 StringRef FName) { 464 FunctionType *FTT = getTrampolineFunctionType(FT); 465 Constant *C = Mod->getOrInsertFunction(FName, FTT); 466 Function *F = dyn_cast<Function>(C); 467 if (F && F->isDeclaration()) { 468 F->setLinkage(GlobalValue::LinkOnceODRLinkage); 469 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F); 470 std::vector<Value *> Args; 471 Function::arg_iterator AI = F->arg_begin(); ++AI; 472 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N) 473 Args.push_back(&*AI); 474 CallInst *CI = 475 CallInst::Create(&F->getArgumentList().front(), Args, "", BB); 476 ReturnInst *RI; 477 if (FT->getReturnType()->isVoidTy()) 478 RI = ReturnInst::Create(*Ctx, BB); 479 else 480 RI = ReturnInst::Create(*Ctx, CI, BB); 481 482 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true); 483 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI; 484 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N) 485 DFSF.ValShadowMap[ValAI] = ShadowAI; 486 DFSanVisitor(DFSF).visitCallInst(*CI); 487 if (!FT->getReturnType()->isVoidTy()) 488 new StoreInst(DFSF.getShadow(RI->getReturnValue()), 489 &F->getArgumentList().back(), RI); 490 } 491 492 return C; 493 } 494 495 bool DataFlowSanitizer::runOnModule(Module &M) { 496 if (!DL) 497 return false; 498 499 if (ABIList->isIn(M, "skip")) 500 return false; 501 502 if (!GetArgTLSPtr) { 503 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64); 504 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy); 505 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS)) 506 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel); 507 } 508 if (!GetRetvalTLSPtr) { 509 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy); 510 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS)) 511 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel); 512 } 513 514 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy); 515 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) { 516 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone); 517 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt); 518 F->addAttribute(1, Attribute::ZExt); 519 F->addAttribute(2, Attribute::ZExt); 520 } 521 DFSanUnionLoadFn = 522 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy); 523 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) { 524 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly); 525 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt); 526 } 527 DFSanUnimplementedFn = 528 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy); 529 DFSanSetLabelFn = 530 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy); 531 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) { 532 F->addAttribute(1, Attribute::ZExt); 533 } 534 DFSanNonzeroLabelFn = 535 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy); 536 537 std::vector<Function *> FnsToInstrument; 538 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI; 539 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) { 540 if (!i->isIntrinsic() && 541 i != DFSanUnionFn && 542 i != DFSanUnionLoadFn && 543 i != DFSanUnimplementedFn && 544 i != DFSanSetLabelFn && 545 i != DFSanNonzeroLabelFn) 546 FnsToInstrument.push_back(&*i); 547 } 548 549 // Give function aliases prefixes when necessary, and build wrappers where the 550 // instrumentedness is inconsistent. 551 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) { 552 GlobalAlias *GA = &*i; 553 ++i; 554 // Don't stop on weak. We assume people aren't playing games with the 555 // instrumentedness of overridden weak aliases. 556 if (Function *F = dyn_cast<Function>( 557 GA->resolveAliasedGlobal(/*stopOnWeak=*/false))) { 558 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F); 559 if (GAInst && FInst) { 560 addGlobalNamePrefix(GA); 561 } else if (GAInst != FInst) { 562 // Non-instrumented alias of an instrumented function, or vice versa. 563 // Replace the alias with a native-ABI wrapper of the aliasee. The pass 564 // below will take care of instrumenting it. 565 Function *NewF = 566 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType()); 567 GA->replaceAllUsesWith(NewF); 568 NewF->takeName(GA); 569 GA->eraseFromParent(); 570 FnsToInstrument.push_back(NewF); 571 } 572 } 573 } 574 575 AttrBuilder B; 576 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone); 577 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B); 578 579 // First, change the ABI of every function in the module. ABI-listed 580 // functions keep their original ABI and get a wrapper function. 581 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(), 582 e = FnsToInstrument.end(); 583 i != e; ++i) { 584 Function &F = **i; 585 FunctionType *FT = F.getFunctionType(); 586 587 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() && 588 FT->getReturnType()->isVoidTy()); 589 590 if (isInstrumented(&F)) { 591 // Instrumented functions get a 'dfs$' prefix. This allows us to more 592 // easily identify cases of mismatching ABIs. 593 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) { 594 FunctionType *NewFT = getArgsFunctionType(FT); 595 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M); 596 NewF->copyAttributesFrom(&F); 597 NewF->removeAttributes( 598 AttributeSet::ReturnIndex, 599 AttributeFuncs::typeIncompatible(NewFT->getReturnType(), 600 AttributeSet::ReturnIndex)); 601 for (Function::arg_iterator FArg = F.arg_begin(), 602 NewFArg = NewF->arg_begin(), 603 FArgEnd = F.arg_end(); 604 FArg != FArgEnd; ++FArg, ++NewFArg) { 605 FArg->replaceAllUsesWith(NewFArg); 606 } 607 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList()); 608 609 for (Function::use_iterator ui = F.use_begin(), ue = F.use_end(); 610 ui != ue;) { 611 BlockAddress *BA = dyn_cast<BlockAddress>(ui.getUse().getUser()); 612 ++ui; 613 if (BA) { 614 BA->replaceAllUsesWith( 615 BlockAddress::get(NewF, BA->getBasicBlock())); 616 delete BA; 617 } 618 } 619 F.replaceAllUsesWith( 620 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT))); 621 NewF->takeName(&F); 622 F.eraseFromParent(); 623 *i = NewF; 624 addGlobalNamePrefix(NewF); 625 } else { 626 addGlobalNamePrefix(&F); 627 } 628 // Hopefully, nobody will try to indirectly call a vararg 629 // function... yet. 630 } else if (FT->isVarArg()) { 631 UnwrappedFnMap[&F] = &F; 632 *i = 0; 633 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) { 634 // Build a wrapper function for F. The wrapper simply calls F, and is 635 // added to FnsToInstrument so that any instrumentation according to its 636 // WrapperKind is done in the second pass below. 637 FunctionType *NewFT = getInstrumentedABI() == IA_Args 638 ? getArgsFunctionType(FT) 639 : FT; 640 Function *NewF = buildWrapperFunction( 641 &F, std::string("dfsw$") + std::string(F.getName()), 642 GlobalValue::LinkOnceODRLinkage, NewFT); 643 if (getInstrumentedABI() == IA_TLS) 644 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs); 645 646 Value *WrappedFnCst = 647 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)); 648 F.replaceAllUsesWith(WrappedFnCst); 649 UnwrappedFnMap[WrappedFnCst] = &F; 650 *i = NewF; 651 652 if (!F.isDeclaration()) { 653 // This function is probably defining an interposition of an 654 // uninstrumented function and hence needs to keep the original ABI. 655 // But any functions it may call need to use the instrumented ABI, so 656 // we instrument it in a mode which preserves the original ABI. 657 FnsWithNativeABI.insert(&F); 658 659 // This code needs to rebuild the iterators, as they may be invalidated 660 // by the push_back, taking care that the new range does not include 661 // any functions added by this code. 662 size_t N = i - FnsToInstrument.begin(), 663 Count = e - FnsToInstrument.begin(); 664 FnsToInstrument.push_back(&F); 665 i = FnsToInstrument.begin() + N; 666 e = FnsToInstrument.begin() + Count; 667 } 668 } 669 } 670 671 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(), 672 e = FnsToInstrument.end(); 673 i != e; ++i) { 674 if (!*i || (*i)->isDeclaration()) 675 continue; 676 677 removeUnreachableBlocks(**i); 678 679 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i)); 680 681 // DFSanVisitor may create new basic blocks, which confuses df_iterator. 682 // Build a copy of the list before iterating over it. 683 llvm::SmallVector<BasicBlock *, 4> BBList; 684 std::copy(df_begin(&(*i)->getEntryBlock()), df_end(&(*i)->getEntryBlock()), 685 std::back_inserter(BBList)); 686 687 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(), 688 e = BBList.end(); 689 i != e; ++i) { 690 Instruction *Inst = &(*i)->front(); 691 while (1) { 692 // DFSanVisitor may split the current basic block, changing the current 693 // instruction's next pointer and moving the next instruction to the 694 // tail block from which we should continue. 695 Instruction *Next = Inst->getNextNode(); 696 // DFSanVisitor may delete Inst, so keep track of whether it was a 697 // terminator. 698 bool IsTerminator = isa<TerminatorInst>(Inst); 699 if (!DFSF.SkipInsts.count(Inst)) 700 DFSanVisitor(DFSF).visit(Inst); 701 if (IsTerminator) 702 break; 703 Inst = Next; 704 } 705 } 706 707 // We will not necessarily be able to compute the shadow for every phi node 708 // until we have visited every block. Therefore, the code that handles phi 709 // nodes adds them to the PHIFixups list so that they can be properly 710 // handled here. 711 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator 712 i = DFSF.PHIFixups.begin(), 713 e = DFSF.PHIFixups.end(); 714 i != e; ++i) { 715 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n; 716 ++val) { 717 i->second->setIncomingValue( 718 val, DFSF.getShadow(i->first->getIncomingValue(val))); 719 } 720 } 721 722 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy 723 // places (i.e. instructions in basic blocks we haven't even begun visiting 724 // yet). To make our life easier, do this work in a pass after the main 725 // instrumentation. 726 if (ClDebugNonzeroLabels) { 727 for (DenseSet<Value *>::iterator i = DFSF.NonZeroChecks.begin(), 728 e = DFSF.NonZeroChecks.end(); 729 i != e; ++i) { 730 Instruction *Pos; 731 if (Instruction *I = dyn_cast<Instruction>(*i)) 732 Pos = I->getNextNode(); 733 else 734 Pos = DFSF.F->getEntryBlock().begin(); 735 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos)) 736 Pos = Pos->getNextNode(); 737 IRBuilder<> IRB(Pos); 738 Value *Ne = IRB.CreateICmpNE(*i, DFSF.DFS.ZeroShadow); 739 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen( 740 Ne, Pos, /*Unreachable=*/false, ColdCallWeights)); 741 IRBuilder<> ThenIRB(BI); 742 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn); 743 } 744 } 745 } 746 747 return false; 748 } 749 750 Value *DFSanFunction::getArgTLSPtr() { 751 if (ArgTLSPtr) 752 return ArgTLSPtr; 753 if (DFS.ArgTLS) 754 return ArgTLSPtr = DFS.ArgTLS; 755 756 IRBuilder<> IRB(F->getEntryBlock().begin()); 757 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS); 758 } 759 760 Value *DFSanFunction::getRetvalTLS() { 761 if (RetvalTLSPtr) 762 return RetvalTLSPtr; 763 if (DFS.RetvalTLS) 764 return RetvalTLSPtr = DFS.RetvalTLS; 765 766 IRBuilder<> IRB(F->getEntryBlock().begin()); 767 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS); 768 } 769 770 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) { 771 IRBuilder<> IRB(Pos); 772 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx); 773 } 774 775 Value *DFSanFunction::getShadow(Value *V) { 776 if (!isa<Argument>(V) && !isa<Instruction>(V)) 777 return DFS.ZeroShadow; 778 Value *&Shadow = ValShadowMap[V]; 779 if (!Shadow) { 780 if (Argument *A = dyn_cast<Argument>(V)) { 781 if (IsNativeABI) 782 return DFS.ZeroShadow; 783 switch (IA) { 784 case DataFlowSanitizer::IA_TLS: { 785 Value *ArgTLSPtr = getArgTLSPtr(); 786 Instruction *ArgTLSPos = 787 DFS.ArgTLS ? &*F->getEntryBlock().begin() 788 : cast<Instruction>(ArgTLSPtr)->getNextNode(); 789 IRBuilder<> IRB(ArgTLSPos); 790 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos)); 791 break; 792 } 793 case DataFlowSanitizer::IA_Args: { 794 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2; 795 Function::arg_iterator i = F->arg_begin(); 796 while (ArgIdx--) 797 ++i; 798 Shadow = i; 799 assert(Shadow->getType() == DFS.ShadowTy); 800 break; 801 } 802 } 803 NonZeroChecks.insert(Shadow); 804 } else { 805 Shadow = DFS.ZeroShadow; 806 } 807 } 808 return Shadow; 809 } 810 811 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) { 812 assert(!ValShadowMap.count(I)); 813 assert(Shadow->getType() == DFS.ShadowTy); 814 ValShadowMap[I] = Shadow; 815 } 816 817 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) { 818 assert(Addr != RetvalTLS && "Reinstrumenting?"); 819 IRBuilder<> IRB(Pos); 820 return IRB.CreateIntToPtr( 821 IRB.CreateMul( 822 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask), 823 ShadowPtrMul), 824 ShadowPtrTy); 825 } 826 827 // Generates IR to compute the union of the two given shadows, inserting it 828 // before Pos. Returns the computed union Value. 829 Value *DataFlowSanitizer::combineShadows(Value *V1, Value *V2, 830 Instruction *Pos) { 831 if (V1 == ZeroShadow) 832 return V2; 833 if (V2 == ZeroShadow) 834 return V1; 835 if (V1 == V2) 836 return V1; 837 IRBuilder<> IRB(Pos); 838 BasicBlock *Head = Pos->getParent(); 839 Value *Ne = IRB.CreateICmpNE(V1, V2); 840 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen( 841 Ne, Pos, /*Unreachable=*/false, ColdCallWeights)); 842 IRBuilder<> ThenIRB(BI); 843 CallInst *Call = ThenIRB.CreateCall2(DFSanUnionFn, V1, V2); 844 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt); 845 Call->addAttribute(1, Attribute::ZExt); 846 Call->addAttribute(2, Attribute::ZExt); 847 848 BasicBlock *Tail = BI->getSuccessor(0); 849 PHINode *Phi = PHINode::Create(ShadowTy, 2, "", Tail->begin()); 850 Phi->addIncoming(Call, Call->getParent()); 851 Phi->addIncoming(V1, Head); 852 Pos = Phi; 853 return Phi; 854 } 855 856 // A convenience function which folds the shadows of each of the operands 857 // of the provided instruction Inst, inserting the IR before Inst. Returns 858 // the computed union Value. 859 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) { 860 if (Inst->getNumOperands() == 0) 861 return DFS.ZeroShadow; 862 863 Value *Shadow = getShadow(Inst->getOperand(0)); 864 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) { 865 Shadow = DFS.combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst); 866 } 867 return Shadow; 868 } 869 870 void DFSanVisitor::visitOperandShadowInst(Instruction &I) { 871 Value *CombinedShadow = DFSF.combineOperandShadows(&I); 872 DFSF.setShadow(&I, CombinedShadow); 873 } 874 875 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where 876 // Addr has alignment Align, and take the union of each of those shadows. 877 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align, 878 Instruction *Pos) { 879 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) { 880 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i = 881 AllocaShadowMap.find(AI); 882 if (i != AllocaShadowMap.end()) { 883 IRBuilder<> IRB(Pos); 884 return IRB.CreateLoad(i->second); 885 } 886 } 887 888 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8; 889 SmallVector<Value *, 2> Objs; 890 GetUnderlyingObjects(Addr, Objs, DFS.DL); 891 bool AllConstants = true; 892 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end(); 893 i != e; ++i) { 894 if (isa<Function>(*i) || isa<BlockAddress>(*i)) 895 continue; 896 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant()) 897 continue; 898 899 AllConstants = false; 900 break; 901 } 902 if (AllConstants) 903 return DFS.ZeroShadow; 904 905 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos); 906 switch (Size) { 907 case 0: 908 return DFS.ZeroShadow; 909 case 1: { 910 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos); 911 LI->setAlignment(ShadowAlign); 912 return LI; 913 } 914 case 2: { 915 IRBuilder<> IRB(Pos); 916 Value *ShadowAddr1 = 917 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1)); 918 return DFS.combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign), 919 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), 920 Pos); 921 } 922 } 923 if (Size % (64 / DFS.ShadowWidth) == 0) { 924 // Fast path for the common case where each byte has identical shadow: load 925 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any 926 // shadow is non-equal. 927 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F); 928 IRBuilder<> FallbackIRB(FallbackBB); 929 CallInst *FallbackCall = FallbackIRB.CreateCall2( 930 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)); 931 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt); 932 933 // Compare each of the shadows stored in the loaded 64 bits to each other, 934 // by computing (WideShadow rotl ShadowWidth) == WideShadow. 935 IRBuilder<> IRB(Pos); 936 Value *WideAddr = 937 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx)); 938 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign); 939 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy); 940 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth); 941 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth); 942 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow); 943 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow); 944 945 BasicBlock *Head = Pos->getParent(); 946 BasicBlock *Tail = Head->splitBasicBlock(Pos); 947 // In the following code LastBr will refer to the previous basic block's 948 // conditional branch instruction, whose true successor is fixed up to point 949 // to the next block during the loop below or to the tail after the final 950 // iteration. 951 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq); 952 ReplaceInstWithInst(Head->getTerminator(), LastBr); 953 954 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size; 955 Ofs += 64 / DFS.ShadowWidth) { 956 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F); 957 IRBuilder<> NextIRB(NextBB); 958 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1)); 959 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign); 960 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow); 961 LastBr->setSuccessor(0, NextBB); 962 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB); 963 } 964 965 LastBr->setSuccessor(0, Tail); 966 FallbackIRB.CreateBr(Tail); 967 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front()); 968 Shadow->addIncoming(FallbackCall, FallbackBB); 969 Shadow->addIncoming(TruncShadow, LastBr->getParent()); 970 return Shadow; 971 } 972 973 IRBuilder<> IRB(Pos); 974 CallInst *FallbackCall = IRB.CreateCall2( 975 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)); 976 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt); 977 return FallbackCall; 978 } 979 980 void DFSanVisitor::visitLoadInst(LoadInst &LI) { 981 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType()); 982 uint64_t Align; 983 if (ClPreserveAlignment) { 984 Align = LI.getAlignment(); 985 if (Align == 0) 986 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType()); 987 } else { 988 Align = 1; 989 } 990 IRBuilder<> IRB(&LI); 991 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI); 992 if (ClCombinePointerLabelsOnLoad) { 993 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand()); 994 Shadow = DFSF.DFS.combineShadows(Shadow, PtrShadow, &LI); 995 } 996 if (Shadow != DFSF.DFS.ZeroShadow) 997 DFSF.NonZeroChecks.insert(Shadow); 998 999 DFSF.setShadow(&LI, Shadow); 1000 } 1001 1002 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align, 1003 Value *Shadow, Instruction *Pos) { 1004 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) { 1005 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i = 1006 AllocaShadowMap.find(AI); 1007 if (i != AllocaShadowMap.end()) { 1008 IRBuilder<> IRB(Pos); 1009 IRB.CreateStore(Shadow, i->second); 1010 return; 1011 } 1012 } 1013 1014 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8; 1015 IRBuilder<> IRB(Pos); 1016 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos); 1017 if (Shadow == DFS.ZeroShadow) { 1018 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth); 1019 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0); 1020 Value *ExtShadowAddr = 1021 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy)); 1022 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign); 1023 return; 1024 } 1025 1026 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth; 1027 uint64_t Offset = 0; 1028 if (Size >= ShadowVecSize) { 1029 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize); 1030 Value *ShadowVec = UndefValue::get(ShadowVecTy); 1031 for (unsigned i = 0; i != ShadowVecSize; ++i) { 1032 ShadowVec = IRB.CreateInsertElement( 1033 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i)); 1034 } 1035 Value *ShadowVecAddr = 1036 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy)); 1037 do { 1038 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset); 1039 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign); 1040 Size -= ShadowVecSize; 1041 ++Offset; 1042 } while (Size >= ShadowVecSize); 1043 Offset *= ShadowVecSize; 1044 } 1045 while (Size > 0) { 1046 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset); 1047 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign); 1048 --Size; 1049 ++Offset; 1050 } 1051 } 1052 1053 void DFSanVisitor::visitStoreInst(StoreInst &SI) { 1054 uint64_t Size = 1055 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType()); 1056 uint64_t Align; 1057 if (ClPreserveAlignment) { 1058 Align = SI.getAlignment(); 1059 if (Align == 0) 1060 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType()); 1061 } else { 1062 Align = 1; 1063 } 1064 1065 Value* Shadow = DFSF.getShadow(SI.getValueOperand()); 1066 if (ClCombinePointerLabelsOnStore) { 1067 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand()); 1068 Shadow = DFSF.DFS.combineShadows(Shadow, PtrShadow, &SI); 1069 } 1070 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI); 1071 } 1072 1073 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) { 1074 visitOperandShadowInst(BO); 1075 } 1076 1077 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); } 1078 1079 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); } 1080 1081 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) { 1082 visitOperandShadowInst(GEPI); 1083 } 1084 1085 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) { 1086 visitOperandShadowInst(I); 1087 } 1088 1089 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) { 1090 visitOperandShadowInst(I); 1091 } 1092 1093 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) { 1094 visitOperandShadowInst(I); 1095 } 1096 1097 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) { 1098 visitOperandShadowInst(I); 1099 } 1100 1101 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) { 1102 visitOperandShadowInst(I); 1103 } 1104 1105 void DFSanVisitor::visitAllocaInst(AllocaInst &I) { 1106 bool AllLoadsStores = true; 1107 for (Instruction::use_iterator i = I.use_begin(), e = I.use_end(); i != e; 1108 ++i) { 1109 if (isa<LoadInst>(*i)) 1110 continue; 1111 1112 if (StoreInst *SI = dyn_cast<StoreInst>(*i)) { 1113 if (SI->getPointerOperand() == &I) 1114 continue; 1115 } 1116 1117 AllLoadsStores = false; 1118 break; 1119 } 1120 if (AllLoadsStores) { 1121 IRBuilder<> IRB(&I); 1122 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy); 1123 } 1124 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow); 1125 } 1126 1127 void DFSanVisitor::visitSelectInst(SelectInst &I) { 1128 Value *CondShadow = DFSF.getShadow(I.getCondition()); 1129 Value *TrueShadow = DFSF.getShadow(I.getTrueValue()); 1130 Value *FalseShadow = DFSF.getShadow(I.getFalseValue()); 1131 1132 if (isa<VectorType>(I.getCondition()->getType())) { 1133 DFSF.setShadow( 1134 &I, DFSF.DFS.combineShadows( 1135 CondShadow, 1136 DFSF.DFS.combineShadows(TrueShadow, FalseShadow, &I), &I)); 1137 } else { 1138 Value *ShadowSel; 1139 if (TrueShadow == FalseShadow) { 1140 ShadowSel = TrueShadow; 1141 } else { 1142 ShadowSel = 1143 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I); 1144 } 1145 DFSF.setShadow(&I, DFSF.DFS.combineShadows(CondShadow, ShadowSel, &I)); 1146 } 1147 } 1148 1149 void DFSanVisitor::visitMemSetInst(MemSetInst &I) { 1150 IRBuilder<> IRB(&I); 1151 Value *ValShadow = DFSF.getShadow(I.getValue()); 1152 IRB.CreateCall3( 1153 DFSF.DFS.DFSanSetLabelFn, ValShadow, 1154 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)), 1155 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)); 1156 } 1157 1158 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) { 1159 IRBuilder<> IRB(&I); 1160 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I); 1161 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I); 1162 Value *LenShadow = IRB.CreateMul( 1163 I.getLength(), 1164 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8)); 1165 Value *AlignShadow; 1166 if (ClPreserveAlignment) { 1167 AlignShadow = IRB.CreateMul(I.getAlignmentCst(), 1168 ConstantInt::get(I.getAlignmentCst()->getType(), 1169 DFSF.DFS.ShadowWidth / 8)); 1170 } else { 1171 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(), 1172 DFSF.DFS.ShadowWidth / 8); 1173 } 1174 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx); 1175 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr); 1176 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr); 1177 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow, 1178 AlignShadow, I.getVolatileCst()); 1179 } 1180 1181 void DFSanVisitor::visitReturnInst(ReturnInst &RI) { 1182 if (!DFSF.IsNativeABI && RI.getReturnValue()) { 1183 switch (DFSF.IA) { 1184 case DataFlowSanitizer::IA_TLS: { 1185 Value *S = DFSF.getShadow(RI.getReturnValue()); 1186 IRBuilder<> IRB(&RI); 1187 IRB.CreateStore(S, DFSF.getRetvalTLS()); 1188 break; 1189 } 1190 case DataFlowSanitizer::IA_Args: { 1191 IRBuilder<> IRB(&RI); 1192 Type *RT = DFSF.F->getFunctionType()->getReturnType(); 1193 Value *InsVal = 1194 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0); 1195 Value *InsShadow = 1196 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1); 1197 RI.setOperand(0, InsShadow); 1198 break; 1199 } 1200 } 1201 } 1202 } 1203 1204 void DFSanVisitor::visitCallSite(CallSite CS) { 1205 Function *F = CS.getCalledFunction(); 1206 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) { 1207 visitOperandShadowInst(*CS.getInstruction()); 1208 return; 1209 } 1210 1211 IRBuilder<> IRB(CS.getInstruction()); 1212 1213 DenseMap<Value *, Function *>::iterator i = 1214 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue()); 1215 if (i != DFSF.DFS.UnwrappedFnMap.end()) { 1216 Function *F = i->second; 1217 switch (DFSF.DFS.getWrapperKind(F)) { 1218 case DataFlowSanitizer::WK_Warning: { 1219 CS.setCalledFunction(F); 1220 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn, 1221 IRB.CreateGlobalStringPtr(F->getName())); 1222 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow); 1223 return; 1224 } 1225 case DataFlowSanitizer::WK_Discard: { 1226 CS.setCalledFunction(F); 1227 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow); 1228 return; 1229 } 1230 case DataFlowSanitizer::WK_Functional: { 1231 CS.setCalledFunction(F); 1232 visitOperandShadowInst(*CS.getInstruction()); 1233 return; 1234 } 1235 case DataFlowSanitizer::WK_Custom: { 1236 // Don't try to handle invokes of custom functions, it's too complicated. 1237 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_ 1238 // wrapper. 1239 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) { 1240 FunctionType *FT = F->getFunctionType(); 1241 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT); 1242 std::string CustomFName = "__dfsw_"; 1243 CustomFName += F->getName(); 1244 Constant *CustomF = 1245 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT); 1246 if (Function *CustomFn = dyn_cast<Function>(CustomF)) { 1247 CustomFn->copyAttributesFrom(F); 1248 1249 // Custom functions returning non-void will write to the return label. 1250 if (!FT->getReturnType()->isVoidTy()) { 1251 CustomFn->removeAttributes(AttributeSet::FunctionIndex, 1252 DFSF.DFS.ReadOnlyNoneAttrs); 1253 } 1254 } 1255 1256 std::vector<Value *> Args; 1257 1258 CallSite::arg_iterator i = CS.arg_begin(); 1259 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) { 1260 Type *T = (*i)->getType(); 1261 FunctionType *ParamFT; 1262 if (isa<PointerType>(T) && 1263 (ParamFT = dyn_cast<FunctionType>( 1264 cast<PointerType>(T)->getElementType()))) { 1265 std::string TName = "dfst"; 1266 TName += utostr(FT->getNumParams() - n); 1267 TName += "$"; 1268 TName += F->getName(); 1269 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName); 1270 Args.push_back(T); 1271 Args.push_back( 1272 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx))); 1273 } else { 1274 Args.push_back(*i); 1275 } 1276 } 1277 1278 i = CS.arg_begin(); 1279 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) 1280 Args.push_back(DFSF.getShadow(*i)); 1281 1282 if (!FT->getReturnType()->isVoidTy()) { 1283 if (!DFSF.LabelReturnAlloca) { 1284 DFSF.LabelReturnAlloca = 1285 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn", 1286 DFSF.F->getEntryBlock().begin()); 1287 } 1288 Args.push_back(DFSF.LabelReturnAlloca); 1289 } 1290 1291 CallInst *CustomCI = IRB.CreateCall(CustomF, Args); 1292 CustomCI->setCallingConv(CI->getCallingConv()); 1293 CustomCI->setAttributes(CI->getAttributes()); 1294 1295 if (!FT->getReturnType()->isVoidTy()) { 1296 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca); 1297 DFSF.setShadow(CustomCI, LabelLoad); 1298 } 1299 1300 CI->replaceAllUsesWith(CustomCI); 1301 CI->eraseFromParent(); 1302 return; 1303 } 1304 break; 1305 } 1306 } 1307 } 1308 1309 FunctionType *FT = cast<FunctionType>( 1310 CS.getCalledValue()->getType()->getPointerElementType()); 1311 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) { 1312 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) { 1313 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)), 1314 DFSF.getArgTLS(i, CS.getInstruction())); 1315 } 1316 } 1317 1318 Instruction *Next = 0; 1319 if (!CS.getType()->isVoidTy()) { 1320 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) { 1321 if (II->getNormalDest()->getSinglePredecessor()) { 1322 Next = II->getNormalDest()->begin(); 1323 } else { 1324 BasicBlock *NewBB = 1325 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS); 1326 Next = NewBB->begin(); 1327 } 1328 } else { 1329 Next = CS->getNextNode(); 1330 } 1331 1332 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) { 1333 IRBuilder<> NextIRB(Next); 1334 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS()); 1335 DFSF.SkipInsts.insert(LI); 1336 DFSF.setShadow(CS.getInstruction(), LI); 1337 DFSF.NonZeroChecks.insert(LI); 1338 } 1339 } 1340 1341 // Do all instrumentation for IA_Args down here to defer tampering with the 1342 // CFG in a way that SplitEdge may be able to detect. 1343 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) { 1344 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT); 1345 Value *Func = 1346 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT)); 1347 std::vector<Value *> Args; 1348 1349 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 1350 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) 1351 Args.push_back(*i); 1352 1353 i = CS.arg_begin(); 1354 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) 1355 Args.push_back(DFSF.getShadow(*i)); 1356 1357 if (FT->isVarArg()) { 1358 unsigned VarArgSize = CS.arg_size() - FT->getNumParams(); 1359 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize); 1360 AllocaInst *VarArgShadow = 1361 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin()); 1362 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0)); 1363 for (unsigned n = 0; i != e; ++i, ++n) { 1364 IRB.CreateStore(DFSF.getShadow(*i), 1365 IRB.CreateConstGEP2_32(VarArgShadow, 0, n)); 1366 Args.push_back(*i); 1367 } 1368 } 1369 1370 CallSite NewCS; 1371 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) { 1372 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(), 1373 Args); 1374 } else { 1375 NewCS = IRB.CreateCall(Func, Args); 1376 } 1377 NewCS.setCallingConv(CS.getCallingConv()); 1378 NewCS.setAttributes(CS.getAttributes().removeAttributes( 1379 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex, 1380 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(), 1381 AttributeSet::ReturnIndex))); 1382 1383 if (Next) { 1384 ExtractValueInst *ExVal = 1385 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next); 1386 DFSF.SkipInsts.insert(ExVal); 1387 ExtractValueInst *ExShadow = 1388 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next); 1389 DFSF.SkipInsts.insert(ExShadow); 1390 DFSF.setShadow(ExVal, ExShadow); 1391 DFSF.NonZeroChecks.insert(ExShadow); 1392 1393 CS.getInstruction()->replaceAllUsesWith(ExVal); 1394 } 1395 1396 CS.getInstruction()->eraseFromParent(); 1397 } 1398 } 1399 1400 void DFSanVisitor::visitPHINode(PHINode &PN) { 1401 PHINode *ShadowPN = 1402 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN); 1403 1404 // Give the shadow phi node valid predecessors to fool SplitEdge into working. 1405 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy); 1406 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e; 1407 ++i) { 1408 ShadowPN->addIncoming(UndefShadow, *i); 1409 } 1410 1411 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN)); 1412 DFSF.setShadow(&PN, ShadowPN); 1413 } 1414