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/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" 68 #include <algorithm> 69 #include <iterator> 70 #include <set> 71 #include <utility> 72 73 using namespace llvm; 74 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"; 79 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, 89 cl::init(false)); 90 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( 99 "dfsan-abilist", 100 cl::desc("File listing native ABI functions and how the pass treats them"), 101 cl::Hidden); 102 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( 106 "dfsan-args-abi", 107 cl::desc("Use the argument ABI rather than the TLS ABI"), 108 cl::Hidden); 109 110 // Controls whether the pass includes or ignores the labels of pointers in load 111 // instructions. 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)); 117 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)); 125 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"), 130 cl::Hidden); 131 132 133 namespace { 134 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(); 142 } 143 return "<unknown type>"; 144 } 145 146 class DFSanABIList { 147 std::unique_ptr<SpecialCaseList> SCL; 148 149 public: 150 DFSanABIList() {} 151 152 void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); } 153 154 /// Returns whether either this function or its source file are listed in the 155 /// given category. 156 bool isIn(const Function &F, StringRef Category) const { 157 return isIn(*F.getParent(), Category) || 158 SCL->inSection("fun", F.getName(), Category); 159 } 160 161 /// Returns whether this global alias is listed in the given category. 162 /// 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)) 167 return true; 168 169 if (isa<FunctionType>(GA.getValueType())) 170 return SCL->inSection("fun", GA.getName(), Category); 171 172 return SCL->inSection("global", GA.getName(), Category) || 173 SCL->inSection("type", GetGlobalTypeString(GA), Category); 174 } 175 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); 179 } 180 }; 181 182 class DataFlowSanitizer : public ModulePass { 183 friend struct DFSanFunction; 184 friend class DFSanVisitor; 185 186 enum { 187 ShadowWidth = 16 188 }; 189 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. 194 IA_Args, 195 196 /// Argument and return value labels are passed through TLS variables 197 /// __dfsan_arg_tls and __dfsan_retval_tls. 198 IA_TLS 199 }; 200 201 /// How should calls to uninstrumented functions be handled? 202 enum WrapperKind { 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. 206 WK_Warning, 207 208 /// This function does not write to (user-accessible) memory, and its return 209 /// value is unlabelled. 210 WK_Discard, 211 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. 214 WK_Functional, 215 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. 223 WK_Custom 224 }; 225 226 Module *Mod; 227 LLVMContext *Ctx; 228 IntegerType *ShadowTy; 229 PointerType *ShadowPtrTy; 230 IntegerType *IntptrTy; 231 ConstantInt *ZeroShadow; 232 ConstantInt *ShadowPtrMask; 233 ConstantInt *ShadowPtrMul; 234 Constant *ArgTLS; 235 Constant *RetvalTLS; 236 void *(*GetArgTLSPtr)(); 237 void *(*GetRetvalTLSPtr)(); 238 Constant *GetArgTLS; 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 AttributeList ReadOnlyNoneAttrs; 258 bool DFSanRuntimeShadowMask; 259 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); 273 274 public: 275 DataFlowSanitizer( 276 const std::vector<std::string> &ABIListFiles = std::vector<std::string>(), 277 void *(*getArgTLS)() = nullptr, void *(*getRetValTLS)() = nullptr); 278 static char ID; 279 bool doInitialization(Module &M) override; 280 bool runOnModule(Module &M) override; 281 }; 282 283 struct DFSanFunction { 284 DataFlowSanitizer &DFS; 285 Function *F; 286 DominatorTree DT; 287 DataFlowSanitizer::InstrumentedABI IA; 288 bool IsNativeABI; 289 Value *ArgTLSPtr; 290 Value *RetvalTLSPtr; 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; 297 bool AvoidNewBlocks; 298 299 struct CachedCombinedShadow { 300 BasicBlock *Block; 301 Value *Shadow; 302 }; 303 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow> 304 CachedCombinedShadows; 305 DenseMap<Value *, std::set<Value *>> ShadowElements; 306 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) { 311 DT.recalculate(*F); 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; 315 } 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, 324 Instruction *Pos); 325 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow, 326 Instruction *Pos); 327 }; 328 329 class DFSanVisitor : public InstVisitor<DFSanVisitor> { 330 public: 331 DFSanFunction &DFSF; 332 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {} 333 334 void visitOperandShadowInst(Instruction &I); 335 336 void visitBinaryOperator(BinaryOperator &BO); 337 void visitCastInst(CastInst &CI); 338 void visitCmpInst(CmpInst &CI); 339 void visitGetElementPtrInst(GetElementPtrInst &GEPI); 340 void visitLoadInst(LoadInst &LI); 341 void visitStoreInst(StoreInst &SI); 342 void visitReturnInst(ReturnInst &RI); 343 void visitCallSite(CallSite CS); 344 void visitPHINode(PHINode &PN); 345 void visitExtractElementInst(ExtractElementInst &I); 346 void visitInsertElementInst(InsertElementInst &I); 347 void visitShuffleVectorInst(ShuffleVectorInst &I); 348 void visitExtractValueInst(ExtractValueInst &I); 349 void visitInsertValueInst(InsertValueInst &I); 350 void visitAllocaInst(AllocaInst &I); 351 void visitSelectInst(SelectInst &I); 352 void visitMemSetInst(MemSetInst &I); 353 void visitMemTransferInst(MemTransferInst &I); 354 }; 355 356 } 357 358 char DataFlowSanitizer::ID; 359 INITIALIZE_PASS(DataFlowSanitizer, "dfsan", 360 "DataFlowSanitizer: dynamic data flow analysis.", false, false) 361 362 ModulePass * 363 llvm::createDataFlowSanitizerPass(const std::vector<std::string> &ABIListFiles, 364 void *(*getArgTLS)(), 365 void *(*getRetValTLS)()) { 366 return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS); 367 } 368 369 DataFlowSanitizer::DataFlowSanitizer( 370 const std::vector<std::string> &ABIListFiles, void *(*getArgTLS)(), 371 void *(*getRetValTLS)()) 372 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS), 373 DFSanRuntimeShadowMask(false) { 374 std::vector<std::string> AllABIListFiles(std::move(ABIListFiles)); 375 AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(), 376 ClABIListFiles.end()); 377 ABIList.set(SpecialCaseList::createOrDie(AllABIListFiles)); 378 } 379 380 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) { 381 llvm::SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end()); 382 ArgTypes.append(T->getNumParams(), ShadowTy); 383 if (T->isVarArg()) 384 ArgTypes.push_back(ShadowPtrTy); 385 Type *RetType = T->getReturnType(); 386 if (!RetType->isVoidTy()) 387 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr); 388 return FunctionType::get(RetType, ArgTypes, T->isVarArg()); 389 } 390 391 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) { 392 assert(!T->isVarArg()); 393 llvm::SmallVector<Type *, 4> ArgTypes; 394 ArgTypes.push_back(T->getPointerTo()); 395 ArgTypes.append(T->param_begin(), T->param_end()); 396 ArgTypes.append(T->getNumParams(), ShadowTy); 397 Type *RetType = T->getReturnType(); 398 if (!RetType->isVoidTy()) 399 ArgTypes.push_back(ShadowPtrTy); 400 return FunctionType::get(T->getReturnType(), ArgTypes, false); 401 } 402 403 FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) { 404 llvm::SmallVector<Type *, 4> ArgTypes; 405 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end(); 406 i != e; ++i) { 407 FunctionType *FT; 408 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>( 409 *i)->getElementType()))) { 410 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo()); 411 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx)); 412 } else { 413 ArgTypes.push_back(*i); 414 } 415 } 416 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i) 417 ArgTypes.push_back(ShadowTy); 418 if (T->isVarArg()) 419 ArgTypes.push_back(ShadowPtrTy); 420 Type *RetType = T->getReturnType(); 421 if (!RetType->isVoidTy()) 422 ArgTypes.push_back(ShadowPtrTy); 423 return FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg()); 424 } 425 426 bool DataFlowSanitizer::doInitialization(Module &M) { 427 llvm::Triple TargetTriple(M.getTargetTriple()); 428 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64; 429 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 || 430 TargetTriple.getArch() == llvm::Triple::mips64el; 431 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64 || 432 TargetTriple.getArch() == llvm::Triple::aarch64_be; 433 434 const DataLayout &DL = M.getDataLayout(); 435 436 Mod = &M; 437 Ctx = &M.getContext(); 438 ShadowTy = IntegerType::get(*Ctx, ShadowWidth); 439 ShadowPtrTy = PointerType::getUnqual(ShadowTy); 440 IntptrTy = DL.getIntPtrType(*Ctx); 441 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0); 442 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8); 443 if (IsX86_64) 444 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL); 445 else if (IsMIPS64) 446 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL); 447 // AArch64 supports multiple VMAs and the shadow mask is set at runtime. 448 else if (IsAArch64) 449 DFSanRuntimeShadowMask = true; 450 else 451 report_fatal_error("unsupported triple"); 452 453 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy }; 454 DFSanUnionFnTy = 455 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false); 456 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy }; 457 DFSanUnionLoadFnTy = 458 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false); 459 DFSanUnimplementedFnTy = FunctionType::get( 460 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false); 461 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy }; 462 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx), 463 DFSanSetLabelArgs, /*isVarArg=*/false); 464 DFSanNonzeroLabelFnTy = FunctionType::get( 465 Type::getVoidTy(*Ctx), None, /*isVarArg=*/false); 466 DFSanVarargWrapperFnTy = FunctionType::get( 467 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false); 468 469 if (GetArgTLSPtr) { 470 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64); 471 ArgTLS = nullptr; 472 GetArgTLS = ConstantExpr::getIntToPtr( 473 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)), 474 PointerType::getUnqual( 475 FunctionType::get(PointerType::getUnqual(ArgTLSTy), 476 (Type *)nullptr))); 477 } 478 if (GetRetvalTLSPtr) { 479 RetvalTLS = nullptr; 480 GetRetvalTLS = ConstantExpr::getIntToPtr( 481 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)), 482 PointerType::getUnqual( 483 FunctionType::get(PointerType::getUnqual(ShadowTy), 484 (Type *)nullptr))); 485 } 486 487 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000); 488 return true; 489 } 490 491 bool DataFlowSanitizer::isInstrumented(const Function *F) { 492 return !ABIList.isIn(*F, "uninstrumented"); 493 } 494 495 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) { 496 return !ABIList.isIn(*GA, "uninstrumented"); 497 } 498 499 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() { 500 return ClArgsABI ? IA_Args : IA_TLS; 501 } 502 503 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) { 504 if (ABIList.isIn(*F, "functional")) 505 return WK_Functional; 506 if (ABIList.isIn(*F, "discard")) 507 return WK_Discard; 508 if (ABIList.isIn(*F, "custom")) 509 return WK_Custom; 510 511 return WK_Warning; 512 } 513 514 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) { 515 std::string GVName = GV->getName(), Prefix = "dfs$"; 516 GV->setName(Prefix + GVName); 517 518 // Try to change the name of the function in module inline asm. We only do 519 // this for specific asm directives, currently only ".symver", to try to avoid 520 // corrupting asm which happens to contain the symbol name as a substring. 521 // Note that the substitution for .symver assumes that the versioned symbol 522 // also has an instrumented name. 523 std::string Asm = GV->getParent()->getModuleInlineAsm(); 524 std::string SearchStr = ".symver " + GVName + ","; 525 size_t Pos = Asm.find(SearchStr); 526 if (Pos != std::string::npos) { 527 Asm.replace(Pos, SearchStr.size(), 528 ".symver " + Prefix + GVName + "," + Prefix); 529 GV->getParent()->setModuleInlineAsm(Asm); 530 } 531 } 532 533 Function * 534 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName, 535 GlobalValue::LinkageTypes NewFLink, 536 FunctionType *NewFT) { 537 FunctionType *FT = F->getFunctionType(); 538 Function *NewF = Function::Create(NewFT, NewFLink, NewFName, 539 F->getParent()); 540 NewF->copyAttributesFrom(F); 541 NewF->removeAttributes( 542 AttributeList::ReturnIndex, 543 AttributeList::get( 544 F->getContext(), AttributeList::ReturnIndex, 545 AttributeFuncs::typeIncompatible(NewFT->getReturnType()))); 546 547 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF); 548 if (F->isVarArg()) { 549 NewF->removeAttributes( 550 AttributeList::FunctionIndex, 551 AttributeList().addAttribute(*Ctx, AttributeList::FunctionIndex, 552 "split-stack")); 553 CallInst::Create(DFSanVarargWrapperFn, 554 IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "", 555 BB); 556 new UnreachableInst(*Ctx, BB); 557 } else { 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); 565 else 566 ReturnInst::Create(*Ctx, CI, BB); 567 } 568 569 return NewF; 570 } 571 572 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT, 573 StringRef FName) { 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); 585 ReturnInst *RI; 586 if (FT->getReturnType()->isVoidTy()) 587 RI = ReturnInst::Create(*Ctx, BB); 588 else 589 RI = ReturnInst::Create(*Ctx, CI, BB); 590 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); 599 } 600 601 return C; 602 } 603 604 bool DataFlowSanitizer::runOnModule(Module &M) { 605 if (ABIList.isIn(M, "skip")) 606 return false; 607 608 if (!GetArgTLSPtr) { 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); 613 } 614 if (!GetRetvalTLSPtr) { 615 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy); 616 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS)) 617 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel); 618 } 619 620 ExternalShadowMask = 621 Mod->getOrInsertGlobal(kDFSanExternShadowPtrMask, IntptrTy); 622 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->addAttribute(1, Attribute::ZExt); 629 F->addAttribute(2, Attribute::ZExt); 630 } 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->addAttribute(1, Attribute::ZExt); 637 F->addAttribute(2, Attribute::ZExt); 638 } 639 DFSanUnionLoadFn = 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); 645 } 646 DFSanUnimplementedFn = 647 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy); 648 DFSanSetLabelFn = 649 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy); 650 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) { 651 F->addAttribute(1, Attribute::ZExt); 652 } 653 DFSanNonzeroLabelFn = 654 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy); 655 DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper", 656 DFSanVarargWrapperFnTy); 657 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); 670 } 671 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; 676 ++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. 687 Function *NewF = 688 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType()); 689 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType())); 690 NewF->takeName(GA); 691 GA->eraseFromParent(); 692 FnsToInstrument.push_back(NewF); 693 } 694 } 695 } 696 697 AttrBuilder B; 698 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone); 699 ReadOnlyNoneAttrs = AttributeList::get(*Ctx, AttributeList::FunctionIndex, B); 700 701 // First, change the ABI of every function in the module. ABI-listed 702 // functions keep their original ABI and get a wrapper function. 703 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(), 704 e = FnsToInstrument.end(); 705 i != e; ++i) { 706 Function &F = **i; 707 FunctionType *FT = F.getFunctionType(); 708 709 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() && 710 FT->getReturnType()->isVoidTy()); 711 712 if (isInstrumented(&F)) { 713 // Instrumented functions get a 'dfs$' prefix. This allows us to more 714 // easily identify cases of mismatching ABIs. 715 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) { 716 FunctionType *NewFT = getArgsFunctionType(FT); 717 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M); 718 NewF->copyAttributesFrom(&F); 719 NewF->removeAttributes( 720 AttributeList::ReturnIndex, 721 AttributeList::get( 722 NewF->getContext(), AttributeList::ReturnIndex, 723 AttributeFuncs::typeIncompatible(NewFT->getReturnType()))); 724 for (Function::arg_iterator FArg = F.arg_begin(), 725 NewFArg = NewF->arg_begin(), 726 FArgEnd = F.arg_end(); 727 FArg != FArgEnd; ++FArg, ++NewFArg) { 728 FArg->replaceAllUsesWith(&*NewFArg); 729 } 730 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList()); 731 732 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end(); 733 UI != UE;) { 734 BlockAddress *BA = dyn_cast<BlockAddress>(*UI); 735 ++UI; 736 if (BA) { 737 BA->replaceAllUsesWith( 738 BlockAddress::get(NewF, BA->getBasicBlock())); 739 delete BA; 740 } 741 } 742 F.replaceAllUsesWith( 743 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT))); 744 NewF->takeName(&F); 745 F.eraseFromParent(); 746 *i = NewF; 747 addGlobalNamePrefix(NewF); 748 } else { 749 addGlobalNamePrefix(&F); 750 } 751 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) { 752 // Build a wrapper function for F. The wrapper simply calls F, and is 753 // added to FnsToInstrument so that any instrumentation according to its 754 // WrapperKind is done in the second pass below. 755 FunctionType *NewFT = getInstrumentedABI() == IA_Args 756 ? getArgsFunctionType(FT) 757 : FT; 758 Function *NewF = buildWrapperFunction( 759 &F, std::string("dfsw$") + std::string(F.getName()), 760 GlobalValue::LinkOnceODRLinkage, NewFT); 761 if (getInstrumentedABI() == IA_TLS) 762 NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs); 763 764 Value *WrappedFnCst = 765 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)); 766 F.replaceAllUsesWith(WrappedFnCst); 767 768 UnwrappedFnMap[WrappedFnCst] = &F; 769 *i = NewF; 770 771 if (!F.isDeclaration()) { 772 // This function is probably defining an interposition of an 773 // uninstrumented function and hence needs to keep the original ABI. 774 // But any functions it may call need to use the instrumented ABI, so 775 // we instrument it in a mode which preserves the original ABI. 776 FnsWithNativeABI.insert(&F); 777 778 // This code needs to rebuild the iterators, as they may be invalidated 779 // by the push_back, taking care that the new range does not include 780 // any functions added by this code. 781 size_t N = i - FnsToInstrument.begin(), 782 Count = e - FnsToInstrument.begin(); 783 FnsToInstrument.push_back(&F); 784 i = FnsToInstrument.begin() + N; 785 e = FnsToInstrument.begin() + Count; 786 } 787 // Hopefully, nobody will try to indirectly call a vararg 788 // function... yet. 789 } else if (FT->isVarArg()) { 790 UnwrappedFnMap[&F] = &F; 791 *i = nullptr; 792 } 793 } 794 795 for (Function *i : FnsToInstrument) { 796 if (!i || i->isDeclaration()) 797 continue; 798 799 removeUnreachableBlocks(*i); 800 801 DFSanFunction DFSF(*this, i, FnsWithNativeABI.count(i)); 802 803 // DFSanVisitor may create new basic blocks, which confuses df_iterator. 804 // Build a copy of the list before iterating over it. 805 llvm::SmallVector<BasicBlock *, 4> BBList(depth_first(&i->getEntryBlock())); 806 807 for (BasicBlock *i : BBList) { 808 Instruction *Inst = &i->front(); 809 while (1) { 810 // DFSanVisitor may split the current basic block, changing the current 811 // instruction's next pointer and moving the next instruction to the 812 // tail block from which we should continue. 813 Instruction *Next = Inst->getNextNode(); 814 // DFSanVisitor may delete Inst, so keep track of whether it was a 815 // terminator. 816 bool IsTerminator = isa<TerminatorInst>(Inst); 817 if (!DFSF.SkipInsts.count(Inst)) 818 DFSanVisitor(DFSF).visit(Inst); 819 if (IsTerminator) 820 break; 821 Inst = Next; 822 } 823 } 824 825 // We will not necessarily be able to compute the shadow for every phi node 826 // until we have visited every block. Therefore, the code that handles phi 827 // nodes adds them to the PHIFixups list so that they can be properly 828 // handled here. 829 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator 830 i = DFSF.PHIFixups.begin(), 831 e = DFSF.PHIFixups.end(); 832 i != e; ++i) { 833 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n; 834 ++val) { 835 i->second->setIncomingValue( 836 val, DFSF.getShadow(i->first->getIncomingValue(val))); 837 } 838 } 839 840 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy 841 // places (i.e. instructions in basic blocks we haven't even begun visiting 842 // yet). To make our life easier, do this work in a pass after the main 843 // instrumentation. 844 if (ClDebugNonzeroLabels) { 845 for (Value *V : DFSF.NonZeroChecks) { 846 Instruction *Pos; 847 if (Instruction *I = dyn_cast<Instruction>(V)) 848 Pos = I->getNextNode(); 849 else 850 Pos = &DFSF.F->getEntryBlock().front(); 851 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos)) 852 Pos = Pos->getNextNode(); 853 IRBuilder<> IRB(Pos); 854 Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow); 855 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen( 856 Ne, Pos, /*Unreachable=*/false, ColdCallWeights)); 857 IRBuilder<> ThenIRB(BI); 858 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {}); 859 } 860 } 861 } 862 863 return false; 864 } 865 866 Value *DFSanFunction::getArgTLSPtr() { 867 if (ArgTLSPtr) 868 return ArgTLSPtr; 869 if (DFS.ArgTLS) 870 return ArgTLSPtr = DFS.ArgTLS; 871 872 IRBuilder<> IRB(&F->getEntryBlock().front()); 873 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS, {}); 874 } 875 876 Value *DFSanFunction::getRetvalTLS() { 877 if (RetvalTLSPtr) 878 return RetvalTLSPtr; 879 if (DFS.RetvalTLS) 880 return RetvalTLSPtr = DFS.RetvalTLS; 881 882 IRBuilder<> IRB(&F->getEntryBlock().front()); 883 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS, {}); 884 } 885 886 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) { 887 IRBuilder<> IRB(Pos); 888 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx); 889 } 890 891 Value *DFSanFunction::getShadow(Value *V) { 892 if (!isa<Argument>(V) && !isa<Instruction>(V)) 893 return DFS.ZeroShadow; 894 Value *&Shadow = ValShadowMap[V]; 895 if (!Shadow) { 896 if (Argument *A = dyn_cast<Argument>(V)) { 897 if (IsNativeABI) 898 return DFS.ZeroShadow; 899 switch (IA) { 900 case DataFlowSanitizer::IA_TLS: { 901 Value *ArgTLSPtr = getArgTLSPtr(); 902 Instruction *ArgTLSPos = 903 DFS.ArgTLS ? &*F->getEntryBlock().begin() 904 : cast<Instruction>(ArgTLSPtr)->getNextNode(); 905 IRBuilder<> IRB(ArgTLSPos); 906 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos)); 907 break; 908 } 909 case DataFlowSanitizer::IA_Args: { 910 unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2; 911 Function::arg_iterator i = F->arg_begin(); 912 while (ArgIdx--) 913 ++i; 914 Shadow = &*i; 915 assert(Shadow->getType() == DFS.ShadowTy); 916 break; 917 } 918 } 919 NonZeroChecks.push_back(Shadow); 920 } else { 921 Shadow = DFS.ZeroShadow; 922 } 923 } 924 return Shadow; 925 } 926 927 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) { 928 assert(!ValShadowMap.count(I)); 929 assert(Shadow->getType() == DFS.ShadowTy); 930 ValShadowMap[I] = Shadow; 931 } 932 933 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) { 934 assert(Addr != RetvalTLS && "Reinstrumenting?"); 935 IRBuilder<> IRB(Pos); 936 Value *ShadowPtrMaskValue; 937 if (DFSanRuntimeShadowMask) 938 ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask); 939 else 940 ShadowPtrMaskValue = ShadowPtrMask; 941 return IRB.CreateIntToPtr( 942 IRB.CreateMul( 943 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), 944 IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy)), 945 ShadowPtrMul), 946 ShadowPtrTy); 947 } 948 949 // Generates IR to compute the union of the two given shadows, inserting it 950 // before Pos. Returns the computed union Value. 951 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) { 952 if (V1 == DFS.ZeroShadow) 953 return V2; 954 if (V2 == DFS.ZeroShadow) 955 return V1; 956 if (V1 == V2) 957 return V1; 958 959 auto V1Elems = ShadowElements.find(V1); 960 auto V2Elems = ShadowElements.find(V2); 961 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) { 962 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(), 963 V2Elems->second.begin(), V2Elems->second.end())) { 964 return V1; 965 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(), 966 V1Elems->second.begin(), V1Elems->second.end())) { 967 return V2; 968 } 969 } else if (V1Elems != ShadowElements.end()) { 970 if (V1Elems->second.count(V2)) 971 return V1; 972 } else if (V2Elems != ShadowElements.end()) { 973 if (V2Elems->second.count(V1)) 974 return V2; 975 } 976 977 auto Key = std::make_pair(V1, V2); 978 if (V1 > V2) 979 std::swap(Key.first, Key.second); 980 CachedCombinedShadow &CCS = CachedCombinedShadows[Key]; 981 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent())) 982 return CCS.Shadow; 983 984 IRBuilder<> IRB(Pos); 985 if (AvoidNewBlocks) { 986 CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {V1, V2}); 987 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt); 988 Call->addAttribute(1, Attribute::ZExt); 989 Call->addAttribute(2, Attribute::ZExt); 990 991 CCS.Block = Pos->getParent(); 992 CCS.Shadow = Call; 993 } else { 994 BasicBlock *Head = Pos->getParent(); 995 Value *Ne = IRB.CreateICmpNE(V1, V2); 996 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen( 997 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT)); 998 IRBuilder<> ThenIRB(BI); 999 CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {V1, V2}); 1000 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt); 1001 Call->addAttribute(1, Attribute::ZExt); 1002 Call->addAttribute(2, Attribute::ZExt); 1003 1004 BasicBlock *Tail = BI->getSuccessor(0); 1005 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front()); 1006 Phi->addIncoming(Call, Call->getParent()); 1007 Phi->addIncoming(V1, Head); 1008 1009 CCS.Block = Tail; 1010 CCS.Shadow = Phi; 1011 } 1012 1013 std::set<Value *> UnionElems; 1014 if (V1Elems != ShadowElements.end()) { 1015 UnionElems = V1Elems->second; 1016 } else { 1017 UnionElems.insert(V1); 1018 } 1019 if (V2Elems != ShadowElements.end()) { 1020 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end()); 1021 } else { 1022 UnionElems.insert(V2); 1023 } 1024 ShadowElements[CCS.Shadow] = std::move(UnionElems); 1025 1026 return CCS.Shadow; 1027 } 1028 1029 // A convenience function which folds the shadows of each of the operands 1030 // of the provided instruction Inst, inserting the IR before Inst. Returns 1031 // the computed union Value. 1032 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) { 1033 if (Inst->getNumOperands() == 0) 1034 return DFS.ZeroShadow; 1035 1036 Value *Shadow = getShadow(Inst->getOperand(0)); 1037 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) { 1038 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst); 1039 } 1040 return Shadow; 1041 } 1042 1043 void DFSanVisitor::visitOperandShadowInst(Instruction &I) { 1044 Value *CombinedShadow = DFSF.combineOperandShadows(&I); 1045 DFSF.setShadow(&I, CombinedShadow); 1046 } 1047 1048 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where 1049 // Addr has alignment Align, and take the union of each of those shadows. 1050 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align, 1051 Instruction *Pos) { 1052 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) { 1053 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i = 1054 AllocaShadowMap.find(AI); 1055 if (i != AllocaShadowMap.end()) { 1056 IRBuilder<> IRB(Pos); 1057 return IRB.CreateLoad(i->second); 1058 } 1059 } 1060 1061 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8; 1062 SmallVector<Value *, 2> Objs; 1063 GetUnderlyingObjects(Addr, Objs, Pos->getModule()->getDataLayout()); 1064 bool AllConstants = true; 1065 for (Value *Obj : Objs) { 1066 if (isa<Function>(Obj) || isa<BlockAddress>(Obj)) 1067 continue; 1068 if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant()) 1069 continue; 1070 1071 AllConstants = false; 1072 break; 1073 } 1074 if (AllConstants) 1075 return DFS.ZeroShadow; 1076 1077 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos); 1078 switch (Size) { 1079 case 0: 1080 return DFS.ZeroShadow; 1081 case 1: { 1082 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos); 1083 LI->setAlignment(ShadowAlign); 1084 return LI; 1085 } 1086 case 2: { 1087 IRBuilder<> IRB(Pos); 1088 Value *ShadowAddr1 = IRB.CreateGEP(DFS.ShadowTy, ShadowAddr, 1089 ConstantInt::get(DFS.IntptrTy, 1)); 1090 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign), 1091 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos); 1092 } 1093 } 1094 if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) { 1095 // Fast path for the common case where each byte has identical shadow: load 1096 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any 1097 // shadow is non-equal. 1098 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F); 1099 IRBuilder<> FallbackIRB(FallbackBB); 1100 CallInst *FallbackCall = FallbackIRB.CreateCall( 1101 DFS.DFSanUnionLoadFn, 1102 {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)}); 1103 FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt); 1104 1105 // Compare each of the shadows stored in the loaded 64 bits to each other, 1106 // by computing (WideShadow rotl ShadowWidth) == WideShadow. 1107 IRBuilder<> IRB(Pos); 1108 Value *WideAddr = 1109 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx)); 1110 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign); 1111 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy); 1112 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth); 1113 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth); 1114 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow); 1115 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow); 1116 1117 BasicBlock *Head = Pos->getParent(); 1118 BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator()); 1119 1120 if (DomTreeNode *OldNode = DT.getNode(Head)) { 1121 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end()); 1122 1123 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head); 1124 for (auto Child : Children) 1125 DT.changeImmediateDominator(Child, NewNode); 1126 } 1127 1128 // In the following code LastBr will refer to the previous basic block's 1129 // conditional branch instruction, whose true successor is fixed up to point 1130 // to the next block during the loop below or to the tail after the final 1131 // iteration. 1132 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq); 1133 ReplaceInstWithInst(Head->getTerminator(), LastBr); 1134 DT.addNewBlock(FallbackBB, Head); 1135 1136 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size; 1137 Ofs += 64 / DFS.ShadowWidth) { 1138 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F); 1139 DT.addNewBlock(NextBB, LastBr->getParent()); 1140 IRBuilder<> NextIRB(NextBB); 1141 WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr, 1142 ConstantInt::get(DFS.IntptrTy, 1)); 1143 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign); 1144 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow); 1145 LastBr->setSuccessor(0, NextBB); 1146 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB); 1147 } 1148 1149 LastBr->setSuccessor(0, Tail); 1150 FallbackIRB.CreateBr(Tail); 1151 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front()); 1152 Shadow->addIncoming(FallbackCall, FallbackBB); 1153 Shadow->addIncoming(TruncShadow, LastBr->getParent()); 1154 return Shadow; 1155 } 1156 1157 IRBuilder<> IRB(Pos); 1158 CallInst *FallbackCall = IRB.CreateCall( 1159 DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)}); 1160 FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt); 1161 return FallbackCall; 1162 } 1163 1164 void DFSanVisitor::visitLoadInst(LoadInst &LI) { 1165 auto &DL = LI.getModule()->getDataLayout(); 1166 uint64_t Size = DL.getTypeStoreSize(LI.getType()); 1167 if (Size == 0) { 1168 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow); 1169 return; 1170 } 1171 1172 uint64_t Align; 1173 if (ClPreserveAlignment) { 1174 Align = LI.getAlignment(); 1175 if (Align == 0) 1176 Align = DL.getABITypeAlignment(LI.getType()); 1177 } else { 1178 Align = 1; 1179 } 1180 IRBuilder<> IRB(&LI); 1181 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI); 1182 if (ClCombinePointerLabelsOnLoad) { 1183 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand()); 1184 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI); 1185 } 1186 if (Shadow != DFSF.DFS.ZeroShadow) 1187 DFSF.NonZeroChecks.push_back(Shadow); 1188 1189 DFSF.setShadow(&LI, Shadow); 1190 } 1191 1192 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align, 1193 Value *Shadow, Instruction *Pos) { 1194 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) { 1195 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i = 1196 AllocaShadowMap.find(AI); 1197 if (i != AllocaShadowMap.end()) { 1198 IRBuilder<> IRB(Pos); 1199 IRB.CreateStore(Shadow, i->second); 1200 return; 1201 } 1202 } 1203 1204 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8; 1205 IRBuilder<> IRB(Pos); 1206 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos); 1207 if (Shadow == DFS.ZeroShadow) { 1208 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth); 1209 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0); 1210 Value *ExtShadowAddr = 1211 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy)); 1212 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign); 1213 return; 1214 } 1215 1216 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth; 1217 uint64_t Offset = 0; 1218 if (Size >= ShadowVecSize) { 1219 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize); 1220 Value *ShadowVec = UndefValue::get(ShadowVecTy); 1221 for (unsigned i = 0; i != ShadowVecSize; ++i) { 1222 ShadowVec = IRB.CreateInsertElement( 1223 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i)); 1224 } 1225 Value *ShadowVecAddr = 1226 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy)); 1227 do { 1228 Value *CurShadowVecAddr = 1229 IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset); 1230 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign); 1231 Size -= ShadowVecSize; 1232 ++Offset; 1233 } while (Size >= ShadowVecSize); 1234 Offset *= ShadowVecSize; 1235 } 1236 while (Size > 0) { 1237 Value *CurShadowAddr = 1238 IRB.CreateConstGEP1_32(DFS.ShadowTy, ShadowAddr, Offset); 1239 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign); 1240 --Size; 1241 ++Offset; 1242 } 1243 } 1244 1245 void DFSanVisitor::visitStoreInst(StoreInst &SI) { 1246 auto &DL = SI.getModule()->getDataLayout(); 1247 uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType()); 1248 if (Size == 0) 1249 return; 1250 1251 uint64_t Align; 1252 if (ClPreserveAlignment) { 1253 Align = SI.getAlignment(); 1254 if (Align == 0) 1255 Align = DL.getABITypeAlignment(SI.getValueOperand()->getType()); 1256 } else { 1257 Align = 1; 1258 } 1259 1260 Value* Shadow = DFSF.getShadow(SI.getValueOperand()); 1261 if (ClCombinePointerLabelsOnStore) { 1262 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand()); 1263 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI); 1264 } 1265 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI); 1266 } 1267 1268 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) { 1269 visitOperandShadowInst(BO); 1270 } 1271 1272 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); } 1273 1274 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); } 1275 1276 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) { 1277 visitOperandShadowInst(GEPI); 1278 } 1279 1280 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) { 1281 visitOperandShadowInst(I); 1282 } 1283 1284 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) { 1285 visitOperandShadowInst(I); 1286 } 1287 1288 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) { 1289 visitOperandShadowInst(I); 1290 } 1291 1292 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) { 1293 visitOperandShadowInst(I); 1294 } 1295 1296 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) { 1297 visitOperandShadowInst(I); 1298 } 1299 1300 void DFSanVisitor::visitAllocaInst(AllocaInst &I) { 1301 bool AllLoadsStores = true; 1302 for (User *U : I.users()) { 1303 if (isa<LoadInst>(U)) 1304 continue; 1305 1306 if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 1307 if (SI->getPointerOperand() == &I) 1308 continue; 1309 } 1310 1311 AllLoadsStores = false; 1312 break; 1313 } 1314 if (AllLoadsStores) { 1315 IRBuilder<> IRB(&I); 1316 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy); 1317 } 1318 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow); 1319 } 1320 1321 void DFSanVisitor::visitSelectInst(SelectInst &I) { 1322 Value *CondShadow = DFSF.getShadow(I.getCondition()); 1323 Value *TrueShadow = DFSF.getShadow(I.getTrueValue()); 1324 Value *FalseShadow = DFSF.getShadow(I.getFalseValue()); 1325 1326 if (isa<VectorType>(I.getCondition()->getType())) { 1327 DFSF.setShadow( 1328 &I, 1329 DFSF.combineShadows( 1330 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I)); 1331 } else { 1332 Value *ShadowSel; 1333 if (TrueShadow == FalseShadow) { 1334 ShadowSel = TrueShadow; 1335 } else { 1336 ShadowSel = 1337 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I); 1338 } 1339 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I)); 1340 } 1341 } 1342 1343 void DFSanVisitor::visitMemSetInst(MemSetInst &I) { 1344 IRBuilder<> IRB(&I); 1345 Value *ValShadow = DFSF.getShadow(I.getValue()); 1346 IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn, 1347 {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy( 1348 *DFSF.DFS.Ctx)), 1349 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)}); 1350 } 1351 1352 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) { 1353 IRBuilder<> IRB(&I); 1354 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I); 1355 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I); 1356 Value *LenShadow = IRB.CreateMul( 1357 I.getLength(), 1358 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8)); 1359 Value *AlignShadow; 1360 if (ClPreserveAlignment) { 1361 AlignShadow = IRB.CreateMul(I.getAlignmentCst(), 1362 ConstantInt::get(I.getAlignmentCst()->getType(), 1363 DFSF.DFS.ShadowWidth / 8)); 1364 } else { 1365 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(), 1366 DFSF.DFS.ShadowWidth / 8); 1367 } 1368 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx); 1369 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr); 1370 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr); 1371 IRB.CreateCall(I.getCalledValue(), {DestShadow, SrcShadow, LenShadow, 1372 AlignShadow, I.getVolatileCst()}); 1373 } 1374 1375 void DFSanVisitor::visitReturnInst(ReturnInst &RI) { 1376 if (!DFSF.IsNativeABI && RI.getReturnValue()) { 1377 switch (DFSF.IA) { 1378 case DataFlowSanitizer::IA_TLS: { 1379 Value *S = DFSF.getShadow(RI.getReturnValue()); 1380 IRBuilder<> IRB(&RI); 1381 IRB.CreateStore(S, DFSF.getRetvalTLS()); 1382 break; 1383 } 1384 case DataFlowSanitizer::IA_Args: { 1385 IRBuilder<> IRB(&RI); 1386 Type *RT = DFSF.F->getFunctionType()->getReturnType(); 1387 Value *InsVal = 1388 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0); 1389 Value *InsShadow = 1390 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1); 1391 RI.setOperand(0, InsShadow); 1392 break; 1393 } 1394 } 1395 } 1396 } 1397 1398 void DFSanVisitor::visitCallSite(CallSite CS) { 1399 Function *F = CS.getCalledFunction(); 1400 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) { 1401 visitOperandShadowInst(*CS.getInstruction()); 1402 return; 1403 } 1404 1405 // Calls to this function are synthesized in wrappers, and we shouldn't 1406 // instrument them. 1407 if (F == DFSF.DFS.DFSanVarargWrapperFn) 1408 return; 1409 1410 IRBuilder<> IRB(CS.getInstruction()); 1411 1412 DenseMap<Value *, Function *>::iterator i = 1413 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue()); 1414 if (i != DFSF.DFS.UnwrappedFnMap.end()) { 1415 Function *F = i->second; 1416 switch (DFSF.DFS.getWrapperKind(F)) { 1417 case DataFlowSanitizer::WK_Warning: { 1418 CS.setCalledFunction(F); 1419 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn, 1420 IRB.CreateGlobalStringPtr(F->getName())); 1421 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow); 1422 return; 1423 } 1424 case DataFlowSanitizer::WK_Discard: { 1425 CS.setCalledFunction(F); 1426 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow); 1427 return; 1428 } 1429 case DataFlowSanitizer::WK_Functional: { 1430 CS.setCalledFunction(F); 1431 visitOperandShadowInst(*CS.getInstruction()); 1432 return; 1433 } 1434 case DataFlowSanitizer::WK_Custom: { 1435 // Don't try to handle invokes of custom functions, it's too complicated. 1436 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_ 1437 // wrapper. 1438 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) { 1439 FunctionType *FT = F->getFunctionType(); 1440 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT); 1441 std::string CustomFName = "__dfsw_"; 1442 CustomFName += F->getName(); 1443 Constant *CustomF = 1444 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT); 1445 if (Function *CustomFn = dyn_cast<Function>(CustomF)) { 1446 CustomFn->copyAttributesFrom(F); 1447 1448 // Custom functions returning non-void will write to the return label. 1449 if (!FT->getReturnType()->isVoidTy()) { 1450 CustomFn->removeAttributes(AttributeList::FunctionIndex, 1451 DFSF.DFS.ReadOnlyNoneAttrs); 1452 } 1453 } 1454 1455 std::vector<Value *> Args; 1456 1457 CallSite::arg_iterator i = CS.arg_begin(); 1458 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) { 1459 Type *T = (*i)->getType(); 1460 FunctionType *ParamFT; 1461 if (isa<PointerType>(T) && 1462 (ParamFT = dyn_cast<FunctionType>( 1463 cast<PointerType>(T)->getElementType()))) { 1464 std::string TName = "dfst"; 1465 TName += utostr(FT->getNumParams() - n); 1466 TName += "$"; 1467 TName += F->getName(); 1468 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName); 1469 Args.push_back(T); 1470 Args.push_back( 1471 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx))); 1472 } else { 1473 Args.push_back(*i); 1474 } 1475 } 1476 1477 i = CS.arg_begin(); 1478 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) 1479 Args.push_back(DFSF.getShadow(*i)); 1480 1481 if (FT->isVarArg()) { 1482 auto *LabelVATy = ArrayType::get(DFSF.DFS.ShadowTy, 1483 CS.arg_size() - FT->getNumParams()); 1484 auto *LabelVAAlloca = new AllocaInst( 1485 LabelVATy, "labelva", &DFSF.F->getEntryBlock().front()); 1486 1487 for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) { 1488 auto LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, n); 1489 IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr); 1490 } 1491 1492 Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0)); 1493 } 1494 1495 if (!FT->getReturnType()->isVoidTy()) { 1496 if (!DFSF.LabelReturnAlloca) { 1497 DFSF.LabelReturnAlloca = 1498 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn", 1499 &DFSF.F->getEntryBlock().front()); 1500 } 1501 Args.push_back(DFSF.LabelReturnAlloca); 1502 } 1503 1504 for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i) 1505 Args.push_back(*i); 1506 1507 CallInst *CustomCI = IRB.CreateCall(CustomF, Args); 1508 CustomCI->setCallingConv(CI->getCallingConv()); 1509 CustomCI->setAttributes(CI->getAttributes()); 1510 1511 if (!FT->getReturnType()->isVoidTy()) { 1512 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca); 1513 DFSF.setShadow(CustomCI, LabelLoad); 1514 } 1515 1516 CI->replaceAllUsesWith(CustomCI); 1517 CI->eraseFromParent(); 1518 return; 1519 } 1520 break; 1521 } 1522 } 1523 } 1524 1525 FunctionType *FT = cast<FunctionType>( 1526 CS.getCalledValue()->getType()->getPointerElementType()); 1527 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) { 1528 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) { 1529 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)), 1530 DFSF.getArgTLS(i, CS.getInstruction())); 1531 } 1532 } 1533 1534 Instruction *Next = nullptr; 1535 if (!CS.getType()->isVoidTy()) { 1536 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) { 1537 if (II->getNormalDest()->getSinglePredecessor()) { 1538 Next = &II->getNormalDest()->front(); 1539 } else { 1540 BasicBlock *NewBB = 1541 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT); 1542 Next = &NewBB->front(); 1543 } 1544 } else { 1545 assert(CS->getIterator() != CS->getParent()->end()); 1546 Next = CS->getNextNode(); 1547 } 1548 1549 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) { 1550 IRBuilder<> NextIRB(Next); 1551 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS()); 1552 DFSF.SkipInsts.insert(LI); 1553 DFSF.setShadow(CS.getInstruction(), LI); 1554 DFSF.NonZeroChecks.push_back(LI); 1555 } 1556 } 1557 1558 // Do all instrumentation for IA_Args down here to defer tampering with the 1559 // CFG in a way that SplitEdge may be able to detect. 1560 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) { 1561 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT); 1562 Value *Func = 1563 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT)); 1564 std::vector<Value *> Args; 1565 1566 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 1567 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) 1568 Args.push_back(*i); 1569 1570 i = CS.arg_begin(); 1571 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) 1572 Args.push_back(DFSF.getShadow(*i)); 1573 1574 if (FT->isVarArg()) { 1575 unsigned VarArgSize = CS.arg_size() - FT->getNumParams(); 1576 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize); 1577 AllocaInst *VarArgShadow = 1578 new AllocaInst(VarArgArrayTy, "", &DFSF.F->getEntryBlock().front()); 1579 Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0)); 1580 for (unsigned n = 0; i != e; ++i, ++n) { 1581 IRB.CreateStore( 1582 DFSF.getShadow(*i), 1583 IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n)); 1584 Args.push_back(*i); 1585 } 1586 } 1587 1588 CallSite NewCS; 1589 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) { 1590 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(), 1591 Args); 1592 } else { 1593 NewCS = IRB.CreateCall(Func, Args); 1594 } 1595 NewCS.setCallingConv(CS.getCallingConv()); 1596 NewCS.setAttributes(CS.getAttributes().removeAttributes( 1597 *DFSF.DFS.Ctx, AttributeList::ReturnIndex, 1598 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType()))); 1599 1600 if (Next) { 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); 1609 1610 CS.getInstruction()->replaceAllUsesWith(ExVal); 1611 } 1612 1613 CS.getInstruction()->eraseFromParent(); 1614 } 1615 } 1616 1617 void DFSanVisitor::visitPHINode(PHINode &PN) { 1618 PHINode *ShadowPN = 1619 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN); 1620 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; 1624 ++i) { 1625 ShadowPN->addIncoming(UndefShadow, *i); 1626 } 1627 1628 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN)); 1629 DFSF.setShadow(&PN, ShadowPN); 1630 } 1631