1 //===- DataFlowSanitizer.cpp - dynamic data flow analysis -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 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. 20 /// 21 /// There are two possible memory layouts. In the first one, each byte of 22 /// application memory is backed by a shadow memory byte. The shadow byte can 23 /// represent up to 8 labels. To enable this you must specify the 24 /// -dfsan-fast-8-labels flag. On Linux/x86_64, memory is then laid out as 25 /// follows: 26 /// 27 /// +--------------------+ 0x800000000000 (top of memory) 28 /// | application memory | 29 /// +--------------------+ 0x700000008000 (kAppAddr) 30 /// | | 31 /// | unused | 32 /// | | 33 /// +--------------------+ 0x300200000000 (kUnusedAddr) 34 /// | union table | 35 /// +--------------------+ 0x300000000000 (kUnionTableAddr) 36 /// | origin | 37 /// +--------------------+ 0x200000008000 (kOriginAddr) 38 /// | shadow memory | 39 /// +--------------------+ 0x100000008000 (kShadowAddr) 40 /// | unused | 41 /// +--------------------+ 0x000000010000 42 /// | reserved by kernel | 43 /// +--------------------+ 0x000000000000 44 /// 45 /// 46 /// In the second memory layout, each byte of application memory is backed by 47 /// two bytes of shadow memory which hold the label. That means we can represent 48 /// either 16 labels (with -dfsan-fast-16-labels flag) or 2^16 labels (on the 49 /// default legacy mode) per byte. On Linux/x86_64, memory is then laid out as 50 /// follows: 51 /// 52 /// +--------------------+ 0x800000000000 (top of memory) 53 /// | application memory | 54 /// +--------------------+ 0x700000008000 (kAppAddr) 55 /// | | 56 /// | unused | 57 /// | | 58 /// +--------------------+ 0x300200000000 (kUnusedAddr) 59 /// | union table | 60 /// +--------------------+ 0x300000000000 (kUnionTableAddr) 61 /// | origin | 62 /// +--------------------+ 0x200000008000 (kOriginAddr) 63 /// | shadow memory | 64 /// +--------------------+ 0x000000010000 (kShadowAddr) 65 /// | reserved by kernel | 66 /// +--------------------+ 0x000000000000 67 /// 68 /// 69 /// To derive a shadow memory address from an application memory address, 70 /// bits 44-46 are cleared to bring the address into the range 71 /// [0x000000008000,0x100000000000). Then the address is shifted left by 1 to 72 /// account for the double byte representation of shadow labels and move the 73 /// address into the shadow memory range. See the function 74 /// DataFlowSanitizer::getShadowAddress below. 75 /// 76 /// For more information, please refer to the design document: 77 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html 78 // 79 //===----------------------------------------------------------------------===// 80 81 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h" 82 #include "llvm/ADT/DenseMap.h" 83 #include "llvm/ADT/DenseSet.h" 84 #include "llvm/ADT/DepthFirstIterator.h" 85 #include "llvm/ADT/None.h" 86 #include "llvm/ADT/SmallPtrSet.h" 87 #include "llvm/ADT/SmallVector.h" 88 #include "llvm/ADT/StringExtras.h" 89 #include "llvm/ADT/StringRef.h" 90 #include "llvm/ADT/Triple.h" 91 #include "llvm/ADT/iterator.h" 92 #include "llvm/Analysis/ValueTracking.h" 93 #include "llvm/IR/Argument.h" 94 #include "llvm/IR/Attributes.h" 95 #include "llvm/IR/BasicBlock.h" 96 #include "llvm/IR/Constant.h" 97 #include "llvm/IR/Constants.h" 98 #include "llvm/IR/DataLayout.h" 99 #include "llvm/IR/DerivedTypes.h" 100 #include "llvm/IR/Dominators.h" 101 #include "llvm/IR/Function.h" 102 #include "llvm/IR/GlobalAlias.h" 103 #include "llvm/IR/GlobalValue.h" 104 #include "llvm/IR/GlobalVariable.h" 105 #include "llvm/IR/IRBuilder.h" 106 #include "llvm/IR/InlineAsm.h" 107 #include "llvm/IR/InstVisitor.h" 108 #include "llvm/IR/InstrTypes.h" 109 #include "llvm/IR/Instruction.h" 110 #include "llvm/IR/Instructions.h" 111 #include "llvm/IR/IntrinsicInst.h" 112 #include "llvm/IR/LLVMContext.h" 113 #include "llvm/IR/MDBuilder.h" 114 #include "llvm/IR/Module.h" 115 #include "llvm/IR/PassManager.h" 116 #include "llvm/IR/Type.h" 117 #include "llvm/IR/User.h" 118 #include "llvm/IR/Value.h" 119 #include "llvm/InitializePasses.h" 120 #include "llvm/Pass.h" 121 #include "llvm/Support/Alignment.h" 122 #include "llvm/Support/Casting.h" 123 #include "llvm/Support/CommandLine.h" 124 #include "llvm/Support/ErrorHandling.h" 125 #include "llvm/Support/SpecialCaseList.h" 126 #include "llvm/Support/VirtualFileSystem.h" 127 #include "llvm/Transforms/Instrumentation.h" 128 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 129 #include "llvm/Transforms/Utils/Local.h" 130 #include <algorithm> 131 #include <cassert> 132 #include <cstddef> 133 #include <cstdint> 134 #include <iterator> 135 #include <memory> 136 #include <set> 137 #include <string> 138 #include <utility> 139 #include <vector> 140 141 using namespace llvm; 142 143 // This must be consistent with ShadowWidthBits. 144 static const Align ShadowTLSAlignment = Align(2); 145 146 static const Align MinOriginAlignment = Align(4); 147 148 // The size of TLS variables. These constants must be kept in sync with the ones 149 // in dfsan.cpp. 150 static const unsigned ArgTLSSize = 800; 151 static const unsigned RetvalTLSSize = 800; 152 153 // External symbol to be used when generating the shadow address for 154 // architectures with multiple VMAs. Instead of using a constant integer 155 // the runtime will set the external mask based on the VMA range. 156 const char DFSanExternShadowPtrMask[] = "__dfsan_shadow_ptr_mask"; 157 158 // The -dfsan-preserve-alignment flag controls whether this pass assumes that 159 // alignment requirements provided by the input IR are correct. For example, 160 // if the input IR contains a load with alignment 8, this flag will cause 161 // the shadow load to have alignment 16. This flag is disabled by default as 162 // we have unfortunately encountered too much code (including Clang itself; 163 // see PR14291) which performs misaligned access. 164 static cl::opt<bool> ClPreserveAlignment( 165 "dfsan-preserve-alignment", 166 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden, 167 cl::init(false)); 168 169 // The ABI list files control how shadow parameters are passed. The pass treats 170 // every function labelled "uninstrumented" in the ABI list file as conforming 171 // to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains 172 // additional annotations for those functions, a call to one of those functions 173 // will produce a warning message, as the labelling behaviour of the function is 174 // unknown. The other supported annotations are "functional" and "discard", 175 // which are described below under DataFlowSanitizer::WrapperKind. 176 static cl::list<std::string> ClABIListFiles( 177 "dfsan-abilist", 178 cl::desc("File listing native ABI functions and how the pass treats them"), 179 cl::Hidden); 180 181 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented 182 // functions (see DataFlowSanitizer::InstrumentedABI below). 183 static cl::opt<bool> 184 ClArgsABI("dfsan-args-abi", 185 cl::desc("Use the argument ABI rather than the TLS ABI"), 186 cl::Hidden); 187 188 // Controls whether the pass includes or ignores the labels of pointers in load 189 // instructions. 190 static cl::opt<bool> ClCombinePointerLabelsOnLoad( 191 "dfsan-combine-pointer-labels-on-load", 192 cl::desc("Combine the label of the pointer with the label of the data when " 193 "loading from memory."), 194 cl::Hidden, cl::init(true)); 195 196 // Controls whether the pass includes or ignores the labels of pointers in 197 // stores instructions. 198 static cl::opt<bool> ClCombinePointerLabelsOnStore( 199 "dfsan-combine-pointer-labels-on-store", 200 cl::desc("Combine the label of the pointer with the label of the data when " 201 "storing in memory."), 202 cl::Hidden, cl::init(false)); 203 204 static cl::opt<bool> ClDebugNonzeroLabels( 205 "dfsan-debug-nonzero-labels", 206 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, " 207 "load or return with a nonzero label"), 208 cl::Hidden); 209 210 // Experimental feature that inserts callbacks for certain data events. 211 // Currently callbacks are only inserted for loads, stores, memory transfers 212 // (i.e. memcpy and memmove), and comparisons. 213 // 214 // If this flag is set to true, the user must provide definitions for the 215 // following callback functions: 216 // void __dfsan_load_callback(dfsan_label Label, void* addr); 217 // void __dfsan_store_callback(dfsan_label Label, void* addr); 218 // void __dfsan_mem_transfer_callback(dfsan_label *Start, size_t Len); 219 // void __dfsan_cmp_callback(dfsan_label CombinedLabel); 220 static cl::opt<bool> ClEventCallbacks( 221 "dfsan-event-callbacks", 222 cl::desc("Insert calls to __dfsan_*_callback functions on data events."), 223 cl::Hidden, cl::init(false)); 224 225 // Use a distinct bit for each base label, enabling faster unions with less 226 // instrumentation. Limits the max number of base labels to 16. 227 static cl::opt<bool> ClFast16Labels( 228 "dfsan-fast-16-labels", 229 cl::desc("Use more efficient instrumentation, limiting the number of " 230 "labels to 16."), 231 cl::Hidden, cl::init(false)); 232 233 // Use a distinct bit for each base label, enabling faster unions with less 234 // instrumentation. Limits the max number of base labels to 8. 235 static cl::opt<bool> ClFast8Labels( 236 "dfsan-fast-8-labels", 237 cl::desc("Use more efficient instrumentation, limiting the number of " 238 "labels to 8."), 239 cl::Hidden, cl::init(false)); 240 241 // Controls whether the pass tracks the control flow of select instructions. 242 static cl::opt<bool> ClTrackSelectControlFlow( 243 "dfsan-track-select-control-flow", 244 cl::desc("Propagate labels from condition values of select instructions " 245 "to results."), 246 cl::Hidden, cl::init(true)); 247 248 // TODO: This default value follows MSan. DFSan may use a different value. 249 static cl::opt<int> ClInstrumentWithCallThreshold( 250 "dfsan-instrument-with-call-threshold", 251 cl::desc("If the function being instrumented requires more than " 252 "this number of origin stores, use callbacks instead of " 253 "inline checks (-1 means never use callbacks)."), 254 cl::Hidden, cl::init(3500)); 255 256 // Controls how to track origins. 257 // * 0: do not track origins. 258 // * 1: track origins at memory store operations. 259 // * 2: TODO: track origins at memory store operations and callsites. 260 static cl::opt<int> ClTrackOrigins("dfsan-track-origins", 261 cl::desc("Track origins of labels"), 262 cl::Hidden, cl::init(0)); 263 264 static StringRef getGlobalTypeString(const GlobalValue &G) { 265 // Types of GlobalVariables are always pointer types. 266 Type *GType = G.getValueType(); 267 // For now we support excluding struct types only. 268 if (StructType *SGType = dyn_cast<StructType>(GType)) { 269 if (!SGType->isLiteral()) 270 return SGType->getName(); 271 } 272 return "<unknown type>"; 273 } 274 275 namespace { 276 277 class DFSanABIList { 278 std::unique_ptr<SpecialCaseList> SCL; 279 280 public: 281 DFSanABIList() = default; 282 283 void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); } 284 285 /// Returns whether either this function or its source file are listed in the 286 /// given category. 287 bool isIn(const Function &F, StringRef Category) const { 288 return isIn(*F.getParent(), Category) || 289 SCL->inSection("dataflow", "fun", F.getName(), Category); 290 } 291 292 /// Returns whether this global alias is listed in the given category. 293 /// 294 /// If GA aliases a function, the alias's name is matched as a function name 295 /// would be. Similarly, aliases of globals are matched like globals. 296 bool isIn(const GlobalAlias &GA, StringRef Category) const { 297 if (isIn(*GA.getParent(), Category)) 298 return true; 299 300 if (isa<FunctionType>(GA.getValueType())) 301 return SCL->inSection("dataflow", "fun", GA.getName(), Category); 302 303 return SCL->inSection("dataflow", "global", GA.getName(), Category) || 304 SCL->inSection("dataflow", "type", getGlobalTypeString(GA), 305 Category); 306 } 307 308 /// Returns whether this module is listed in the given category. 309 bool isIn(const Module &M, StringRef Category) const { 310 return SCL->inSection("dataflow", "src", M.getModuleIdentifier(), Category); 311 } 312 }; 313 314 /// TransformedFunction is used to express the result of transforming one 315 /// function type into another. This struct is immutable. It holds metadata 316 /// useful for updating calls of the old function to the new type. 317 struct TransformedFunction { 318 TransformedFunction(FunctionType *OriginalType, FunctionType *TransformedType, 319 std::vector<unsigned> ArgumentIndexMapping) 320 : OriginalType(OriginalType), TransformedType(TransformedType), 321 ArgumentIndexMapping(ArgumentIndexMapping) {} 322 323 // Disallow copies. 324 TransformedFunction(const TransformedFunction &) = delete; 325 TransformedFunction &operator=(const TransformedFunction &) = delete; 326 327 // Allow moves. 328 TransformedFunction(TransformedFunction &&) = default; 329 TransformedFunction &operator=(TransformedFunction &&) = default; 330 331 /// Type of the function before the transformation. 332 FunctionType *OriginalType; 333 334 /// Type of the function after the transformation. 335 FunctionType *TransformedType; 336 337 /// Transforming a function may change the position of arguments. This 338 /// member records the mapping from each argument's old position to its new 339 /// position. Argument positions are zero-indexed. If the transformation 340 /// from F to F' made the first argument of F into the third argument of F', 341 /// then ArgumentIndexMapping[0] will equal 2. 342 std::vector<unsigned> ArgumentIndexMapping; 343 }; 344 345 /// Given function attributes from a call site for the original function, 346 /// return function attributes appropriate for a call to the transformed 347 /// function. 348 AttributeList 349 transformFunctionAttributes(const TransformedFunction &TransformedFunction, 350 LLVMContext &Ctx, AttributeList CallSiteAttrs) { 351 352 // Construct a vector of AttributeSet for each function argument. 353 std::vector<llvm::AttributeSet> ArgumentAttributes( 354 TransformedFunction.TransformedType->getNumParams()); 355 356 // Copy attributes from the parameter of the original function to the 357 // transformed version. 'ArgumentIndexMapping' holds the mapping from 358 // old argument position to new. 359 for (unsigned I = 0, IE = TransformedFunction.ArgumentIndexMapping.size(); 360 I < IE; ++I) { 361 unsigned TransformedIndex = TransformedFunction.ArgumentIndexMapping[I]; 362 ArgumentAttributes[TransformedIndex] = CallSiteAttrs.getParamAttributes(I); 363 } 364 365 // Copy annotations on varargs arguments. 366 for (unsigned I = TransformedFunction.OriginalType->getNumParams(), 367 IE = CallSiteAttrs.getNumAttrSets(); 368 I < IE; ++I) { 369 ArgumentAttributes.push_back(CallSiteAttrs.getParamAttributes(I)); 370 } 371 372 return AttributeList::get(Ctx, CallSiteAttrs.getFnAttributes(), 373 CallSiteAttrs.getRetAttributes(), 374 llvm::makeArrayRef(ArgumentAttributes)); 375 } 376 377 class DataFlowSanitizer { 378 friend struct DFSanFunction; 379 friend class DFSanVisitor; 380 381 enum { 382 OriginWidthBits = 32, 383 OriginWidthBytes = OriginWidthBits / 8 384 }; 385 386 /// Which ABI should be used for instrumented functions? 387 enum InstrumentedABI { 388 /// Argument and return value labels are passed through additional 389 /// arguments and by modifying the return type. 390 IA_Args, 391 392 /// Argument and return value labels are passed through TLS variables 393 /// __dfsan_arg_tls and __dfsan_retval_tls. 394 IA_TLS 395 }; 396 397 /// How should calls to uninstrumented functions be handled? 398 enum WrapperKind { 399 /// This function is present in an uninstrumented form but we don't know 400 /// how it should be handled. Print a warning and call the function anyway. 401 /// Don't label the return value. 402 WK_Warning, 403 404 /// This function does not write to (user-accessible) memory, and its return 405 /// value is unlabelled. 406 WK_Discard, 407 408 /// This function does not write to (user-accessible) memory, and the label 409 /// of its return value is the union of the label of its arguments. 410 WK_Functional, 411 412 /// Instead of calling the function, a custom wrapper __dfsw_F is called, 413 /// where F is the name of the function. This function may wrap the 414 /// original function or provide its own implementation. This is similar to 415 /// the IA_Args ABI, except that IA_Args uses a struct return type to 416 /// pass the return value shadow in a register, while WK_Custom uses an 417 /// extra pointer argument to return the shadow. This allows the wrapped 418 /// form of the function type to be expressed in C. 419 WK_Custom 420 }; 421 422 unsigned ShadowWidthBits; 423 unsigned ShadowWidthBytes; 424 425 Module *Mod; 426 LLVMContext *Ctx; 427 Type *Int8Ptr; 428 IntegerType *OriginTy; 429 PointerType *OriginPtrTy; 430 ConstantInt *OriginBase; 431 ConstantInt *ZeroOrigin; 432 /// The shadow type for all primitive types and vector types. 433 IntegerType *PrimitiveShadowTy; 434 PointerType *PrimitiveShadowPtrTy; 435 IntegerType *IntptrTy; 436 ConstantInt *ZeroPrimitiveShadow; 437 ConstantInt *ShadowPtrMask; 438 ConstantInt *ShadowPtrMul; 439 Constant *ArgTLS; 440 ArrayType *ArgOriginTLSTy; 441 Constant *ArgOriginTLS; 442 Constant *RetvalTLS; 443 Constant *RetvalOriginTLS; 444 Constant *ExternalShadowMask; 445 FunctionType *DFSanUnionFnTy; 446 FunctionType *DFSanUnionLoadFnTy; 447 FunctionType *DFSanLoadLabelAndOriginFnTy; 448 FunctionType *DFSanUnimplementedFnTy; 449 FunctionType *DFSanSetLabelFnTy; 450 FunctionType *DFSanNonzeroLabelFnTy; 451 FunctionType *DFSanVarargWrapperFnTy; 452 FunctionType *DFSanCmpCallbackFnTy; 453 FunctionType *DFSanLoadStoreCallbackFnTy; 454 FunctionType *DFSanMemTransferCallbackFnTy; 455 FunctionType *DFSanChainOriginFnTy; 456 FunctionType *DFSanMemOriginTransferFnTy; 457 FunctionType *DFSanMaybeStoreOriginFnTy; 458 FunctionCallee DFSanUnionFn; 459 FunctionCallee DFSanCheckedUnionFn; 460 FunctionCallee DFSanUnionLoadFn; 461 FunctionCallee DFSanUnionLoadFastLabelsFn; 462 FunctionCallee DFSanLoadLabelAndOriginFn; 463 FunctionCallee DFSanUnimplementedFn; 464 FunctionCallee DFSanSetLabelFn; 465 FunctionCallee DFSanNonzeroLabelFn; 466 FunctionCallee DFSanVarargWrapperFn; 467 FunctionCallee DFSanLoadCallbackFn; 468 FunctionCallee DFSanStoreCallbackFn; 469 FunctionCallee DFSanMemTransferCallbackFn; 470 FunctionCallee DFSanCmpCallbackFn; 471 FunctionCallee DFSanChainOriginFn; 472 FunctionCallee DFSanMemOriginTransferFn; 473 FunctionCallee DFSanMaybeStoreOriginFn; 474 SmallPtrSet<Value *, 16> DFSanRuntimeFunctions; 475 MDNode *ColdCallWeights; 476 MDNode *OriginStoreWeights; 477 DFSanABIList ABIList; 478 DenseMap<Value *, Function *> UnwrappedFnMap; 479 AttrBuilder ReadOnlyNoneAttrs; 480 bool DFSanRuntimeShadowMask = false; 481 482 Value *getShadowOffset(Value *Addr, IRBuilder<> &IRB); 483 Value *getShadowAddress(Value *Addr, Instruction *Pos); 484 Value *getShadowAddress(Value *Addr, Instruction *Pos, Value *ShadowOffset); 485 std::pair<Value *, Value *> 486 getShadowOriginAddress(Value *Addr, Align InstAlignment, Instruction *Pos); 487 bool isInstrumented(const Function *F); 488 bool isInstrumented(const GlobalAlias *GA); 489 FunctionType *getArgsFunctionType(FunctionType *T); 490 FunctionType *getTrampolineFunctionType(FunctionType *T); 491 TransformedFunction getCustomFunctionType(FunctionType *T); 492 InstrumentedABI getInstrumentedABI(); 493 WrapperKind getWrapperKind(Function *F); 494 void addGlobalNamePrefix(GlobalValue *GV); 495 Function *buildWrapperFunction(Function *F, StringRef NewFName, 496 GlobalValue::LinkageTypes NewFLink, 497 FunctionType *NewFT); 498 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName); 499 void initializeCallbackFunctions(Module &M); 500 void initializeRuntimeFunctions(Module &M); 501 void injectMetadataGlobals(Module &M); 502 503 bool init(Module &M); 504 505 /// Returns whether fast8 or fast16 mode has been specified. 506 bool hasFastLabelsEnabled(); 507 508 /// Returns whether the given load byte size is amenable to inlined 509 /// optimization patterns. 510 bool hasLoadSizeForFastPath(uint64_t Size); 511 512 /// Returns whether the pass tracks origins. Support only fast16 mode in TLS 513 /// ABI mode. 514 bool shouldTrackOrigins(); 515 516 /// Returns whether the pass tracks labels for struct fields and array 517 /// indices. Support only fast16 mode in TLS ABI mode. 518 bool shouldTrackFieldsAndIndices(); 519 520 /// Returns a zero constant with the shadow type of OrigTy. 521 /// 522 /// getZeroShadow({T1,T2,...}) = {getZeroShadow(T1),getZeroShadow(T2,...} 523 /// getZeroShadow([n x T]) = [n x getZeroShadow(T)] 524 /// getZeroShadow(other type) = i16(0) 525 /// 526 /// Note that a zero shadow is always i16(0) when shouldTrackFieldsAndIndices 527 /// returns false. 528 Constant *getZeroShadow(Type *OrigTy); 529 /// Returns a zero constant with the shadow type of V's type. 530 Constant *getZeroShadow(Value *V); 531 532 /// Checks if V is a zero shadow. 533 bool isZeroShadow(Value *V); 534 535 /// Returns the shadow type of OrigTy. 536 /// 537 /// getShadowTy({T1,T2,...}) = {getShadowTy(T1),getShadowTy(T2),...} 538 /// getShadowTy([n x T]) = [n x getShadowTy(T)] 539 /// getShadowTy(other type) = i16 540 /// 541 /// Note that a shadow type is always i16 when shouldTrackFieldsAndIndices 542 /// returns false. 543 Type *getShadowTy(Type *OrigTy); 544 /// Returns the shadow type of of V's type. 545 Type *getShadowTy(Value *V); 546 547 const uint64_t NumOfElementsInArgOrgTLS = ArgTLSSize / OriginWidthBytes; 548 549 public: 550 DataFlowSanitizer(const std::vector<std::string> &ABIListFiles); 551 552 bool runImpl(Module &M); 553 }; 554 555 struct DFSanFunction { 556 DataFlowSanitizer &DFS; 557 Function *F; 558 DominatorTree DT; 559 DataFlowSanitizer::InstrumentedABI IA; 560 bool IsNativeABI; 561 AllocaInst *LabelReturnAlloca = nullptr; 562 AllocaInst *OriginReturnAlloca = nullptr; 563 DenseMap<Value *, Value *> ValShadowMap; 564 DenseMap<Value *, Value *> ValOriginMap; 565 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap; 566 DenseMap<AllocaInst *, AllocaInst *> AllocaOriginMap; 567 568 struct PHIFixupElement { 569 PHINode *Phi; 570 PHINode *ShadowPhi; 571 PHINode *OriginPhi; 572 }; 573 std::vector<PHIFixupElement> PHIFixups; 574 575 DenseSet<Instruction *> SkipInsts; 576 std::vector<Value *> NonZeroChecks; 577 bool AvoidNewBlocks; 578 579 struct CachedShadow { 580 BasicBlock *Block; // The block where Shadow is defined. 581 Value *Shadow; 582 }; 583 /// Maps a value to its latest shadow value in terms of domination tree. 584 DenseMap<std::pair<Value *, Value *>, CachedShadow> CachedShadows; 585 /// Maps a value to its latest collapsed shadow value it was converted to in 586 /// terms of domination tree. When ClDebugNonzeroLabels is on, this cache is 587 /// used at a post process where CFG blocks are split. So it does not cache 588 /// BasicBlock like CachedShadows, but uses domination between values. 589 DenseMap<Value *, Value *> CachedCollapsedShadows; 590 DenseMap<Value *, std::set<Value *>> ShadowElements; 591 592 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI) 593 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()), IsNativeABI(IsNativeABI) { 594 DT.recalculate(*F); 595 // FIXME: Need to track down the register allocator issue which causes poor 596 // performance in pathological cases with large numbers of basic blocks. 597 AvoidNewBlocks = F->size() > 1000; 598 } 599 600 /// Computes the shadow address for a given function argument. 601 /// 602 /// Shadow = ArgTLS+ArgOffset. 603 Value *getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB); 604 605 /// Computes the shadow address for a return value. 606 Value *getRetvalTLS(Type *T, IRBuilder<> &IRB); 607 608 /// Computes the origin address for a given function argument. 609 /// 610 /// Origin = ArgOriginTLS[ArgNo]. 611 Value *getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB); 612 613 /// Computes the origin address for a return value. 614 Value *getRetvalOriginTLS(); 615 616 Value *getOrigin(Value *V); 617 void setOrigin(Instruction *I, Value *Origin); 618 /// Generates IR to compute the origin of the last operand with a taint label. 619 Value *combineOperandOrigins(Instruction *Inst); 620 /// Before the instruction Pos, generates IR to compute the last origin with a 621 /// taint label. Labels and origins are from vectors Shadows and Origins 622 /// correspondingly. The generated IR is like 623 /// Sn-1 != Zero ? On-1: ... S2 != Zero ? O2: S1 != Zero ? O1: O0 624 /// When Zero is nullptr, it uses ZeroPrimitiveShadow. Otherwise it can be 625 /// zeros with other bitwidths. 626 Value *combineOrigins(const std::vector<Value *> &Shadows, 627 const std::vector<Value *> &Origins, Instruction *Pos, 628 ConstantInt *Zero = nullptr); 629 630 Value *getShadow(Value *V); 631 void setShadow(Instruction *I, Value *Shadow); 632 /// Generates IR to compute the union of the two given shadows, inserting it 633 /// before Pos. The combined value is with primitive type. 634 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos); 635 /// Combines the shadow values of V1 and V2, then converts the combined value 636 /// with primitive type into a shadow value with the original type T. 637 Value *combineShadowsThenConvert(Type *T, Value *V1, Value *V2, 638 Instruction *Pos); 639 Value *combineOperandShadows(Instruction *Inst); 640 std::pair<Value *, Value *> loadShadowOrigin(Value *ShadowAddr, uint64_t Size, 641 Align InstAlignment, 642 Instruction *Pos); 643 void storePrimitiveShadowOrigin(Value *Addr, uint64_t Size, 644 Align InstAlignment, Value *PrimitiveShadow, 645 Value *Origin, Instruction *Pos); 646 /// Applies PrimitiveShadow to all primitive subtypes of T, returning 647 /// the expanded shadow value. 648 /// 649 /// EFP({T1,T2, ...}, PS) = {EFP(T1,PS),EFP(T2,PS),...} 650 /// EFP([n x T], PS) = [n x EFP(T,PS)] 651 /// EFP(other types, PS) = PS 652 Value *expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow, 653 Instruction *Pos); 654 /// Collapses Shadow into a single primitive shadow value, unioning all 655 /// primitive shadow values in the process. Returns the final primitive 656 /// shadow value. 657 /// 658 /// CTP({V1,V2, ...}) = UNION(CFP(V1,PS),CFP(V2,PS),...) 659 /// CTP([V1,V2,...]) = UNION(CFP(V1,PS),CFP(V2,PS),...) 660 /// CTP(other types, PS) = PS 661 Value *collapseToPrimitiveShadow(Value *Shadow, Instruction *Pos); 662 663 void storeZeroPrimitiveShadow(Value *Addr, uint64_t Size, Align ShadowAlign, 664 Instruction *Pos); 665 666 Align getShadowAlign(Align InstAlignment); 667 668 private: 669 /// Collapses the shadow with aggregate type into a single primitive shadow 670 /// value. 671 template <class AggregateType> 672 Value *collapseAggregateShadow(AggregateType *AT, Value *Shadow, 673 IRBuilder<> &IRB); 674 675 Value *collapseToPrimitiveShadow(Value *Shadow, IRBuilder<> &IRB); 676 677 /// Returns the shadow value of an argument A. 678 Value *getShadowForTLSArgument(Argument *A); 679 680 /// The fast path of loading shadow in legacy mode. 681 Value *loadLegacyShadowFast(Value *ShadowAddr, uint64_t Size, 682 Align ShadowAlign, Instruction *Pos); 683 684 /// The fast path of loading shadow in fast-16-label mode. 685 std::pair<Value *, Value *> 686 loadFast16ShadowFast(Value *ShadowAddr, Value *OriginAddr, uint64_t Size, 687 Align ShadowAlign, Align OriginAlign, Value *FirstOrigin, 688 Instruction *Pos); 689 690 Align getOriginAlign(Align InstAlignment); 691 692 /// Because 4 contiguous bytes share one 4-byte origin, the most accurate load 693 /// is __dfsan_load_label_and_origin. This function returns the union of all 694 /// labels and the origin of the first taint label. However this is an 695 /// additional call with many instructions. To ensure common cases are fast, 696 /// checks if it is possible to load labels and origins without using the 697 /// callback function. 698 bool useCallbackLoadLabelAndOrigin(uint64_t Size, Align InstAlignment); 699 700 /// Returns a chain at the current stack with previous origin V. 701 Value *updateOrigin(Value *V, IRBuilder<> &IRB); 702 703 /// Creates an Intptr = Origin | Origin << 32 if Intptr's size is 64. Returns 704 /// Origin otherwise. 705 Value *originToIntptr(IRBuilder<> &IRB, Value *Origin); 706 707 /// Stores Origin into the address range [StoreOriginAddr, StoreOriginAddr + 708 /// Size). 709 void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *StoreOriginAddr, 710 uint64_t StoreOriginSize, Align Alignment); 711 712 /// Stores Origin in terms of its Shadow value. 713 /// * Do not write origins for zero shadows because we do not trace origins 714 /// for untainted sinks. 715 /// * Use __dfsan_maybe_store_origin if there are too many origin store 716 /// instrumentations. 717 void storeOrigin(Instruction *Pos, Value *Addr, uint64_t Size, Value *Shadow, 718 Value *Origin, Value *StoreOriginAddr, Align InstAlignment); 719 720 /// Convert a scalar value to an i1 by comparing with 0. 721 Value *convertToBool(Value *V, IRBuilder<> &IRB, const Twine &Name = ""); 722 723 bool shouldInstrumentWithCall(); 724 725 int NumOriginStores = 0; 726 }; 727 728 class DFSanVisitor : public InstVisitor<DFSanVisitor> { 729 public: 730 DFSanFunction &DFSF; 731 732 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {} 733 734 const DataLayout &getDataLayout() const { 735 return DFSF.F->getParent()->getDataLayout(); 736 } 737 738 // Combines shadow values and origins for all of I's operands. 739 void visitInstOperands(Instruction &I); 740 741 void visitUnaryOperator(UnaryOperator &UO); 742 void visitBinaryOperator(BinaryOperator &BO); 743 void visitCastInst(CastInst &CI); 744 void visitCmpInst(CmpInst &CI); 745 void visitGetElementPtrInst(GetElementPtrInst &GEPI); 746 void visitLoadInst(LoadInst &LI); 747 void visitStoreInst(StoreInst &SI); 748 void visitAtomicRMWInst(AtomicRMWInst &I); 749 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I); 750 void visitReturnInst(ReturnInst &RI); 751 void visitCallBase(CallBase &CB); 752 void visitPHINode(PHINode &PN); 753 void visitExtractElementInst(ExtractElementInst &I); 754 void visitInsertElementInst(InsertElementInst &I); 755 void visitShuffleVectorInst(ShuffleVectorInst &I); 756 void visitExtractValueInst(ExtractValueInst &I); 757 void visitInsertValueInst(InsertValueInst &I); 758 void visitAllocaInst(AllocaInst &I); 759 void visitSelectInst(SelectInst &I); 760 void visitMemSetInst(MemSetInst &I); 761 void visitMemTransferInst(MemTransferInst &I); 762 763 private: 764 void visitCASOrRMW(Align InstAlignment, Instruction &I); 765 766 // Returns false when this is an invoke of a custom function. 767 bool visitWrappedCallBase(Function &F, CallBase &CB); 768 769 // Combines origins for all of I's operands. 770 void visitInstOperandOrigins(Instruction &I); 771 772 void addShadowArguments(Function &F, CallBase &CB, std::vector<Value *> &Args, 773 IRBuilder<> &IRB); 774 775 void addOriginArguments(Function &F, CallBase &CB, std::vector<Value *> &Args, 776 IRBuilder<> &IRB); 777 }; 778 779 } // end anonymous namespace 780 781 DataFlowSanitizer::DataFlowSanitizer( 782 const std::vector<std::string> &ABIListFiles) { 783 if (ClFast8Labels && ClFast16Labels) { 784 report_fatal_error( 785 "cannot set both -dfsan-fast-8-labels and -dfsan-fast-16-labels"); 786 } 787 788 ShadowWidthBits = ClFast8Labels ? 8 : 16; 789 ShadowWidthBytes = ShadowWidthBits / 8; 790 791 std::vector<std::string> AllABIListFiles(std::move(ABIListFiles)); 792 llvm::append_range(AllABIListFiles, ClABIListFiles); 793 // FIXME: should we propagate vfs::FileSystem to this constructor? 794 ABIList.set( 795 SpecialCaseList::createOrDie(AllABIListFiles, *vfs::getRealFileSystem())); 796 } 797 798 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) { 799 SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end()); 800 ArgTypes.append(T->getNumParams(), PrimitiveShadowTy); 801 if (T->isVarArg()) 802 ArgTypes.push_back(PrimitiveShadowPtrTy); 803 Type *RetType = T->getReturnType(); 804 if (!RetType->isVoidTy()) 805 RetType = StructType::get(RetType, PrimitiveShadowTy); 806 return FunctionType::get(RetType, ArgTypes, T->isVarArg()); 807 } 808 809 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) { 810 assert(!T->isVarArg()); 811 SmallVector<Type *, 4> ArgTypes; 812 ArgTypes.push_back(T->getPointerTo()); 813 ArgTypes.append(T->param_begin(), T->param_end()); 814 ArgTypes.append(T->getNumParams(), PrimitiveShadowTy); 815 Type *RetType = T->getReturnType(); 816 if (!RetType->isVoidTy()) 817 ArgTypes.push_back(PrimitiveShadowPtrTy); 818 819 if (shouldTrackOrigins()) { 820 ArgTypes.append(T->getNumParams(), OriginTy); 821 if (!RetType->isVoidTy()) 822 ArgTypes.push_back(OriginPtrTy); 823 } 824 825 return FunctionType::get(T->getReturnType(), ArgTypes, false); 826 } 827 828 TransformedFunction DataFlowSanitizer::getCustomFunctionType(FunctionType *T) { 829 SmallVector<Type *, 4> ArgTypes; 830 831 // Some parameters of the custom function being constructed are 832 // parameters of T. Record the mapping from parameters of T to 833 // parameters of the custom function, so that parameter attributes 834 // at call sites can be updated. 835 std::vector<unsigned> ArgumentIndexMapping; 836 for (unsigned I = 0, E = T->getNumParams(); I != E; ++I) { 837 Type *ParamType = T->getParamType(I); 838 FunctionType *FT; 839 if (isa<PointerType>(ParamType) && 840 (FT = dyn_cast<FunctionType>(ParamType->getPointerElementType()))) { 841 ArgumentIndexMapping.push_back(ArgTypes.size()); 842 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo()); 843 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx)); 844 } else { 845 ArgumentIndexMapping.push_back(ArgTypes.size()); 846 ArgTypes.push_back(ParamType); 847 } 848 } 849 for (unsigned I = 0, E = T->getNumParams(); I != E; ++I) 850 ArgTypes.push_back(PrimitiveShadowTy); 851 if (T->isVarArg()) 852 ArgTypes.push_back(PrimitiveShadowPtrTy); 853 Type *RetType = T->getReturnType(); 854 if (!RetType->isVoidTy()) 855 ArgTypes.push_back(PrimitiveShadowPtrTy); 856 857 if (shouldTrackOrigins()) { 858 for (unsigned I = 0, E = T->getNumParams(); I != E; ++I) 859 ArgTypes.push_back(OriginTy); 860 if (T->isVarArg()) 861 ArgTypes.push_back(OriginPtrTy); 862 if (!RetType->isVoidTy()) 863 ArgTypes.push_back(OriginPtrTy); 864 } 865 866 return TransformedFunction( 867 T, FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg()), 868 ArgumentIndexMapping); 869 } 870 871 bool DataFlowSanitizer::isZeroShadow(Value *V) { 872 if (!shouldTrackFieldsAndIndices()) 873 return ZeroPrimitiveShadow == V; 874 875 Type *T = V->getType(); 876 if (!isa<ArrayType>(T) && !isa<StructType>(T)) { 877 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) 878 return CI->isZero(); 879 return false; 880 } 881 882 return isa<ConstantAggregateZero>(V); 883 } 884 885 bool DataFlowSanitizer::hasFastLabelsEnabled() { 886 static const bool HasFastLabelsEnabled = ClFast8Labels || ClFast16Labels; 887 return HasFastLabelsEnabled; 888 } 889 890 bool DataFlowSanitizer::hasLoadSizeForFastPath(uint64_t Size) { 891 uint64_t ShadowSize = Size * ShadowWidthBytes; 892 return ShadowSize % 8 == 0 || ShadowSize == 4; 893 } 894 895 bool DataFlowSanitizer::shouldTrackOrigins() { 896 static const bool ShouldTrackOrigins = 897 ClTrackOrigins && getInstrumentedABI() == DataFlowSanitizer::IA_TLS && 898 hasFastLabelsEnabled(); 899 return ShouldTrackOrigins; 900 } 901 902 bool DataFlowSanitizer::shouldTrackFieldsAndIndices() { 903 return getInstrumentedABI() == DataFlowSanitizer::IA_TLS && 904 hasFastLabelsEnabled(); 905 } 906 907 Constant *DataFlowSanitizer::getZeroShadow(Type *OrigTy) { 908 if (!shouldTrackFieldsAndIndices()) 909 return ZeroPrimitiveShadow; 910 911 if (!isa<ArrayType>(OrigTy) && !isa<StructType>(OrigTy)) 912 return ZeroPrimitiveShadow; 913 Type *ShadowTy = getShadowTy(OrigTy); 914 return ConstantAggregateZero::get(ShadowTy); 915 } 916 917 Constant *DataFlowSanitizer::getZeroShadow(Value *V) { 918 return getZeroShadow(V->getType()); 919 } 920 921 static Value *expandFromPrimitiveShadowRecursive( 922 Value *Shadow, SmallVector<unsigned, 4> &Indices, Type *SubShadowTy, 923 Value *PrimitiveShadow, IRBuilder<> &IRB) { 924 if (!isa<ArrayType>(SubShadowTy) && !isa<StructType>(SubShadowTy)) 925 return IRB.CreateInsertValue(Shadow, PrimitiveShadow, Indices); 926 927 if (ArrayType *AT = dyn_cast<ArrayType>(SubShadowTy)) { 928 for (unsigned Idx = 0; Idx < AT->getNumElements(); Idx++) { 929 Indices.push_back(Idx); 930 Shadow = expandFromPrimitiveShadowRecursive( 931 Shadow, Indices, AT->getElementType(), PrimitiveShadow, IRB); 932 Indices.pop_back(); 933 } 934 return Shadow; 935 } 936 937 if (StructType *ST = dyn_cast<StructType>(SubShadowTy)) { 938 for (unsigned Idx = 0; Idx < ST->getNumElements(); Idx++) { 939 Indices.push_back(Idx); 940 Shadow = expandFromPrimitiveShadowRecursive( 941 Shadow, Indices, ST->getElementType(Idx), PrimitiveShadow, IRB); 942 Indices.pop_back(); 943 } 944 return Shadow; 945 } 946 llvm_unreachable("Unexpected shadow type"); 947 } 948 949 bool DFSanFunction::shouldInstrumentWithCall() { 950 return ClInstrumentWithCallThreshold >= 0 && 951 NumOriginStores >= ClInstrumentWithCallThreshold; 952 } 953 954 Value *DFSanFunction::expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow, 955 Instruction *Pos) { 956 Type *ShadowTy = DFS.getShadowTy(T); 957 958 if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy)) 959 return PrimitiveShadow; 960 961 if (DFS.isZeroShadow(PrimitiveShadow)) 962 return DFS.getZeroShadow(ShadowTy); 963 964 IRBuilder<> IRB(Pos); 965 SmallVector<unsigned, 4> Indices; 966 Value *Shadow = UndefValue::get(ShadowTy); 967 Shadow = expandFromPrimitiveShadowRecursive(Shadow, Indices, ShadowTy, 968 PrimitiveShadow, IRB); 969 970 // Caches the primitive shadow value that built the shadow value. 971 CachedCollapsedShadows[Shadow] = PrimitiveShadow; 972 return Shadow; 973 } 974 975 template <class AggregateType> 976 Value *DFSanFunction::collapseAggregateShadow(AggregateType *AT, Value *Shadow, 977 IRBuilder<> &IRB) { 978 if (!AT->getNumElements()) 979 return DFS.ZeroPrimitiveShadow; 980 981 Value *FirstItem = IRB.CreateExtractValue(Shadow, 0); 982 Value *Aggregator = collapseToPrimitiveShadow(FirstItem, IRB); 983 984 for (unsigned Idx = 1; Idx < AT->getNumElements(); Idx++) { 985 Value *ShadowItem = IRB.CreateExtractValue(Shadow, Idx); 986 Value *ShadowInner = collapseToPrimitiveShadow(ShadowItem, IRB); 987 Aggregator = IRB.CreateOr(Aggregator, ShadowInner); 988 } 989 return Aggregator; 990 } 991 992 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow, 993 IRBuilder<> &IRB) { 994 Type *ShadowTy = Shadow->getType(); 995 if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy)) 996 return Shadow; 997 if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) 998 return collapseAggregateShadow<>(AT, Shadow, IRB); 999 if (StructType *ST = dyn_cast<StructType>(ShadowTy)) 1000 return collapseAggregateShadow<>(ST, Shadow, IRB); 1001 llvm_unreachable("Unexpected shadow type"); 1002 } 1003 1004 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow, 1005 Instruction *Pos) { 1006 Type *ShadowTy = Shadow->getType(); 1007 if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy)) 1008 return Shadow; 1009 1010 assert(DFS.shouldTrackFieldsAndIndices()); 1011 1012 // Checks if the cached collapsed shadow value dominates Pos. 1013 Value *&CS = CachedCollapsedShadows[Shadow]; 1014 if (CS && DT.dominates(CS, Pos)) 1015 return CS; 1016 1017 IRBuilder<> IRB(Pos); 1018 Value *PrimitiveShadow = collapseToPrimitiveShadow(Shadow, IRB); 1019 // Caches the converted primitive shadow value. 1020 CS = PrimitiveShadow; 1021 return PrimitiveShadow; 1022 } 1023 1024 Type *DataFlowSanitizer::getShadowTy(Type *OrigTy) { 1025 if (!shouldTrackFieldsAndIndices()) 1026 return PrimitiveShadowTy; 1027 1028 if (!OrigTy->isSized()) 1029 return PrimitiveShadowTy; 1030 if (isa<IntegerType>(OrigTy)) 1031 return PrimitiveShadowTy; 1032 if (isa<VectorType>(OrigTy)) 1033 return PrimitiveShadowTy; 1034 if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) 1035 return ArrayType::get(getShadowTy(AT->getElementType()), 1036 AT->getNumElements()); 1037 if (StructType *ST = dyn_cast<StructType>(OrigTy)) { 1038 SmallVector<Type *, 4> Elements; 1039 for (unsigned I = 0, N = ST->getNumElements(); I < N; ++I) 1040 Elements.push_back(getShadowTy(ST->getElementType(I))); 1041 return StructType::get(*Ctx, Elements); 1042 } 1043 return PrimitiveShadowTy; 1044 } 1045 1046 Type *DataFlowSanitizer::getShadowTy(Value *V) { 1047 return getShadowTy(V->getType()); 1048 } 1049 1050 bool DataFlowSanitizer::init(Module &M) { 1051 Triple TargetTriple(M.getTargetTriple()); 1052 const DataLayout &DL = M.getDataLayout(); 1053 1054 Mod = &M; 1055 Ctx = &M.getContext(); 1056 Int8Ptr = Type::getInt8PtrTy(*Ctx); 1057 OriginTy = IntegerType::get(*Ctx, OriginWidthBits); 1058 OriginPtrTy = PointerType::getUnqual(OriginTy); 1059 PrimitiveShadowTy = IntegerType::get(*Ctx, ShadowWidthBits); 1060 PrimitiveShadowPtrTy = PointerType::getUnqual(PrimitiveShadowTy); 1061 IntptrTy = DL.getIntPtrType(*Ctx); 1062 ZeroPrimitiveShadow = ConstantInt::getSigned(PrimitiveShadowTy, 0); 1063 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidthBytes); 1064 OriginBase = ConstantInt::get(IntptrTy, 0x200000000000LL); 1065 ZeroOrigin = ConstantInt::getSigned(OriginTy, 0); 1066 1067 switch (TargetTriple.getArch()) { 1068 case Triple::x86_64: 1069 ShadowPtrMask = ClFast8Labels 1070 ? ConstantInt::getSigned(IntptrTy, ~0x600000000000LL) 1071 : ConstantInt::getSigned(IntptrTy, ~0x700000000000LL); 1072 break; 1073 case Triple::mips64: 1074 case Triple::mips64el: 1075 ShadowPtrMask = ClFast8Labels 1076 ? ConstantInt::getSigned(IntptrTy, ~0xE000000000LL) 1077 : ConstantInt::getSigned(IntptrTy, ~0xF000000000LL); 1078 break; 1079 case Triple::aarch64: 1080 case Triple::aarch64_be: 1081 // AArch64 supports multiple VMAs and the shadow mask is set at runtime. 1082 DFSanRuntimeShadowMask = true; 1083 break; 1084 default: 1085 report_fatal_error("unsupported triple"); 1086 } 1087 1088 Type *DFSanUnionArgs[2] = {PrimitiveShadowTy, PrimitiveShadowTy}; 1089 DFSanUnionFnTy = 1090 FunctionType::get(PrimitiveShadowTy, DFSanUnionArgs, /*isVarArg=*/false); 1091 Type *DFSanUnionLoadArgs[2] = {PrimitiveShadowPtrTy, IntptrTy}; 1092 DFSanUnionLoadFnTy = FunctionType::get(PrimitiveShadowTy, DFSanUnionLoadArgs, 1093 /*isVarArg=*/false); 1094 Type *DFSanLoadLabelAndOriginArgs[2] = {Int8Ptr, IntptrTy}; 1095 DFSanLoadLabelAndOriginFnTy = 1096 FunctionType::get(IntegerType::get(*Ctx, 64), DFSanLoadLabelAndOriginArgs, 1097 /*isVarArg=*/false); 1098 DFSanUnimplementedFnTy = FunctionType::get( 1099 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false); 1100 Type *DFSanSetLabelArgs[4] = {PrimitiveShadowTy, OriginTy, 1101 Type::getInt8PtrTy(*Ctx), IntptrTy}; 1102 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx), 1103 DFSanSetLabelArgs, /*isVarArg=*/false); 1104 DFSanNonzeroLabelFnTy = 1105 FunctionType::get(Type::getVoidTy(*Ctx), None, /*isVarArg=*/false); 1106 DFSanVarargWrapperFnTy = FunctionType::get( 1107 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false); 1108 DFSanCmpCallbackFnTy = 1109 FunctionType::get(Type::getVoidTy(*Ctx), PrimitiveShadowTy, 1110 /*isVarArg=*/false); 1111 DFSanChainOriginFnTy = 1112 FunctionType::get(OriginTy, OriginTy, /*isVarArg=*/false); 1113 Type *DFSanMaybeStoreOriginArgs[4] = {IntegerType::get(*Ctx, ShadowWidthBits), 1114 Int8Ptr, IntptrTy, OriginTy}; 1115 DFSanMaybeStoreOriginFnTy = FunctionType::get( 1116 Type::getVoidTy(*Ctx), DFSanMaybeStoreOriginArgs, /*isVarArg=*/false); 1117 Type *DFSanMemOriginTransferArgs[3] = {Int8Ptr, Int8Ptr, IntptrTy}; 1118 DFSanMemOriginTransferFnTy = FunctionType::get( 1119 Type::getVoidTy(*Ctx), DFSanMemOriginTransferArgs, /*isVarArg=*/false); 1120 Type *DFSanLoadStoreCallbackArgs[2] = {PrimitiveShadowTy, Int8Ptr}; 1121 DFSanLoadStoreCallbackFnTy = 1122 FunctionType::get(Type::getVoidTy(*Ctx), DFSanLoadStoreCallbackArgs, 1123 /*isVarArg=*/false); 1124 Type *DFSanMemTransferCallbackArgs[2] = {PrimitiveShadowPtrTy, IntptrTy}; 1125 DFSanMemTransferCallbackFnTy = 1126 FunctionType::get(Type::getVoidTy(*Ctx), DFSanMemTransferCallbackArgs, 1127 /*isVarArg=*/false); 1128 1129 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000); 1130 OriginStoreWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000); 1131 return true; 1132 } 1133 1134 bool DataFlowSanitizer::isInstrumented(const Function *F) { 1135 return !ABIList.isIn(*F, "uninstrumented"); 1136 } 1137 1138 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) { 1139 return !ABIList.isIn(*GA, "uninstrumented"); 1140 } 1141 1142 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() { 1143 return ClArgsABI ? IA_Args : IA_TLS; 1144 } 1145 1146 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) { 1147 if (ABIList.isIn(*F, "functional")) 1148 return WK_Functional; 1149 if (ABIList.isIn(*F, "discard")) 1150 return WK_Discard; 1151 if (ABIList.isIn(*F, "custom")) 1152 return WK_Custom; 1153 1154 return WK_Warning; 1155 } 1156 1157 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) { 1158 std::string GVName = std::string(GV->getName()), Prefix = "dfs$"; 1159 GV->setName(Prefix + GVName); 1160 1161 // Try to change the name of the function in module inline asm. We only do 1162 // this for specific asm directives, currently only ".symver", to try to avoid 1163 // corrupting asm which happens to contain the symbol name as a substring. 1164 // Note that the substitution for .symver assumes that the versioned symbol 1165 // also has an instrumented name. 1166 std::string Asm = GV->getParent()->getModuleInlineAsm(); 1167 std::string SearchStr = ".symver " + GVName + ","; 1168 size_t Pos = Asm.find(SearchStr); 1169 if (Pos != std::string::npos) { 1170 Asm.replace(Pos, SearchStr.size(), 1171 ".symver " + Prefix + GVName + "," + Prefix); 1172 GV->getParent()->setModuleInlineAsm(Asm); 1173 } 1174 } 1175 1176 Function * 1177 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName, 1178 GlobalValue::LinkageTypes NewFLink, 1179 FunctionType *NewFT) { 1180 FunctionType *FT = F->getFunctionType(); 1181 Function *NewF = Function::Create(NewFT, NewFLink, F->getAddressSpace(), 1182 NewFName, F->getParent()); 1183 NewF->copyAttributesFrom(F); 1184 NewF->removeAttributes( 1185 AttributeList::ReturnIndex, 1186 AttributeFuncs::typeIncompatible(NewFT->getReturnType())); 1187 1188 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF); 1189 if (F->isVarArg()) { 1190 NewF->removeAttributes(AttributeList::FunctionIndex, 1191 AttrBuilder().addAttribute("split-stack")); 1192 CallInst::Create(DFSanVarargWrapperFn, 1193 IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "", 1194 BB); 1195 new UnreachableInst(*Ctx, BB); 1196 } else { 1197 auto ArgIt = pointer_iterator<Argument *>(NewF->arg_begin()); 1198 std::vector<Value *> Args(ArgIt, ArgIt + FT->getNumParams()); 1199 1200 CallInst *CI = CallInst::Create(F, Args, "", BB); 1201 if (FT->getReturnType()->isVoidTy()) 1202 ReturnInst::Create(*Ctx, BB); 1203 else 1204 ReturnInst::Create(*Ctx, CI, BB); 1205 } 1206 1207 return NewF; 1208 } 1209 1210 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT, 1211 StringRef FName) { 1212 FunctionType *FTT = getTrampolineFunctionType(FT); 1213 FunctionCallee C = Mod->getOrInsertFunction(FName, FTT); 1214 Function *F = dyn_cast<Function>(C.getCallee()); 1215 if (F && F->isDeclaration()) { 1216 F->setLinkage(GlobalValue::LinkOnceODRLinkage); 1217 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F); 1218 std::vector<Value *> Args; 1219 Function::arg_iterator AI = F->arg_begin() + 1; 1220 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N) 1221 Args.push_back(&*AI); 1222 CallInst *CI = CallInst::Create(FT, &*F->arg_begin(), Args, "", BB); 1223 Type *RetType = FT->getReturnType(); 1224 ReturnInst *RI = RetType->isVoidTy() ? ReturnInst::Create(*Ctx, BB) 1225 : ReturnInst::Create(*Ctx, CI, BB); 1226 1227 // F is called by a wrapped custom function with primitive shadows. So 1228 // its arguments and return value need conversion. 1229 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true); 1230 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; 1231 ++ValAI; 1232 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N) { 1233 Value *Shadow = 1234 DFSF.expandFromPrimitiveShadow(ValAI->getType(), &*ShadowAI, CI); 1235 DFSF.ValShadowMap[&*ValAI] = Shadow; 1236 } 1237 Function::arg_iterator RetShadowAI = ShadowAI; 1238 const bool ShouldTrackOrigins = shouldTrackOrigins(); 1239 if (ShouldTrackOrigins) { 1240 ValAI = F->arg_begin(); 1241 ++ValAI; 1242 Function::arg_iterator OriginAI = ShadowAI; 1243 if (!RetType->isVoidTy()) 1244 ++OriginAI; 1245 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++OriginAI, --N) { 1246 DFSF.ValOriginMap[&*ValAI] = &*OriginAI; 1247 } 1248 } 1249 DFSanVisitor(DFSF).visitCallInst(*CI); 1250 if (!RetType->isVoidTy()) { 1251 Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow( 1252 DFSF.getShadow(RI->getReturnValue()), RI); 1253 new StoreInst(PrimitiveShadow, &*RetShadowAI, RI); 1254 if (ShouldTrackOrigins) { 1255 Value *Origin = DFSF.getOrigin(RI->getReturnValue()); 1256 new StoreInst(Origin, &*std::prev(F->arg_end()), RI); 1257 } 1258 } 1259 } 1260 1261 return cast<Constant>(C.getCallee()); 1262 } 1263 1264 // Initialize DataFlowSanitizer runtime functions and declare them in the module 1265 void DataFlowSanitizer::initializeRuntimeFunctions(Module &M) { 1266 { 1267 AttributeList AL; 1268 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex, 1269 Attribute::NoUnwind); 1270 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex, 1271 Attribute::ReadNone); 1272 AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex, 1273 Attribute::ZExt); 1274 AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt); 1275 AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt); 1276 DFSanUnionFn = 1277 Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy, AL); 1278 } 1279 { 1280 AttributeList AL; 1281 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex, 1282 Attribute::NoUnwind); 1283 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex, 1284 Attribute::ReadNone); 1285 AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex, 1286 Attribute::ZExt); 1287 AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt); 1288 AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt); 1289 DFSanCheckedUnionFn = 1290 Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy, AL); 1291 } 1292 { 1293 AttributeList AL; 1294 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex, 1295 Attribute::NoUnwind); 1296 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex, 1297 Attribute::ReadOnly); 1298 AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex, 1299 Attribute::ZExt); 1300 DFSanUnionLoadFn = 1301 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy, AL); 1302 } 1303 { 1304 AttributeList AL; 1305 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex, 1306 Attribute::NoUnwind); 1307 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex, 1308 Attribute::ReadOnly); 1309 AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex, 1310 Attribute::ZExt); 1311 DFSanUnionLoadFastLabelsFn = Mod->getOrInsertFunction( 1312 "__dfsan_union_load_fast16labels", DFSanUnionLoadFnTy, AL); 1313 } 1314 { 1315 AttributeList AL; 1316 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex, 1317 Attribute::NoUnwind); 1318 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex, 1319 Attribute::ReadOnly); 1320 AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex, 1321 Attribute::ZExt); 1322 DFSanLoadLabelAndOriginFn = Mod->getOrInsertFunction( 1323 "__dfsan_load_label_and_origin", DFSanLoadLabelAndOriginFnTy, AL); 1324 } 1325 DFSanUnimplementedFn = 1326 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy); 1327 { 1328 AttributeList AL; 1329 AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt); 1330 AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt); 1331 DFSanSetLabelFn = 1332 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy, AL); 1333 } 1334 DFSanNonzeroLabelFn = 1335 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy); 1336 DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper", 1337 DFSanVarargWrapperFnTy); 1338 { 1339 AttributeList AL; 1340 AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt); 1341 AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex, 1342 Attribute::ZExt); 1343 DFSanChainOriginFn = Mod->getOrInsertFunction("__dfsan_chain_origin", 1344 DFSanChainOriginFnTy, AL); 1345 } 1346 DFSanMemOriginTransferFn = Mod->getOrInsertFunction( 1347 "__dfsan_mem_origin_transfer", DFSanMemOriginTransferFnTy); 1348 1349 { 1350 AttributeList AL; 1351 AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt); 1352 AL = AL.addParamAttribute(M.getContext(), 3, Attribute::ZExt); 1353 DFSanMaybeStoreOriginFn = Mod->getOrInsertFunction( 1354 "__dfsan_maybe_store_origin", DFSanMaybeStoreOriginFnTy, AL); 1355 } 1356 1357 DFSanRuntimeFunctions.insert(DFSanUnionFn.getCallee()->stripPointerCasts()); 1358 DFSanRuntimeFunctions.insert( 1359 DFSanCheckedUnionFn.getCallee()->stripPointerCasts()); 1360 DFSanRuntimeFunctions.insert( 1361 DFSanUnionLoadFn.getCallee()->stripPointerCasts()); 1362 DFSanRuntimeFunctions.insert( 1363 DFSanUnionLoadFastLabelsFn.getCallee()->stripPointerCasts()); 1364 DFSanRuntimeFunctions.insert( 1365 DFSanLoadLabelAndOriginFn.getCallee()->stripPointerCasts()); 1366 DFSanRuntimeFunctions.insert( 1367 DFSanUnimplementedFn.getCallee()->stripPointerCasts()); 1368 DFSanRuntimeFunctions.insert( 1369 DFSanSetLabelFn.getCallee()->stripPointerCasts()); 1370 DFSanRuntimeFunctions.insert( 1371 DFSanNonzeroLabelFn.getCallee()->stripPointerCasts()); 1372 DFSanRuntimeFunctions.insert( 1373 DFSanVarargWrapperFn.getCallee()->stripPointerCasts()); 1374 DFSanRuntimeFunctions.insert( 1375 DFSanLoadCallbackFn.getCallee()->stripPointerCasts()); 1376 DFSanRuntimeFunctions.insert( 1377 DFSanStoreCallbackFn.getCallee()->stripPointerCasts()); 1378 DFSanRuntimeFunctions.insert( 1379 DFSanMemTransferCallbackFn.getCallee()->stripPointerCasts()); 1380 DFSanRuntimeFunctions.insert( 1381 DFSanCmpCallbackFn.getCallee()->stripPointerCasts()); 1382 DFSanRuntimeFunctions.insert( 1383 DFSanChainOriginFn.getCallee()->stripPointerCasts()); 1384 DFSanRuntimeFunctions.insert( 1385 DFSanMemOriginTransferFn.getCallee()->stripPointerCasts()); 1386 DFSanRuntimeFunctions.insert( 1387 DFSanMaybeStoreOriginFn.getCallee()->stripPointerCasts()); 1388 } 1389 1390 // Initializes event callback functions and declare them in the module 1391 void DataFlowSanitizer::initializeCallbackFunctions(Module &M) { 1392 DFSanLoadCallbackFn = Mod->getOrInsertFunction("__dfsan_load_callback", 1393 DFSanLoadStoreCallbackFnTy); 1394 DFSanStoreCallbackFn = Mod->getOrInsertFunction("__dfsan_store_callback", 1395 DFSanLoadStoreCallbackFnTy); 1396 DFSanMemTransferCallbackFn = Mod->getOrInsertFunction( 1397 "__dfsan_mem_transfer_callback", DFSanMemTransferCallbackFnTy); 1398 DFSanCmpCallbackFn = 1399 Mod->getOrInsertFunction("__dfsan_cmp_callback", DFSanCmpCallbackFnTy); 1400 } 1401 1402 void DataFlowSanitizer::injectMetadataGlobals(Module &M) { 1403 // These variables can be used: 1404 // - by the runtime (to discover what the shadow width was, during 1405 // compilation) 1406 // - in testing (to avoid hardcoding the shadow width and type but instead 1407 // extract them by pattern matching) 1408 Type *IntTy = Type::getInt32Ty(*Ctx); 1409 (void)Mod->getOrInsertGlobal("__dfsan_shadow_width_bits", IntTy, [&] { 1410 return new GlobalVariable( 1411 M, IntTy, /*isConstant=*/true, GlobalValue::WeakODRLinkage, 1412 ConstantInt::get(IntTy, ShadowWidthBits), "__dfsan_shadow_width_bits"); 1413 }); 1414 (void)Mod->getOrInsertGlobal("__dfsan_shadow_width_bytes", IntTy, [&] { 1415 return new GlobalVariable(M, IntTy, /*isConstant=*/true, 1416 GlobalValue::WeakODRLinkage, 1417 ConstantInt::get(IntTy, ShadowWidthBytes), 1418 "__dfsan_shadow_width_bytes"); 1419 }); 1420 } 1421 1422 bool DataFlowSanitizer::runImpl(Module &M) { 1423 init(M); 1424 1425 if (ABIList.isIn(M, "skip")) 1426 return false; 1427 1428 const unsigned InitialGlobalSize = M.global_size(); 1429 const unsigned InitialModuleSize = M.size(); 1430 1431 bool Changed = false; 1432 1433 auto GetOrInsertGlobal = [this, &Changed](StringRef Name, 1434 Type *Ty) -> Constant * { 1435 Constant *C = Mod->getOrInsertGlobal(Name, Ty); 1436 if (GlobalVariable *G = dyn_cast<GlobalVariable>(C)) { 1437 Changed |= G->getThreadLocalMode() != GlobalVariable::InitialExecTLSModel; 1438 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel); 1439 } 1440 return C; 1441 }; 1442 1443 // These globals must be kept in sync with the ones in dfsan.cpp. 1444 ArgTLS = 1445 GetOrInsertGlobal("__dfsan_arg_tls", 1446 ArrayType::get(Type::getInt64Ty(*Ctx), ArgTLSSize / 8)); 1447 RetvalTLS = GetOrInsertGlobal( 1448 "__dfsan_retval_tls", 1449 ArrayType::get(Type::getInt64Ty(*Ctx), RetvalTLSSize / 8)); 1450 ArgOriginTLSTy = ArrayType::get(OriginTy, NumOfElementsInArgOrgTLS); 1451 ArgOriginTLS = GetOrInsertGlobal("__dfsan_arg_origin_tls", ArgOriginTLSTy); 1452 RetvalOriginTLS = GetOrInsertGlobal("__dfsan_retval_origin_tls", OriginTy); 1453 1454 (void)Mod->getOrInsertGlobal("__dfsan_track_origins", OriginTy, [&] { 1455 Changed = true; 1456 return new GlobalVariable( 1457 M, OriginTy, true, GlobalValue::WeakODRLinkage, 1458 ConstantInt::getSigned(OriginTy, shouldTrackOrigins()), 1459 "__dfsan_track_origins"); 1460 }); 1461 1462 injectMetadataGlobals(M); 1463 1464 ExternalShadowMask = 1465 Mod->getOrInsertGlobal(DFSanExternShadowPtrMask, IntptrTy); 1466 1467 initializeCallbackFunctions(M); 1468 initializeRuntimeFunctions(M); 1469 1470 std::vector<Function *> FnsToInstrument; 1471 SmallPtrSet<Function *, 2> FnsWithNativeABI; 1472 for (Function &F : M) 1473 if (!F.isIntrinsic() && !DFSanRuntimeFunctions.contains(&F)) 1474 FnsToInstrument.push_back(&F); 1475 1476 // Give function aliases prefixes when necessary, and build wrappers where the 1477 // instrumentedness is inconsistent. 1478 for (Module::alias_iterator AI = M.alias_begin(), AE = M.alias_end(); 1479 AI != AE;) { 1480 GlobalAlias *GA = &*AI; 1481 ++AI; 1482 // Don't stop on weak. We assume people aren't playing games with the 1483 // instrumentedness of overridden weak aliases. 1484 auto *F = dyn_cast<Function>(GA->getBaseObject()); 1485 if (!F) 1486 continue; 1487 1488 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F); 1489 if (GAInst && FInst) { 1490 addGlobalNamePrefix(GA); 1491 } else if (GAInst != FInst) { 1492 // Non-instrumented alias of an instrumented function, or vice versa. 1493 // Replace the alias with a native-ABI wrapper of the aliasee. The pass 1494 // below will take care of instrumenting it. 1495 Function *NewF = 1496 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType()); 1497 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType())); 1498 NewF->takeName(GA); 1499 GA->eraseFromParent(); 1500 FnsToInstrument.push_back(NewF); 1501 } 1502 } 1503 1504 ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly) 1505 .addAttribute(Attribute::ReadNone); 1506 1507 // First, change the ABI of every function in the module. ABI-listed 1508 // functions keep their original ABI and get a wrapper function. 1509 for (std::vector<Function *>::iterator FI = FnsToInstrument.begin(), 1510 FE = FnsToInstrument.end(); 1511 FI != FE; ++FI) { 1512 Function &F = **FI; 1513 FunctionType *FT = F.getFunctionType(); 1514 1515 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() && 1516 FT->getReturnType()->isVoidTy()); 1517 1518 if (isInstrumented(&F)) { 1519 // Instrumented functions get a 'dfs$' prefix. This allows us to more 1520 // easily identify cases of mismatching ABIs. 1521 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) { 1522 FunctionType *NewFT = getArgsFunctionType(FT); 1523 Function *NewF = Function::Create(NewFT, F.getLinkage(), 1524 F.getAddressSpace(), "", &M); 1525 NewF->copyAttributesFrom(&F); 1526 NewF->removeAttributes( 1527 AttributeList::ReturnIndex, 1528 AttributeFuncs::typeIncompatible(NewFT->getReturnType())); 1529 for (Function::arg_iterator FArg = F.arg_begin(), 1530 NewFArg = NewF->arg_begin(), 1531 FArgEnd = F.arg_end(); 1532 FArg != FArgEnd; ++FArg, ++NewFArg) { 1533 FArg->replaceAllUsesWith(&*NewFArg); 1534 } 1535 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList()); 1536 1537 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end(); 1538 UI != UE;) { 1539 BlockAddress *BA = dyn_cast<BlockAddress>(*UI); 1540 ++UI; 1541 if (BA) { 1542 BA->replaceAllUsesWith( 1543 BlockAddress::get(NewF, BA->getBasicBlock())); 1544 delete BA; 1545 } 1546 } 1547 F.replaceAllUsesWith( 1548 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT))); 1549 NewF->takeName(&F); 1550 F.eraseFromParent(); 1551 *FI = NewF; 1552 addGlobalNamePrefix(NewF); 1553 } else { 1554 addGlobalNamePrefix(&F); 1555 } 1556 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) { 1557 // Build a wrapper function for F. The wrapper simply calls F, and is 1558 // added to FnsToInstrument so that any instrumentation according to its 1559 // WrapperKind is done in the second pass below. 1560 FunctionType *NewFT = 1561 getInstrumentedABI() == IA_Args ? getArgsFunctionType(FT) : FT; 1562 1563 // If the function being wrapped has local linkage, then preserve the 1564 // function's linkage in the wrapper function. 1565 GlobalValue::LinkageTypes WrapperLinkage = 1566 F.hasLocalLinkage() ? F.getLinkage() 1567 : GlobalValue::LinkOnceODRLinkage; 1568 1569 Function *NewF = buildWrapperFunction( 1570 &F, 1571 (shouldTrackOrigins() ? std::string("dfso$") : std::string("dfsw$")) + 1572 std::string(F.getName()), 1573 WrapperLinkage, NewFT); 1574 if (getInstrumentedABI() == IA_TLS) 1575 NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs); 1576 1577 Value *WrappedFnCst = 1578 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)); 1579 F.replaceAllUsesWith(WrappedFnCst); 1580 1581 UnwrappedFnMap[WrappedFnCst] = &F; 1582 *FI = NewF; 1583 1584 if (!F.isDeclaration()) { 1585 // This function is probably defining an interposition of an 1586 // uninstrumented function and hence needs to keep the original ABI. 1587 // But any functions it may call need to use the instrumented ABI, so 1588 // we instrument it in a mode which preserves the original ABI. 1589 FnsWithNativeABI.insert(&F); 1590 1591 // This code needs to rebuild the iterators, as they may be invalidated 1592 // by the push_back, taking care that the new range does not include 1593 // any functions added by this code. 1594 size_t N = FI - FnsToInstrument.begin(), 1595 Count = FE - FnsToInstrument.begin(); 1596 FnsToInstrument.push_back(&F); 1597 FI = FnsToInstrument.begin() + N; 1598 FE = FnsToInstrument.begin() + Count; 1599 } 1600 // Hopefully, nobody will try to indirectly call a vararg 1601 // function... yet. 1602 } else if (FT->isVarArg()) { 1603 UnwrappedFnMap[&F] = &F; 1604 *FI = nullptr; 1605 } 1606 } 1607 1608 for (Function *F : FnsToInstrument) { 1609 if (!F || F->isDeclaration()) 1610 continue; 1611 1612 removeUnreachableBlocks(*F); 1613 1614 DFSanFunction DFSF(*this, F, FnsWithNativeABI.count(F)); 1615 1616 // DFSanVisitor may create new basic blocks, which confuses df_iterator. 1617 // Build a copy of the list before iterating over it. 1618 SmallVector<BasicBlock *, 4> BBList(depth_first(&F->getEntryBlock())); 1619 1620 for (BasicBlock *BB : BBList) { 1621 Instruction *Inst = &BB->front(); 1622 while (true) { 1623 // DFSanVisitor may split the current basic block, changing the current 1624 // instruction's next pointer and moving the next instruction to the 1625 // tail block from which we should continue. 1626 Instruction *Next = Inst->getNextNode(); 1627 // DFSanVisitor may delete Inst, so keep track of whether it was a 1628 // terminator. 1629 bool IsTerminator = Inst->isTerminator(); 1630 if (!DFSF.SkipInsts.count(Inst)) 1631 DFSanVisitor(DFSF).visit(Inst); 1632 if (IsTerminator) 1633 break; 1634 Inst = Next; 1635 } 1636 } 1637 1638 // We will not necessarily be able to compute the shadow for every phi node 1639 // until we have visited every block. Therefore, the code that handles phi 1640 // nodes adds them to the PHIFixups list so that they can be properly 1641 // handled here. 1642 for (DFSanFunction::PHIFixupElement &P : DFSF.PHIFixups) { 1643 for (unsigned Val = 0, N = P.Phi->getNumIncomingValues(); Val != N; 1644 ++Val) { 1645 P.ShadowPhi->setIncomingValue( 1646 Val, DFSF.getShadow(P.Phi->getIncomingValue(Val))); 1647 if (P.OriginPhi) 1648 P.OriginPhi->setIncomingValue( 1649 Val, DFSF.getOrigin(P.Phi->getIncomingValue(Val))); 1650 } 1651 } 1652 1653 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy 1654 // places (i.e. instructions in basic blocks we haven't even begun visiting 1655 // yet). To make our life easier, do this work in a pass after the main 1656 // instrumentation. 1657 if (ClDebugNonzeroLabels) { 1658 for (Value *V : DFSF.NonZeroChecks) { 1659 Instruction *Pos; 1660 if (Instruction *I = dyn_cast<Instruction>(V)) 1661 Pos = I->getNextNode(); 1662 else 1663 Pos = &DFSF.F->getEntryBlock().front(); 1664 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos)) 1665 Pos = Pos->getNextNode(); 1666 IRBuilder<> IRB(Pos); 1667 Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(V, Pos); 1668 Value *Ne = 1669 IRB.CreateICmpNE(PrimitiveShadow, DFSF.DFS.ZeroPrimitiveShadow); 1670 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen( 1671 Ne, Pos, /*Unreachable=*/false, ColdCallWeights)); 1672 IRBuilder<> ThenIRB(BI); 1673 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {}); 1674 } 1675 } 1676 } 1677 1678 return Changed || !FnsToInstrument.empty() || 1679 M.global_size() != InitialGlobalSize || M.size() != InitialModuleSize; 1680 } 1681 1682 Value *DFSanFunction::getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB) { 1683 Value *Base = IRB.CreatePointerCast(DFS.ArgTLS, DFS.IntptrTy); 1684 if (ArgOffset) 1685 Base = IRB.CreateAdd(Base, ConstantInt::get(DFS.IntptrTy, ArgOffset)); 1686 return IRB.CreateIntToPtr(Base, PointerType::get(DFS.getShadowTy(T), 0), 1687 "_dfsarg"); 1688 } 1689 1690 Value *DFSanFunction::getRetvalTLS(Type *T, IRBuilder<> &IRB) { 1691 return IRB.CreatePointerCast( 1692 DFS.RetvalTLS, PointerType::get(DFS.getShadowTy(T), 0), "_dfsret"); 1693 } 1694 1695 Value *DFSanFunction::getRetvalOriginTLS() { return DFS.RetvalOriginTLS; } 1696 1697 Value *DFSanFunction::getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB) { 1698 return IRB.CreateConstGEP2_64(DFS.ArgOriginTLSTy, DFS.ArgOriginTLS, 0, ArgNo, 1699 "_dfsarg_o"); 1700 } 1701 1702 Value *DFSanFunction::getOrigin(Value *V) { 1703 assert(DFS.shouldTrackOrigins()); 1704 if (!isa<Argument>(V) && !isa<Instruction>(V)) 1705 return DFS.ZeroOrigin; 1706 Value *&Origin = ValOriginMap[V]; 1707 if (!Origin) { 1708 if (Argument *A = dyn_cast<Argument>(V)) { 1709 if (IsNativeABI) 1710 return DFS.ZeroOrigin; 1711 switch (IA) { 1712 case DataFlowSanitizer::IA_TLS: { 1713 if (A->getArgNo() < DFS.NumOfElementsInArgOrgTLS) { 1714 Instruction *ArgOriginTLSPos = &*F->getEntryBlock().begin(); 1715 IRBuilder<> IRB(ArgOriginTLSPos); 1716 Value *ArgOriginPtr = getArgOriginTLS(A->getArgNo(), IRB); 1717 Origin = IRB.CreateLoad(DFS.OriginTy, ArgOriginPtr); 1718 } else { 1719 // Overflow 1720 Origin = DFS.ZeroOrigin; 1721 } 1722 break; 1723 } 1724 case DataFlowSanitizer::IA_Args: { 1725 Origin = DFS.ZeroOrigin; 1726 break; 1727 } 1728 } 1729 } else { 1730 Origin = DFS.ZeroOrigin; 1731 } 1732 } 1733 return Origin; 1734 } 1735 1736 void DFSanFunction::setOrigin(Instruction *I, Value *Origin) { 1737 if (!DFS.shouldTrackOrigins()) 1738 return; 1739 assert(!ValOriginMap.count(I)); 1740 assert(Origin->getType() == DFS.OriginTy); 1741 ValOriginMap[I] = Origin; 1742 } 1743 1744 Value *DFSanFunction::getShadowForTLSArgument(Argument *A) { 1745 unsigned ArgOffset = 0; 1746 const DataLayout &DL = F->getParent()->getDataLayout(); 1747 for (auto &FArg : F->args()) { 1748 if (!FArg.getType()->isSized()) { 1749 if (A == &FArg) 1750 break; 1751 continue; 1752 } 1753 1754 unsigned Size = DL.getTypeAllocSize(DFS.getShadowTy(&FArg)); 1755 if (A != &FArg) { 1756 ArgOffset += alignTo(Size, ShadowTLSAlignment); 1757 if (ArgOffset > ArgTLSSize) 1758 break; // ArgTLS overflows, uses a zero shadow. 1759 continue; 1760 } 1761 1762 if (ArgOffset + Size > ArgTLSSize) 1763 break; // ArgTLS overflows, uses a zero shadow. 1764 1765 Instruction *ArgTLSPos = &*F->getEntryBlock().begin(); 1766 IRBuilder<> IRB(ArgTLSPos); 1767 Value *ArgShadowPtr = getArgTLS(FArg.getType(), ArgOffset, IRB); 1768 return IRB.CreateAlignedLoad(DFS.getShadowTy(&FArg), ArgShadowPtr, 1769 ShadowTLSAlignment); 1770 } 1771 1772 return DFS.getZeroShadow(A); 1773 } 1774 1775 Value *DFSanFunction::getShadow(Value *V) { 1776 if (!isa<Argument>(V) && !isa<Instruction>(V)) 1777 return DFS.getZeroShadow(V); 1778 Value *&Shadow = ValShadowMap[V]; 1779 if (!Shadow) { 1780 if (Argument *A = dyn_cast<Argument>(V)) { 1781 if (IsNativeABI) 1782 return DFS.getZeroShadow(V); 1783 switch (IA) { 1784 case DataFlowSanitizer::IA_TLS: { 1785 Shadow = getShadowForTLSArgument(A); 1786 break; 1787 } 1788 case DataFlowSanitizer::IA_Args: { 1789 unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2; 1790 Function::arg_iterator Arg = F->arg_begin(); 1791 std::advance(Arg, ArgIdx); 1792 Shadow = &*Arg; 1793 assert(Shadow->getType() == DFS.PrimitiveShadowTy); 1794 break; 1795 } 1796 } 1797 NonZeroChecks.push_back(Shadow); 1798 } else { 1799 Shadow = DFS.getZeroShadow(V); 1800 } 1801 } 1802 return Shadow; 1803 } 1804 1805 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) { 1806 assert(!ValShadowMap.count(I)); 1807 assert(DFS.shouldTrackFieldsAndIndices() || 1808 Shadow->getType() == DFS.PrimitiveShadowTy); 1809 ValShadowMap[I] = Shadow; 1810 } 1811 1812 Value *DataFlowSanitizer::getShadowOffset(Value *Addr, IRBuilder<> &IRB) { 1813 // Returns Addr & shadow_mask 1814 assert(Addr != RetvalTLS && "Reinstrumenting?"); 1815 Value *ShadowPtrMaskValue; 1816 if (DFSanRuntimeShadowMask) 1817 ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask); 1818 else 1819 ShadowPtrMaskValue = ShadowPtrMask; 1820 return IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), 1821 IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy)); 1822 } 1823 1824 std::pair<Value *, Value *> 1825 DataFlowSanitizer::getShadowOriginAddress(Value *Addr, Align InstAlignment, 1826 Instruction *Pos) { 1827 // Returns ((Addr & shadow_mask) + origin_base) & ~4UL 1828 IRBuilder<> IRB(Pos); 1829 Value *ShadowOffset = getShadowOffset(Addr, IRB); 1830 Value *ShadowPtr = getShadowAddress(Addr, Pos, ShadowOffset); 1831 Value *OriginPtr = nullptr; 1832 if (shouldTrackOrigins()) { 1833 Value *OriginLong = IRB.CreateAdd(ShadowOffset, OriginBase); 1834 const Align Alignment = llvm::assumeAligned(InstAlignment.value()); 1835 // When alignment is >= 4, Addr must be aligned to 4, otherwise it is UB. 1836 // So Mask is unnecessary. 1837 if (Alignment < MinOriginAlignment) { 1838 uint64_t Mask = MinOriginAlignment.value() - 1; 1839 OriginLong = IRB.CreateAnd(OriginLong, ConstantInt::get(IntptrTy, ~Mask)); 1840 } 1841 OriginPtr = IRB.CreateIntToPtr(OriginLong, OriginPtrTy); 1842 } 1843 return {ShadowPtr, OriginPtr}; 1844 } 1845 1846 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos, 1847 Value *ShadowOffset) { 1848 IRBuilder<> IRB(Pos); 1849 1850 if (!ShadowPtrMul->isOne()) 1851 ShadowOffset = IRB.CreateMul(ShadowOffset, ShadowPtrMul); 1852 1853 return IRB.CreateIntToPtr(ShadowOffset, PrimitiveShadowPtrTy); 1854 } 1855 1856 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) { 1857 // Returns (Addr & shadow_mask) x 2 1858 IRBuilder<> IRB(Pos); 1859 Value *ShadowOffset = getShadowOffset(Addr, IRB); 1860 return getShadowAddress(Addr, Pos, ShadowOffset); 1861 } 1862 1863 Value *DFSanFunction::combineShadowsThenConvert(Type *T, Value *V1, Value *V2, 1864 Instruction *Pos) { 1865 Value *PrimitiveValue = combineShadows(V1, V2, Pos); 1866 return expandFromPrimitiveShadow(T, PrimitiveValue, Pos); 1867 } 1868 1869 // Generates IR to compute the union of the two given shadows, inserting it 1870 // before Pos. The combined value is with primitive type. 1871 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) { 1872 if (DFS.isZeroShadow(V1)) 1873 return collapseToPrimitiveShadow(V2, Pos); 1874 if (DFS.isZeroShadow(V2)) 1875 return collapseToPrimitiveShadow(V1, Pos); 1876 if (V1 == V2) 1877 return collapseToPrimitiveShadow(V1, Pos); 1878 1879 auto V1Elems = ShadowElements.find(V1); 1880 auto V2Elems = ShadowElements.find(V2); 1881 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) { 1882 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(), 1883 V2Elems->second.begin(), V2Elems->second.end())) { 1884 return collapseToPrimitiveShadow(V1, Pos); 1885 } 1886 if (std::includes(V2Elems->second.begin(), V2Elems->second.end(), 1887 V1Elems->second.begin(), V1Elems->second.end())) { 1888 return collapseToPrimitiveShadow(V2, Pos); 1889 } 1890 } else if (V1Elems != ShadowElements.end()) { 1891 if (V1Elems->second.count(V2)) 1892 return collapseToPrimitiveShadow(V1, Pos); 1893 } else if (V2Elems != ShadowElements.end()) { 1894 if (V2Elems->second.count(V1)) 1895 return collapseToPrimitiveShadow(V2, Pos); 1896 } 1897 1898 auto Key = std::make_pair(V1, V2); 1899 if (V1 > V2) 1900 std::swap(Key.first, Key.second); 1901 CachedShadow &CCS = CachedShadows[Key]; 1902 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent())) 1903 return CCS.Shadow; 1904 1905 // Converts inputs shadows to shadows with primitive types. 1906 Value *PV1 = collapseToPrimitiveShadow(V1, Pos); 1907 Value *PV2 = collapseToPrimitiveShadow(V2, Pos); 1908 1909 IRBuilder<> IRB(Pos); 1910 if (DFS.hasFastLabelsEnabled()) { 1911 CCS.Block = Pos->getParent(); 1912 CCS.Shadow = IRB.CreateOr(PV1, PV2); 1913 } else if (AvoidNewBlocks) { 1914 CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {PV1, PV2}); 1915 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt); 1916 Call->addParamAttr(0, Attribute::ZExt); 1917 Call->addParamAttr(1, Attribute::ZExt); 1918 1919 CCS.Block = Pos->getParent(); 1920 CCS.Shadow = Call; 1921 } else { 1922 BasicBlock *Head = Pos->getParent(); 1923 Value *Ne = IRB.CreateICmpNE(PV1, PV2); 1924 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen( 1925 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT)); 1926 IRBuilder<> ThenIRB(BI); 1927 CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {PV1, PV2}); 1928 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt); 1929 Call->addParamAttr(0, Attribute::ZExt); 1930 Call->addParamAttr(1, Attribute::ZExt); 1931 1932 BasicBlock *Tail = BI->getSuccessor(0); 1933 PHINode *Phi = 1934 PHINode::Create(DFS.PrimitiveShadowTy, 2, "", &Tail->front()); 1935 Phi->addIncoming(Call, Call->getParent()); 1936 Phi->addIncoming(PV1, Head); 1937 1938 CCS.Block = Tail; 1939 CCS.Shadow = Phi; 1940 } 1941 1942 std::set<Value *> UnionElems; 1943 if (V1Elems != ShadowElements.end()) { 1944 UnionElems = V1Elems->second; 1945 } else { 1946 UnionElems.insert(V1); 1947 } 1948 if (V2Elems != ShadowElements.end()) { 1949 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end()); 1950 } else { 1951 UnionElems.insert(V2); 1952 } 1953 ShadowElements[CCS.Shadow] = std::move(UnionElems); 1954 1955 return CCS.Shadow; 1956 } 1957 1958 // A convenience function which folds the shadows of each of the operands 1959 // of the provided instruction Inst, inserting the IR before Inst. Returns 1960 // the computed union Value. 1961 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) { 1962 if (Inst->getNumOperands() == 0) 1963 return DFS.getZeroShadow(Inst); 1964 1965 Value *Shadow = getShadow(Inst->getOperand(0)); 1966 for (unsigned I = 1, N = Inst->getNumOperands(); I < N; ++I) 1967 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(I)), Inst); 1968 1969 return expandFromPrimitiveShadow(Inst->getType(), Shadow, Inst); 1970 } 1971 1972 void DFSanVisitor::visitInstOperands(Instruction &I) { 1973 Value *CombinedShadow = DFSF.combineOperandShadows(&I); 1974 DFSF.setShadow(&I, CombinedShadow); 1975 visitInstOperandOrigins(I); 1976 } 1977 1978 Value *DFSanFunction::combineOrigins(const std::vector<Value *> &Shadows, 1979 const std::vector<Value *> &Origins, 1980 Instruction *Pos, ConstantInt *Zero) { 1981 assert(Shadows.size() == Origins.size()); 1982 size_t Size = Origins.size(); 1983 if (Size == 0) 1984 return DFS.ZeroOrigin; 1985 Value *Origin = nullptr; 1986 if (!Zero) 1987 Zero = DFS.ZeroPrimitiveShadow; 1988 for (size_t I = 0; I != Size; ++I) { 1989 Value *OpOrigin = Origins[I]; 1990 Constant *ConstOpOrigin = dyn_cast<Constant>(OpOrigin); 1991 if (ConstOpOrigin && ConstOpOrigin->isNullValue()) 1992 continue; 1993 if (!Origin) { 1994 Origin = OpOrigin; 1995 continue; 1996 } 1997 Value *OpShadow = Shadows[I]; 1998 Value *PrimitiveShadow = collapseToPrimitiveShadow(OpShadow, Pos); 1999 IRBuilder<> IRB(Pos); 2000 Value *Cond = IRB.CreateICmpNE(PrimitiveShadow, Zero); 2001 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin); 2002 } 2003 return Origin ? Origin : DFS.ZeroOrigin; 2004 } 2005 2006 Value *DFSanFunction::combineOperandOrigins(Instruction *Inst) { 2007 size_t Size = Inst->getNumOperands(); 2008 std::vector<Value *> Shadows(Size); 2009 std::vector<Value *> Origins(Size); 2010 for (unsigned I = 0; I != Size; ++I) { 2011 Shadows[I] = getShadow(Inst->getOperand(I)); 2012 Origins[I] = getOrigin(Inst->getOperand(I)); 2013 } 2014 return combineOrigins(Shadows, Origins, Inst); 2015 } 2016 2017 void DFSanVisitor::visitInstOperandOrigins(Instruction &I) { 2018 if (!DFSF.DFS.shouldTrackOrigins()) 2019 return; 2020 Value *CombinedOrigin = DFSF.combineOperandOrigins(&I); 2021 DFSF.setOrigin(&I, CombinedOrigin); 2022 } 2023 2024 Align DFSanFunction::getShadowAlign(Align InstAlignment) { 2025 const Align Alignment = ClPreserveAlignment ? InstAlignment : Align(1); 2026 return Align(Alignment.value() * DFS.ShadowWidthBytes); 2027 } 2028 2029 Align DFSanFunction::getOriginAlign(Align InstAlignment) { 2030 const Align Alignment = llvm::assumeAligned(InstAlignment.value()); 2031 return Align(std::max(MinOriginAlignment, Alignment)); 2032 } 2033 2034 bool DFSanFunction::useCallbackLoadLabelAndOrigin(uint64_t Size, 2035 Align InstAlignment) { 2036 assert(Size != 0); 2037 // * if Size == 1, it is sufficient to load its origin aligned at 4. 2038 // * if Size == 2, we assume most cases Addr % 2 == 0, so it is sufficient to 2039 // load its origin aligned at 4. If not, although origins may be lost, it 2040 // should not happen very often. 2041 // * if align >= 4, Addr must be aligned to 4, otherwise it is UB. When 2042 // Size % 4 == 0, it is more efficient to load origins without callbacks. 2043 // * Otherwise we use __dfsan_load_label_and_origin. 2044 // This should ensure that common cases run efficiently. 2045 if (Size <= 2) 2046 return false; 2047 2048 const Align Alignment = llvm::assumeAligned(InstAlignment.value()); 2049 return Alignment < MinOriginAlignment || !DFS.hasLoadSizeForFastPath(Size); 2050 } 2051 2052 std::pair<Value *, Value *> DFSanFunction::loadFast16ShadowFast( 2053 Value *ShadowAddr, Value *OriginAddr, uint64_t Size, Align ShadowAlign, 2054 Align OriginAlign, Value *FirstOrigin, Instruction *Pos) { 2055 const bool ShouldTrackOrigins = DFS.shouldTrackOrigins(); 2056 const uint64_t ShadowSize = Size * DFS.ShadowWidthBytes; 2057 2058 assert(Size >= 4 && "Not large enough load size for fast path!"); 2059 2060 // Used for origin tracking. 2061 std::vector<Value *> Shadows; 2062 std::vector<Value *> Origins; 2063 2064 // Load instructions in LLVM can have arbitrary byte sizes (e.g., 3, 12, 20) 2065 // but this function is only used in a subset of cases that make it possible 2066 // to optimize the instrumentation. 2067 // 2068 // Specifically, when the shadow size in bytes (i.e., loaded bytes x shadow 2069 // per byte) is either: 2070 // - a multiple of 8 (common) 2071 // - equal to 4 (only for load32 in fast-8 mode) 2072 // 2073 // For the second case, we can fit the wide shadow in a 32-bit integer. In all 2074 // other cases, we use a 64-bit integer to hold the wide shadow. 2075 Type *WideShadowTy = 2076 ShadowSize == 4 ? Type::getInt32Ty(*DFS.Ctx) : Type::getInt64Ty(*DFS.Ctx); 2077 2078 IRBuilder<> IRB(Pos); 2079 Value *WideAddr = IRB.CreateBitCast(ShadowAddr, WideShadowTy->getPointerTo()); 2080 Value *CombinedWideShadow = 2081 IRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign); 2082 2083 if (ShouldTrackOrigins) { 2084 Shadows.push_back(CombinedWideShadow); 2085 Origins.push_back(FirstOrigin); 2086 } 2087 2088 // First OR all the WideShadows (i.e., 64bit or 32bit shadow chunks) linearly; 2089 // then OR individual shadows within the combined WideShadow by binary ORing. 2090 // This is fewer instructions than ORing shadows individually, since it 2091 // needs logN shift/or instructions (N being the bytes of the combined wide 2092 // shadow). 2093 unsigned WideShadowBitWidth = WideShadowTy->getIntegerBitWidth(); 2094 const uint64_t BytesPerWideShadow = WideShadowBitWidth / DFS.ShadowWidthBits; 2095 2096 for (uint64_t ByteOfs = BytesPerWideShadow; ByteOfs < Size; 2097 ByteOfs += BytesPerWideShadow) { 2098 WideAddr = IRB.CreateGEP(WideShadowTy, WideAddr, 2099 ConstantInt::get(DFS.IntptrTy, 1)); 2100 Value *NextWideShadow = 2101 IRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign); 2102 CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, NextWideShadow); 2103 if (ShouldTrackOrigins) { 2104 Shadows.push_back(NextWideShadow); 2105 OriginAddr = IRB.CreateGEP(DFS.OriginTy, OriginAddr, 2106 ConstantInt::get(DFS.IntptrTy, 1)); 2107 Origins.push_back( 2108 IRB.CreateAlignedLoad(DFS.OriginTy, OriginAddr, OriginAlign)); 2109 } 2110 } 2111 for (unsigned Width = WideShadowBitWidth / 2; Width >= DFS.ShadowWidthBits; 2112 Width >>= 1) { 2113 Value *ShrShadow = IRB.CreateLShr(CombinedWideShadow, Width); 2114 CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, ShrShadow); 2115 } 2116 return {IRB.CreateTrunc(CombinedWideShadow, DFS.PrimitiveShadowTy), 2117 ShouldTrackOrigins 2118 ? combineOrigins(Shadows, Origins, Pos, 2119 ConstantInt::getSigned(IRB.getInt64Ty(), 0)) 2120 : DFS.ZeroOrigin}; 2121 } 2122 2123 Value *DFSanFunction::loadLegacyShadowFast(Value *ShadowAddr, uint64_t Size, 2124 Align ShadowAlign, 2125 Instruction *Pos) { 2126 // Fast path for the common case where each byte has identical shadow: load 2127 // shadow 64 (or 32) bits at a time, fall out to a __dfsan_union_load call if 2128 // any shadow is non-equal. 2129 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F); 2130 IRBuilder<> FallbackIRB(FallbackBB); 2131 CallInst *FallbackCall = FallbackIRB.CreateCall( 2132 DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)}); 2133 FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt); 2134 2135 const uint64_t ShadowSize = Size * DFS.ShadowWidthBytes; 2136 assert(Size >= 4 && "Not large enough load size for fast path!"); 2137 2138 // Same as in loadFast16AShadowsFast. In the case of load32, we can fit the 2139 // wide shadow in a 32-bit integer instead. 2140 Type *WideShadowTy = 2141 ShadowSize == 4 ? Type::getInt32Ty(*DFS.Ctx) : Type::getInt64Ty(*DFS.Ctx); 2142 2143 // Compare each of the shadows stored in the loaded 64 bits to each other, 2144 // by computing (WideShadow rotl ShadowWidthBits) == WideShadow. 2145 IRBuilder<> IRB(Pos); 2146 unsigned WideShadowBitWidth = WideShadowTy->getIntegerBitWidth(); 2147 Value *WideAddr = IRB.CreateBitCast(ShadowAddr, WideShadowTy->getPointerTo()); 2148 Value *WideShadow = 2149 IRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign); 2150 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.PrimitiveShadowTy); 2151 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidthBits); 2152 Value *ShrShadow = 2153 IRB.CreateLShr(WideShadow, WideShadowBitWidth - DFS.ShadowWidthBits); 2154 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow); 2155 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow); 2156 2157 BasicBlock *Head = Pos->getParent(); 2158 BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator()); 2159 2160 if (DomTreeNode *OldNode = DT.getNode(Head)) { 2161 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end()); 2162 2163 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head); 2164 for (auto *Child : Children) 2165 DT.changeImmediateDominator(Child, NewNode); 2166 } 2167 2168 // In the following code LastBr will refer to the previous basic block's 2169 // conditional branch instruction, whose true successor is fixed up to point 2170 // to the next block during the loop below or to the tail after the final 2171 // iteration. 2172 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq); 2173 ReplaceInstWithInst(Head->getTerminator(), LastBr); 2174 DT.addNewBlock(FallbackBB, Head); 2175 2176 const uint64_t BytesPerWideShadow = WideShadowBitWidth / DFS.ShadowWidthBits; 2177 2178 for (uint64_t ByteOfs = BytesPerWideShadow; ByteOfs < Size; 2179 ByteOfs += BytesPerWideShadow) { 2180 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F); 2181 DT.addNewBlock(NextBB, LastBr->getParent()); 2182 IRBuilder<> NextIRB(NextBB); 2183 WideAddr = NextIRB.CreateGEP(WideShadowTy, WideAddr, 2184 ConstantInt::get(DFS.IntptrTy, 1)); 2185 Value *NextWideShadow = 2186 NextIRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign); 2187 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow); 2188 LastBr->setSuccessor(0, NextBB); 2189 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB); 2190 } 2191 2192 LastBr->setSuccessor(0, Tail); 2193 FallbackIRB.CreateBr(Tail); 2194 PHINode *Shadow = 2195 PHINode::Create(DFS.PrimitiveShadowTy, 2, "", &Tail->front()); 2196 Shadow->addIncoming(FallbackCall, FallbackBB); 2197 Shadow->addIncoming(TruncShadow, LastBr->getParent()); 2198 return Shadow; 2199 } 2200 2201 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where 2202 // Addr has alignment Align, and take the union of each of those shadows. The 2203 // returned shadow always has primitive type. 2204 std::pair<Value *, Value *> DFSanFunction::loadShadowOrigin(Value *Addr, 2205 uint64_t Size, 2206 Align InstAlignment, 2207 Instruction *Pos) { 2208 const bool ShouldTrackOrigins = DFS.shouldTrackOrigins(); 2209 2210 // Non-escaped loads. 2211 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) { 2212 const auto SI = AllocaShadowMap.find(AI); 2213 if (SI != AllocaShadowMap.end()) { 2214 IRBuilder<> IRB(Pos); 2215 Value *ShadowLI = IRB.CreateLoad(DFS.PrimitiveShadowTy, SI->second); 2216 const auto OI = AllocaOriginMap.find(AI); 2217 assert(!ShouldTrackOrigins || OI != AllocaOriginMap.end()); 2218 return {ShadowLI, ShouldTrackOrigins 2219 ? IRB.CreateLoad(DFS.OriginTy, OI->second) 2220 : nullptr}; 2221 } 2222 } 2223 2224 // Load from constant addresses. 2225 SmallVector<const Value *, 2> Objs; 2226 getUnderlyingObjects(Addr, Objs); 2227 bool AllConstants = true; 2228 for (const Value *Obj : Objs) { 2229 if (isa<Function>(Obj) || isa<BlockAddress>(Obj)) 2230 continue; 2231 if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant()) 2232 continue; 2233 2234 AllConstants = false; 2235 break; 2236 } 2237 if (AllConstants) 2238 return {DFS.ZeroPrimitiveShadow, 2239 ShouldTrackOrigins ? DFS.ZeroOrigin : nullptr}; 2240 2241 if (Size == 0) 2242 return {DFS.ZeroPrimitiveShadow, 2243 ShouldTrackOrigins ? DFS.ZeroOrigin : nullptr}; 2244 2245 // Use callback to load if this is not an optimizable case for origin 2246 // tracking. 2247 if (ShouldTrackOrigins && 2248 useCallbackLoadLabelAndOrigin(Size, InstAlignment)) { 2249 IRBuilder<> IRB(Pos); 2250 CallInst *Call = 2251 IRB.CreateCall(DFS.DFSanLoadLabelAndOriginFn, 2252 {IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()), 2253 ConstantInt::get(DFS.IntptrTy, Size)}); 2254 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt); 2255 return {IRB.CreateTrunc(IRB.CreateLShr(Call, DFS.OriginWidthBits), 2256 DFS.PrimitiveShadowTy), 2257 IRB.CreateTrunc(Call, DFS.OriginTy)}; 2258 } 2259 2260 // Other cases that support loading shadows or origins in a fast way. 2261 Value *ShadowAddr, *OriginAddr; 2262 std::tie(ShadowAddr, OriginAddr) = 2263 DFS.getShadowOriginAddress(Addr, InstAlignment, Pos); 2264 2265 const Align ShadowAlign = getShadowAlign(InstAlignment); 2266 const Align OriginAlign = getOriginAlign(InstAlignment); 2267 Value *Origin = nullptr; 2268 if (ShouldTrackOrigins) { 2269 IRBuilder<> IRB(Pos); 2270 Origin = IRB.CreateAlignedLoad(DFS.OriginTy, OriginAddr, OriginAlign); 2271 } 2272 2273 // When the byte size is small enough, we can load the shadow directly with 2274 // just a few instructions. 2275 switch (Size) { 2276 case 1: { 2277 LoadInst *LI = new LoadInst(DFS.PrimitiveShadowTy, ShadowAddr, "", Pos); 2278 LI->setAlignment(ShadowAlign); 2279 return {LI, Origin}; 2280 } 2281 case 2: { 2282 IRBuilder<> IRB(Pos); 2283 Value *ShadowAddr1 = IRB.CreateGEP(DFS.PrimitiveShadowTy, ShadowAddr, 2284 ConstantInt::get(DFS.IntptrTy, 1)); 2285 Value *Load = 2286 IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr, ShadowAlign); 2287 Value *Load1 = 2288 IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr1, ShadowAlign); 2289 return {combineShadows(Load, Load1, Pos), Origin}; 2290 } 2291 } 2292 bool HasSizeForFastPath = DFS.hasLoadSizeForFastPath(Size); 2293 bool HasFastLabelsEnabled = DFS.hasFastLabelsEnabled(); 2294 2295 if (HasFastLabelsEnabled && HasSizeForFastPath) 2296 return loadFast16ShadowFast(ShadowAddr, OriginAddr, Size, ShadowAlign, 2297 OriginAlign, Origin, Pos); 2298 2299 if (!AvoidNewBlocks && HasSizeForFastPath) 2300 return {loadLegacyShadowFast(ShadowAddr, Size, ShadowAlign, Pos), Origin}; 2301 2302 IRBuilder<> IRB(Pos); 2303 FunctionCallee &UnionLoadFn = HasFastLabelsEnabled 2304 ? DFS.DFSanUnionLoadFastLabelsFn 2305 : DFS.DFSanUnionLoadFn; 2306 CallInst *FallbackCall = IRB.CreateCall( 2307 UnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)}); 2308 FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt); 2309 return {FallbackCall, Origin}; 2310 } 2311 2312 static AtomicOrdering addAcquireOrdering(AtomicOrdering AO) { 2313 switch (AO) { 2314 case AtomicOrdering::NotAtomic: 2315 return AtomicOrdering::NotAtomic; 2316 case AtomicOrdering::Unordered: 2317 case AtomicOrdering::Monotonic: 2318 case AtomicOrdering::Acquire: 2319 return AtomicOrdering::Acquire; 2320 case AtomicOrdering::Release: 2321 case AtomicOrdering::AcquireRelease: 2322 return AtomicOrdering::AcquireRelease; 2323 case AtomicOrdering::SequentiallyConsistent: 2324 return AtomicOrdering::SequentiallyConsistent; 2325 } 2326 llvm_unreachable("Unknown ordering"); 2327 } 2328 2329 void DFSanVisitor::visitLoadInst(LoadInst &LI) { 2330 auto &DL = LI.getModule()->getDataLayout(); 2331 uint64_t Size = DL.getTypeStoreSize(LI.getType()); 2332 if (Size == 0) { 2333 DFSF.setShadow(&LI, DFSF.DFS.getZeroShadow(&LI)); 2334 DFSF.setOrigin(&LI, DFSF.DFS.ZeroOrigin); 2335 return; 2336 } 2337 2338 // When an application load is atomic, increase atomic ordering between 2339 // atomic application loads and stores to ensure happen-before order; load 2340 // shadow data after application data; store zero shadow data before 2341 // application data. This ensure shadow loads return either labels of the 2342 // initial application data or zeros. 2343 if (LI.isAtomic()) 2344 LI.setOrdering(addAcquireOrdering(LI.getOrdering())); 2345 2346 Instruction *Pos = LI.isAtomic() ? LI.getNextNode() : &LI; 2347 std::vector<Value *> Shadows; 2348 std::vector<Value *> Origins; 2349 Value *PrimitiveShadow, *Origin; 2350 std::tie(PrimitiveShadow, Origin) = 2351 DFSF.loadShadowOrigin(LI.getPointerOperand(), Size, LI.getAlign(), Pos); 2352 const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins(); 2353 if (ShouldTrackOrigins) { 2354 Shadows.push_back(PrimitiveShadow); 2355 Origins.push_back(Origin); 2356 } 2357 if (ClCombinePointerLabelsOnLoad) { 2358 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand()); 2359 PrimitiveShadow = DFSF.combineShadows(PrimitiveShadow, PtrShadow, Pos); 2360 if (ShouldTrackOrigins) { 2361 Shadows.push_back(PtrShadow); 2362 Origins.push_back(DFSF.getOrigin(LI.getPointerOperand())); 2363 } 2364 } 2365 if (!DFSF.DFS.isZeroShadow(PrimitiveShadow)) 2366 DFSF.NonZeroChecks.push_back(PrimitiveShadow); 2367 2368 Value *Shadow = 2369 DFSF.expandFromPrimitiveShadow(LI.getType(), PrimitiveShadow, Pos); 2370 DFSF.setShadow(&LI, Shadow); 2371 2372 if (ShouldTrackOrigins) { 2373 DFSF.setOrigin(&LI, DFSF.combineOrigins(Shadows, Origins, Pos)); 2374 } 2375 2376 if (ClEventCallbacks) { 2377 IRBuilder<> IRB(Pos); 2378 Value *Addr8 = IRB.CreateBitCast(LI.getPointerOperand(), DFSF.DFS.Int8Ptr); 2379 IRB.CreateCall(DFSF.DFS.DFSanLoadCallbackFn, {PrimitiveShadow, Addr8}); 2380 } 2381 } 2382 2383 Value *DFSanFunction::updateOrigin(Value *V, IRBuilder<> &IRB) { 2384 if (!DFS.shouldTrackOrigins()) 2385 return V; 2386 return IRB.CreateCall(DFS.DFSanChainOriginFn, V); 2387 } 2388 2389 Value *DFSanFunction::originToIntptr(IRBuilder<> &IRB, Value *Origin) { 2390 const unsigned OriginSize = DataFlowSanitizer::OriginWidthBytes; 2391 const DataLayout &DL = F->getParent()->getDataLayout(); 2392 unsigned IntptrSize = DL.getTypeStoreSize(DFS.IntptrTy); 2393 if (IntptrSize == OriginSize) 2394 return Origin; 2395 assert(IntptrSize == OriginSize * 2); 2396 Origin = IRB.CreateIntCast(Origin, DFS.IntptrTy, /* isSigned */ false); 2397 return IRB.CreateOr(Origin, IRB.CreateShl(Origin, OriginSize * 8)); 2398 } 2399 2400 void DFSanFunction::paintOrigin(IRBuilder<> &IRB, Value *Origin, 2401 Value *StoreOriginAddr, 2402 uint64_t StoreOriginSize, Align Alignment) { 2403 const unsigned OriginSize = DataFlowSanitizer::OriginWidthBytes; 2404 const DataLayout &DL = F->getParent()->getDataLayout(); 2405 const Align IntptrAlignment = DL.getABITypeAlign(DFS.IntptrTy); 2406 unsigned IntptrSize = DL.getTypeStoreSize(DFS.IntptrTy); 2407 assert(IntptrAlignment >= MinOriginAlignment); 2408 assert(IntptrSize >= OriginSize); 2409 2410 unsigned Ofs = 0; 2411 Align CurrentAlignment = Alignment; 2412 if (Alignment >= IntptrAlignment && IntptrSize > OriginSize) { 2413 Value *IntptrOrigin = originToIntptr(IRB, Origin); 2414 Value *IntptrStoreOriginPtr = IRB.CreatePointerCast( 2415 StoreOriginAddr, PointerType::get(DFS.IntptrTy, 0)); 2416 for (unsigned I = 0; I < StoreOriginSize / IntptrSize; ++I) { 2417 Value *Ptr = 2418 I ? IRB.CreateConstGEP1_32(DFS.IntptrTy, IntptrStoreOriginPtr, I) 2419 : IntptrStoreOriginPtr; 2420 IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment); 2421 Ofs += IntptrSize / OriginSize; 2422 CurrentAlignment = IntptrAlignment; 2423 } 2424 } 2425 2426 for (unsigned I = Ofs; I < (StoreOriginSize + OriginSize - 1) / OriginSize; 2427 ++I) { 2428 Value *GEP = I ? IRB.CreateConstGEP1_32(DFS.OriginTy, StoreOriginAddr, I) 2429 : StoreOriginAddr; 2430 IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment); 2431 CurrentAlignment = MinOriginAlignment; 2432 } 2433 } 2434 2435 Value *DFSanFunction::convertToBool(Value *V, IRBuilder<> &IRB, 2436 const Twine &Name) { 2437 Type *VTy = V->getType(); 2438 assert(VTy->isIntegerTy()); 2439 if (VTy->getIntegerBitWidth() == 1) 2440 // Just converting a bool to a bool, so do nothing. 2441 return V; 2442 return IRB.CreateICmpNE(V, ConstantInt::get(VTy, 0), Name); 2443 } 2444 2445 void DFSanFunction::storeOrigin(Instruction *Pos, Value *Addr, uint64_t Size, 2446 Value *Shadow, Value *Origin, 2447 Value *StoreOriginAddr, Align InstAlignment) { 2448 // Do not write origins for zero shadows because we do not trace origins for 2449 // untainted sinks. 2450 const Align OriginAlignment = getOriginAlign(InstAlignment); 2451 Value *CollapsedShadow = collapseToPrimitiveShadow(Shadow, Pos); 2452 IRBuilder<> IRB(Pos); 2453 if (auto *ConstantShadow = dyn_cast<Constant>(CollapsedShadow)) { 2454 if (!ConstantShadow->isZeroValue()) 2455 paintOrigin(IRB, updateOrigin(Origin, IRB), StoreOriginAddr, Size, 2456 OriginAlignment); 2457 return; 2458 } 2459 2460 if (shouldInstrumentWithCall()) { 2461 IRB.CreateCall(DFS.DFSanMaybeStoreOriginFn, 2462 {CollapsedShadow, 2463 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()), 2464 ConstantInt::get(DFS.IntptrTy, Size), Origin}); 2465 } else { 2466 Value *Cmp = convertToBool(CollapsedShadow, IRB, "_dfscmp"); 2467 Instruction *CheckTerm = SplitBlockAndInsertIfThen( 2468 Cmp, &*IRB.GetInsertPoint(), false, DFS.OriginStoreWeights, &DT); 2469 IRBuilder<> IRBNew(CheckTerm); 2470 paintOrigin(IRBNew, updateOrigin(Origin, IRBNew), StoreOriginAddr, Size, 2471 OriginAlignment); 2472 ++NumOriginStores; 2473 } 2474 } 2475 2476 void DFSanFunction::storeZeroPrimitiveShadow(Value *Addr, uint64_t Size, 2477 Align ShadowAlign, 2478 Instruction *Pos) { 2479 IRBuilder<> IRB(Pos); 2480 IntegerType *ShadowTy = 2481 IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidthBits); 2482 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0); 2483 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos); 2484 Value *ExtShadowAddr = 2485 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy)); 2486 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign); 2487 // Do not write origins for 0 shadows because we do not trace origins for 2488 // untainted sinks. 2489 } 2490 2491 void DFSanFunction::storePrimitiveShadowOrigin(Value *Addr, uint64_t Size, 2492 Align InstAlignment, 2493 Value *PrimitiveShadow, 2494 Value *Origin, 2495 Instruction *Pos) { 2496 const bool ShouldTrackOrigins = DFS.shouldTrackOrigins() && Origin; 2497 2498 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) { 2499 const auto SI = AllocaShadowMap.find(AI); 2500 if (SI != AllocaShadowMap.end()) { 2501 IRBuilder<> IRB(Pos); 2502 IRB.CreateStore(PrimitiveShadow, SI->second); 2503 2504 // Do not write origins for 0 shadows because we do not trace origins for 2505 // untainted sinks. 2506 if (ShouldTrackOrigins && !DFS.isZeroShadow(PrimitiveShadow)) { 2507 const auto OI = AllocaOriginMap.find(AI); 2508 assert(OI != AllocaOriginMap.end() && Origin); 2509 IRB.CreateStore(Origin, OI->second); 2510 } 2511 return; 2512 } 2513 } 2514 2515 const Align ShadowAlign = getShadowAlign(InstAlignment); 2516 if (DFS.isZeroShadow(PrimitiveShadow)) { 2517 storeZeroPrimitiveShadow(Addr, Size, ShadowAlign, Pos); 2518 return; 2519 } 2520 2521 IRBuilder<> IRB(Pos); 2522 Value *ShadowAddr, *OriginAddr; 2523 std::tie(ShadowAddr, OriginAddr) = 2524 DFS.getShadowOriginAddress(Addr, InstAlignment, Pos); 2525 2526 const unsigned ShadowVecSize = 8; 2527 assert(ShadowVecSize * DFS.ShadowWidthBits <= 128 && 2528 "Shadow vector is too large!"); 2529 2530 uint64_t Offset = 0; 2531 uint64_t LeftSize = Size; 2532 if (LeftSize >= ShadowVecSize) { 2533 auto *ShadowVecTy = 2534 FixedVectorType::get(DFS.PrimitiveShadowTy, ShadowVecSize); 2535 Value *ShadowVec = UndefValue::get(ShadowVecTy); 2536 for (unsigned I = 0; I != ShadowVecSize; ++I) { 2537 ShadowVec = IRB.CreateInsertElement( 2538 ShadowVec, PrimitiveShadow, 2539 ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), I)); 2540 } 2541 Value *ShadowVecAddr = 2542 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy)); 2543 do { 2544 Value *CurShadowVecAddr = 2545 IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset); 2546 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign); 2547 LeftSize -= ShadowVecSize; 2548 ++Offset; 2549 } while (LeftSize >= ShadowVecSize); 2550 Offset *= ShadowVecSize; 2551 } 2552 while (LeftSize > 0) { 2553 Value *CurShadowAddr = 2554 IRB.CreateConstGEP1_32(DFS.PrimitiveShadowTy, ShadowAddr, Offset); 2555 IRB.CreateAlignedStore(PrimitiveShadow, CurShadowAddr, ShadowAlign); 2556 --LeftSize; 2557 ++Offset; 2558 } 2559 2560 if (ShouldTrackOrigins) { 2561 storeOrigin(Pos, Addr, Size, PrimitiveShadow, Origin, OriginAddr, 2562 InstAlignment); 2563 } 2564 } 2565 2566 static AtomicOrdering addReleaseOrdering(AtomicOrdering AO) { 2567 switch (AO) { 2568 case AtomicOrdering::NotAtomic: 2569 return AtomicOrdering::NotAtomic; 2570 case AtomicOrdering::Unordered: 2571 case AtomicOrdering::Monotonic: 2572 case AtomicOrdering::Release: 2573 return AtomicOrdering::Release; 2574 case AtomicOrdering::Acquire: 2575 case AtomicOrdering::AcquireRelease: 2576 return AtomicOrdering::AcquireRelease; 2577 case AtomicOrdering::SequentiallyConsistent: 2578 return AtomicOrdering::SequentiallyConsistent; 2579 } 2580 llvm_unreachable("Unknown ordering"); 2581 } 2582 2583 void DFSanVisitor::visitStoreInst(StoreInst &SI) { 2584 auto &DL = SI.getModule()->getDataLayout(); 2585 Value *Val = SI.getValueOperand(); 2586 uint64_t Size = DL.getTypeStoreSize(Val->getType()); 2587 if (Size == 0) 2588 return; 2589 2590 // When an application store is atomic, increase atomic ordering between 2591 // atomic application loads and stores to ensure happen-before order; load 2592 // shadow data after application data; store zero shadow data before 2593 // application data. This ensure shadow loads return either labels of the 2594 // initial application data or zeros. 2595 if (SI.isAtomic()) 2596 SI.setOrdering(addReleaseOrdering(SI.getOrdering())); 2597 2598 const bool ShouldTrackOrigins = 2599 DFSF.DFS.shouldTrackOrigins() && !SI.isAtomic(); 2600 std::vector<Value *> Shadows; 2601 std::vector<Value *> Origins; 2602 2603 Value *Shadow = 2604 SI.isAtomic() ? DFSF.DFS.getZeroShadow(Val) : DFSF.getShadow(Val); 2605 2606 if (ShouldTrackOrigins) { 2607 Shadows.push_back(Shadow); 2608 Origins.push_back(DFSF.getOrigin(Val)); 2609 } 2610 2611 Value *PrimitiveShadow; 2612 if (ClCombinePointerLabelsOnStore) { 2613 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand()); 2614 if (ShouldTrackOrigins) { 2615 Shadows.push_back(PtrShadow); 2616 Origins.push_back(DFSF.getOrigin(SI.getPointerOperand())); 2617 } 2618 PrimitiveShadow = DFSF.combineShadows(Shadow, PtrShadow, &SI); 2619 } else { 2620 PrimitiveShadow = DFSF.collapseToPrimitiveShadow(Shadow, &SI); 2621 } 2622 Value *Origin = nullptr; 2623 if (ShouldTrackOrigins) 2624 Origin = DFSF.combineOrigins(Shadows, Origins, &SI); 2625 DFSF.storePrimitiveShadowOrigin(SI.getPointerOperand(), Size, SI.getAlign(), 2626 PrimitiveShadow, Origin, &SI); 2627 if (ClEventCallbacks) { 2628 IRBuilder<> IRB(&SI); 2629 Value *Addr8 = IRB.CreateBitCast(SI.getPointerOperand(), DFSF.DFS.Int8Ptr); 2630 IRB.CreateCall(DFSF.DFS.DFSanStoreCallbackFn, {PrimitiveShadow, Addr8}); 2631 } 2632 } 2633 2634 void DFSanVisitor::visitCASOrRMW(Align InstAlignment, Instruction &I) { 2635 assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I)); 2636 2637 Value *Val = I.getOperand(1); 2638 const auto &DL = I.getModule()->getDataLayout(); 2639 uint64_t Size = DL.getTypeStoreSize(Val->getType()); 2640 if (Size == 0) 2641 return; 2642 2643 // Conservatively set data at stored addresses and return with zero shadow to 2644 // prevent shadow data races. 2645 IRBuilder<> IRB(&I); 2646 Value *Addr = I.getOperand(0); 2647 const Align ShadowAlign = DFSF.getShadowAlign(InstAlignment); 2648 DFSF.storeZeroPrimitiveShadow(Addr, Size, ShadowAlign, &I); 2649 DFSF.setShadow(&I, DFSF.DFS.getZeroShadow(&I)); 2650 DFSF.setOrigin(&I, DFSF.DFS.ZeroOrigin); 2651 } 2652 2653 void DFSanVisitor::visitAtomicRMWInst(AtomicRMWInst &I) { 2654 visitCASOrRMW(I.getAlign(), I); 2655 // TODO: The ordering change follows MSan. It is possible not to change 2656 // ordering because we always set and use 0 shadows. 2657 I.setOrdering(addReleaseOrdering(I.getOrdering())); 2658 } 2659 2660 void DFSanVisitor::visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) { 2661 visitCASOrRMW(I.getAlign(), I); 2662 // TODO: The ordering change follows MSan. It is possible not to change 2663 // ordering because we always set and use 0 shadows. 2664 I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering())); 2665 } 2666 2667 void DFSanVisitor::visitUnaryOperator(UnaryOperator &UO) { 2668 visitInstOperands(UO); 2669 } 2670 2671 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) { 2672 visitInstOperands(BO); 2673 } 2674 2675 void DFSanVisitor::visitCastInst(CastInst &CI) { visitInstOperands(CI); } 2676 2677 void DFSanVisitor::visitCmpInst(CmpInst &CI) { 2678 visitInstOperands(CI); 2679 if (ClEventCallbacks) { 2680 IRBuilder<> IRB(&CI); 2681 Value *CombinedShadow = DFSF.getShadow(&CI); 2682 IRB.CreateCall(DFSF.DFS.DFSanCmpCallbackFn, CombinedShadow); 2683 } 2684 } 2685 2686 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) { 2687 visitInstOperands(GEPI); 2688 } 2689 2690 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) { 2691 visitInstOperands(I); 2692 } 2693 2694 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) { 2695 visitInstOperands(I); 2696 } 2697 2698 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) { 2699 visitInstOperands(I); 2700 } 2701 2702 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) { 2703 if (!DFSF.DFS.shouldTrackFieldsAndIndices()) { 2704 visitInstOperands(I); 2705 return; 2706 } 2707 2708 IRBuilder<> IRB(&I); 2709 Value *Agg = I.getAggregateOperand(); 2710 Value *AggShadow = DFSF.getShadow(Agg); 2711 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices()); 2712 DFSF.setShadow(&I, ResShadow); 2713 visitInstOperandOrigins(I); 2714 } 2715 2716 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) { 2717 if (!DFSF.DFS.shouldTrackFieldsAndIndices()) { 2718 visitInstOperands(I); 2719 return; 2720 } 2721 2722 IRBuilder<> IRB(&I); 2723 Value *AggShadow = DFSF.getShadow(I.getAggregateOperand()); 2724 Value *InsShadow = DFSF.getShadow(I.getInsertedValueOperand()); 2725 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices()); 2726 DFSF.setShadow(&I, Res); 2727 visitInstOperandOrigins(I); 2728 } 2729 2730 void DFSanVisitor::visitAllocaInst(AllocaInst &I) { 2731 bool AllLoadsStores = true; 2732 for (User *U : I.users()) { 2733 if (isa<LoadInst>(U)) 2734 continue; 2735 2736 if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 2737 if (SI->getPointerOperand() == &I) 2738 continue; 2739 } 2740 2741 AllLoadsStores = false; 2742 break; 2743 } 2744 if (AllLoadsStores) { 2745 IRBuilder<> IRB(&I); 2746 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.PrimitiveShadowTy); 2747 if (DFSF.DFS.shouldTrackOrigins()) { 2748 DFSF.AllocaOriginMap[&I] = 2749 IRB.CreateAlloca(DFSF.DFS.OriginTy, nullptr, "_dfsa"); 2750 } 2751 } 2752 DFSF.setShadow(&I, DFSF.DFS.ZeroPrimitiveShadow); 2753 DFSF.setOrigin(&I, DFSF.DFS.ZeroOrigin); 2754 } 2755 2756 void DFSanVisitor::visitSelectInst(SelectInst &I) { 2757 Value *CondShadow = DFSF.getShadow(I.getCondition()); 2758 Value *TrueShadow = DFSF.getShadow(I.getTrueValue()); 2759 Value *FalseShadow = DFSF.getShadow(I.getFalseValue()); 2760 Value *ShadowSel = nullptr; 2761 const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins(); 2762 std::vector<Value *> Shadows; 2763 std::vector<Value *> Origins; 2764 Value *TrueOrigin = 2765 ShouldTrackOrigins ? DFSF.getOrigin(I.getTrueValue()) : nullptr; 2766 Value *FalseOrigin = 2767 ShouldTrackOrigins ? DFSF.getOrigin(I.getFalseValue()) : nullptr; 2768 2769 if (isa<VectorType>(I.getCondition()->getType())) { 2770 ShadowSel = DFSF.combineShadowsThenConvert(I.getType(), TrueShadow, 2771 FalseShadow, &I); 2772 if (ShouldTrackOrigins) { 2773 Shadows.push_back(TrueShadow); 2774 Shadows.push_back(FalseShadow); 2775 Origins.push_back(TrueOrigin); 2776 Origins.push_back(FalseOrigin); 2777 } 2778 } else { 2779 if (TrueShadow == FalseShadow) { 2780 ShadowSel = TrueShadow; 2781 if (ShouldTrackOrigins) { 2782 Shadows.push_back(TrueShadow); 2783 Origins.push_back(TrueOrigin); 2784 } 2785 } else { 2786 ShadowSel = 2787 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I); 2788 if (ShouldTrackOrigins) { 2789 Shadows.push_back(ShadowSel); 2790 Origins.push_back(SelectInst::Create(I.getCondition(), TrueOrigin, 2791 FalseOrigin, "", &I)); 2792 } 2793 } 2794 } 2795 DFSF.setShadow(&I, ClTrackSelectControlFlow 2796 ? DFSF.combineShadowsThenConvert( 2797 I.getType(), CondShadow, ShadowSel, &I) 2798 : ShadowSel); 2799 if (ShouldTrackOrigins) { 2800 if (ClTrackSelectControlFlow) { 2801 Shadows.push_back(CondShadow); 2802 Origins.push_back(DFSF.getOrigin(I.getCondition())); 2803 } 2804 DFSF.setOrigin(&I, DFSF.combineOrigins(Shadows, Origins, &I)); 2805 } 2806 } 2807 2808 void DFSanVisitor::visitMemSetInst(MemSetInst &I) { 2809 IRBuilder<> IRB(&I); 2810 Value *ValShadow = DFSF.getShadow(I.getValue()); 2811 Value *ValOrigin = DFSF.DFS.shouldTrackOrigins() 2812 ? DFSF.getOrigin(I.getValue()) 2813 : DFSF.DFS.ZeroOrigin; 2814 IRB.CreateCall( 2815 DFSF.DFS.DFSanSetLabelFn, 2816 {ValShadow, ValOrigin, 2817 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)), 2818 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)}); 2819 } 2820 2821 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) { 2822 IRBuilder<> IRB(&I); 2823 2824 // CopyOrMoveOrigin transfers origins by refering to their shadows. So we 2825 // need to move origins before moving shadows. 2826 if (DFSF.DFS.shouldTrackOrigins()) { 2827 IRB.CreateCall( 2828 DFSF.DFS.DFSanMemOriginTransferFn, 2829 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()), 2830 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()), 2831 IRB.CreateIntCast(I.getArgOperand(2), DFSF.DFS.IntptrTy, false)}); 2832 } 2833 2834 Value *RawDestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I); 2835 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I); 2836 Value *LenShadow = 2837 IRB.CreateMul(I.getLength(), ConstantInt::get(I.getLength()->getType(), 2838 DFSF.DFS.ShadowWidthBytes)); 2839 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx); 2840 Value *DestShadow = IRB.CreateBitCast(RawDestShadow, Int8Ptr); 2841 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr); 2842 auto *MTI = cast<MemTransferInst>( 2843 IRB.CreateCall(I.getFunctionType(), I.getCalledOperand(), 2844 {DestShadow, SrcShadow, LenShadow, I.getVolatileCst()})); 2845 if (ClPreserveAlignment) { 2846 MTI->setDestAlignment(I.getDestAlign() * DFSF.DFS.ShadowWidthBytes); 2847 MTI->setSourceAlignment(I.getSourceAlign() * DFSF.DFS.ShadowWidthBytes); 2848 } else { 2849 MTI->setDestAlignment(Align(DFSF.DFS.ShadowWidthBytes)); 2850 MTI->setSourceAlignment(Align(DFSF.DFS.ShadowWidthBytes)); 2851 } 2852 if (ClEventCallbacks) { 2853 IRB.CreateCall(DFSF.DFS.DFSanMemTransferCallbackFn, 2854 {RawDestShadow, I.getLength()}); 2855 } 2856 } 2857 2858 void DFSanVisitor::visitReturnInst(ReturnInst &RI) { 2859 if (!DFSF.IsNativeABI && RI.getReturnValue()) { 2860 switch (DFSF.IA) { 2861 case DataFlowSanitizer::IA_TLS: { 2862 Value *S = DFSF.getShadow(RI.getReturnValue()); 2863 IRBuilder<> IRB(&RI); 2864 Type *RT = DFSF.F->getFunctionType()->getReturnType(); 2865 unsigned Size = 2866 getDataLayout().getTypeAllocSize(DFSF.DFS.getShadowTy(RT)); 2867 if (Size <= RetvalTLSSize) { 2868 // If the size overflows, stores nothing. At callsite, oversized return 2869 // shadows are set to zero. 2870 IRB.CreateAlignedStore(S, DFSF.getRetvalTLS(RT, IRB), 2871 ShadowTLSAlignment); 2872 } 2873 if (DFSF.DFS.shouldTrackOrigins()) { 2874 Value *O = DFSF.getOrigin(RI.getReturnValue()); 2875 IRB.CreateStore(O, DFSF.getRetvalOriginTLS()); 2876 } 2877 break; 2878 } 2879 case DataFlowSanitizer::IA_Args: { 2880 IRBuilder<> IRB(&RI); 2881 Type *RT = DFSF.F->getFunctionType()->getReturnType(); 2882 Value *InsVal = 2883 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0); 2884 Value *InsShadow = 2885 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1); 2886 RI.setOperand(0, InsShadow); 2887 break; 2888 } 2889 } 2890 } 2891 } 2892 2893 void DFSanVisitor::addShadowArguments(Function &F, CallBase &CB, 2894 std::vector<Value *> &Args, 2895 IRBuilder<> &IRB) { 2896 FunctionType *FT = F.getFunctionType(); 2897 2898 auto *I = CB.arg_begin(); 2899 2900 // Adds non-variable argument shadows. 2901 for (unsigned N = FT->getNumParams(); N != 0; ++I, --N) 2902 Args.push_back(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB)); 2903 2904 // Adds variable argument shadows. 2905 if (FT->isVarArg()) { 2906 auto *LabelVATy = ArrayType::get(DFSF.DFS.PrimitiveShadowTy, 2907 CB.arg_size() - FT->getNumParams()); 2908 auto *LabelVAAlloca = 2909 new AllocaInst(LabelVATy, getDataLayout().getAllocaAddrSpace(), 2910 "labelva", &DFSF.F->getEntryBlock().front()); 2911 2912 for (unsigned N = 0; I != CB.arg_end(); ++I, ++N) { 2913 auto *LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, N); 2914 IRB.CreateStore(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB), 2915 LabelVAPtr); 2916 } 2917 2918 Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0)); 2919 } 2920 2921 // Adds the return value shadow. 2922 if (!FT->getReturnType()->isVoidTy()) { 2923 if (!DFSF.LabelReturnAlloca) { 2924 DFSF.LabelReturnAlloca = new AllocaInst( 2925 DFSF.DFS.PrimitiveShadowTy, getDataLayout().getAllocaAddrSpace(), 2926 "labelreturn", &DFSF.F->getEntryBlock().front()); 2927 } 2928 Args.push_back(DFSF.LabelReturnAlloca); 2929 } 2930 } 2931 2932 void DFSanVisitor::addOriginArguments(Function &F, CallBase &CB, 2933 std::vector<Value *> &Args, 2934 IRBuilder<> &IRB) { 2935 FunctionType *FT = F.getFunctionType(); 2936 2937 auto *I = CB.arg_begin(); 2938 2939 // Add non-variable argument origins. 2940 for (unsigned N = FT->getNumParams(); N != 0; ++I, --N) 2941 Args.push_back(DFSF.getOrigin(*I)); 2942 2943 // Add variable argument origins. 2944 if (FT->isVarArg()) { 2945 auto *OriginVATy = 2946 ArrayType::get(DFSF.DFS.OriginTy, CB.arg_size() - FT->getNumParams()); 2947 auto *OriginVAAlloca = 2948 new AllocaInst(OriginVATy, getDataLayout().getAllocaAddrSpace(), 2949 "originva", &DFSF.F->getEntryBlock().front()); 2950 2951 for (unsigned N = 0; I != CB.arg_end(); ++I, ++N) { 2952 auto *OriginVAPtr = IRB.CreateStructGEP(OriginVATy, OriginVAAlloca, N); 2953 IRB.CreateStore(DFSF.getOrigin(*I), OriginVAPtr); 2954 } 2955 2956 Args.push_back(IRB.CreateStructGEP(OriginVATy, OriginVAAlloca, 0)); 2957 } 2958 2959 // Add the return value origin. 2960 if (!FT->getReturnType()->isVoidTy()) { 2961 if (!DFSF.OriginReturnAlloca) { 2962 DFSF.OriginReturnAlloca = new AllocaInst( 2963 DFSF.DFS.OriginTy, getDataLayout().getAllocaAddrSpace(), 2964 "originreturn", &DFSF.F->getEntryBlock().front()); 2965 } 2966 Args.push_back(DFSF.OriginReturnAlloca); 2967 } 2968 } 2969 2970 bool DFSanVisitor::visitWrappedCallBase(Function &F, CallBase &CB) { 2971 IRBuilder<> IRB(&CB); 2972 switch (DFSF.DFS.getWrapperKind(&F)) { 2973 case DataFlowSanitizer::WK_Warning: 2974 CB.setCalledFunction(&F); 2975 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn, 2976 IRB.CreateGlobalStringPtr(F.getName())); 2977 DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB)); 2978 DFSF.setOrigin(&CB, DFSF.DFS.ZeroOrigin); 2979 return true; 2980 case DataFlowSanitizer::WK_Discard: 2981 CB.setCalledFunction(&F); 2982 DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB)); 2983 DFSF.setOrigin(&CB, DFSF.DFS.ZeroOrigin); 2984 return true; 2985 case DataFlowSanitizer::WK_Functional: 2986 CB.setCalledFunction(&F); 2987 visitInstOperands(CB); 2988 return true; 2989 case DataFlowSanitizer::WK_Custom: 2990 // Don't try to handle invokes of custom functions, it's too complicated. 2991 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_ 2992 // wrapper. 2993 CallInst *CI = dyn_cast<CallInst>(&CB); 2994 if (!CI) 2995 return false; 2996 2997 const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins(); 2998 FunctionType *FT = F.getFunctionType(); 2999 TransformedFunction CustomFn = DFSF.DFS.getCustomFunctionType(FT); 3000 std::string CustomFName = ShouldTrackOrigins ? "__dfso_" : "__dfsw_"; 3001 CustomFName += F.getName(); 3002 FunctionCallee CustomF = DFSF.DFS.Mod->getOrInsertFunction( 3003 CustomFName, CustomFn.TransformedType); 3004 if (Function *CustomFn = dyn_cast<Function>(CustomF.getCallee())) { 3005 CustomFn->copyAttributesFrom(&F); 3006 3007 // Custom functions returning non-void will write to the return label. 3008 if (!FT->getReturnType()->isVoidTy()) { 3009 CustomFn->removeAttributes(AttributeList::FunctionIndex, 3010 DFSF.DFS.ReadOnlyNoneAttrs); 3011 } 3012 } 3013 3014 std::vector<Value *> Args; 3015 3016 // Adds non-variable arguments. 3017 auto *I = CB.arg_begin(); 3018 for (unsigned N = FT->getNumParams(); N != 0; ++I, --N) { 3019 Type *T = (*I)->getType(); 3020 FunctionType *ParamFT; 3021 if (isa<PointerType>(T) && 3022 (ParamFT = dyn_cast<FunctionType>(T->getPointerElementType()))) { 3023 std::string TName = "dfst"; 3024 TName += utostr(FT->getNumParams() - N); 3025 TName += "$"; 3026 TName += F.getName(); 3027 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName); 3028 Args.push_back(T); 3029 Args.push_back( 3030 IRB.CreateBitCast(*I, Type::getInt8PtrTy(*DFSF.DFS.Ctx))); 3031 } else { 3032 Args.push_back(*I); 3033 } 3034 } 3035 3036 // Adds shadow arguments. 3037 const unsigned ShadowArgStart = Args.size(); 3038 addShadowArguments(F, CB, Args, IRB); 3039 3040 // Adds origin arguments. 3041 const unsigned OriginArgStart = Args.size(); 3042 if (ShouldTrackOrigins) 3043 addOriginArguments(F, CB, Args, IRB); 3044 3045 // Adds variable arguments. 3046 append_range(Args, drop_begin(CB.args(), FT->getNumParams())); 3047 3048 CallInst *CustomCI = IRB.CreateCall(CustomF, Args); 3049 CustomCI->setCallingConv(CI->getCallingConv()); 3050 CustomCI->setAttributes(transformFunctionAttributes( 3051 CustomFn, CI->getContext(), CI->getAttributes())); 3052 3053 // Update the parameter attributes of the custom call instruction to 3054 // zero extend the shadow parameters. This is required for targets 3055 // which consider PrimitiveShadowTy an illegal type. 3056 for (unsigned N = 0; N < FT->getNumParams(); N++) { 3057 const unsigned ArgNo = ShadowArgStart + N; 3058 if (CustomCI->getArgOperand(ArgNo)->getType() == 3059 DFSF.DFS.PrimitiveShadowTy) 3060 CustomCI->addParamAttr(ArgNo, Attribute::ZExt); 3061 if (ShouldTrackOrigins) { 3062 const unsigned OriginArgNo = OriginArgStart + N; 3063 if (CustomCI->getArgOperand(OriginArgNo)->getType() == 3064 DFSF.DFS.OriginTy) 3065 CustomCI->addParamAttr(OriginArgNo, Attribute::ZExt); 3066 } 3067 } 3068 3069 // Loads the return value shadow and origin. 3070 if (!FT->getReturnType()->isVoidTy()) { 3071 LoadInst *LabelLoad = 3072 IRB.CreateLoad(DFSF.DFS.PrimitiveShadowTy, DFSF.LabelReturnAlloca); 3073 DFSF.setShadow(CustomCI, DFSF.expandFromPrimitiveShadow( 3074 FT->getReturnType(), LabelLoad, &CB)); 3075 if (ShouldTrackOrigins) { 3076 LoadInst *OriginLoad = 3077 IRB.CreateLoad(DFSF.DFS.OriginTy, DFSF.OriginReturnAlloca); 3078 DFSF.setOrigin(CustomCI, OriginLoad); 3079 } 3080 } 3081 3082 CI->replaceAllUsesWith(CustomCI); 3083 CI->eraseFromParent(); 3084 return true; 3085 } 3086 return false; 3087 } 3088 3089 void DFSanVisitor::visitCallBase(CallBase &CB) { 3090 Function *F = CB.getCalledFunction(); 3091 if ((F && F->isIntrinsic()) || CB.isInlineAsm()) { 3092 visitInstOperands(CB); 3093 return; 3094 } 3095 3096 // Calls to this function are synthesized in wrappers, and we shouldn't 3097 // instrument them. 3098 if (F == DFSF.DFS.DFSanVarargWrapperFn.getCallee()->stripPointerCasts()) 3099 return; 3100 3101 DenseMap<Value *, Function *>::iterator UnwrappedFnIt = 3102 DFSF.DFS.UnwrappedFnMap.find(CB.getCalledOperand()); 3103 if (UnwrappedFnIt != DFSF.DFS.UnwrappedFnMap.end()) 3104 if (visitWrappedCallBase(*UnwrappedFnIt->second, CB)) 3105 return; 3106 3107 IRBuilder<> IRB(&CB); 3108 3109 const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins(); 3110 FunctionType *FT = CB.getFunctionType(); 3111 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) { 3112 // Stores argument shadows. 3113 unsigned ArgOffset = 0; 3114 const DataLayout &DL = getDataLayout(); 3115 for (unsigned I = 0, N = FT->getNumParams(); I != N; ++I) { 3116 if (ShouldTrackOrigins) { 3117 // Ignore overflowed origins 3118 Value *ArgShadow = DFSF.getShadow(CB.getArgOperand(I)); 3119 if (I < DFSF.DFS.NumOfElementsInArgOrgTLS && 3120 !DFSF.DFS.isZeroShadow(ArgShadow)) 3121 IRB.CreateStore(DFSF.getOrigin(CB.getArgOperand(I)), 3122 DFSF.getArgOriginTLS(I, IRB)); 3123 } 3124 3125 unsigned Size = 3126 DL.getTypeAllocSize(DFSF.DFS.getShadowTy(FT->getParamType(I))); 3127 // Stop storing if arguments' size overflows. Inside a function, arguments 3128 // after overflow have zero shadow values. 3129 if (ArgOffset + Size > ArgTLSSize) 3130 break; 3131 IRB.CreateAlignedStore( 3132 DFSF.getShadow(CB.getArgOperand(I)), 3133 DFSF.getArgTLS(FT->getParamType(I), ArgOffset, IRB), 3134 ShadowTLSAlignment); 3135 ArgOffset += alignTo(Size, ShadowTLSAlignment); 3136 } 3137 } 3138 3139 Instruction *Next = nullptr; 3140 if (!CB.getType()->isVoidTy()) { 3141 if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) { 3142 if (II->getNormalDest()->getSinglePredecessor()) { 3143 Next = &II->getNormalDest()->front(); 3144 } else { 3145 BasicBlock *NewBB = 3146 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT); 3147 Next = &NewBB->front(); 3148 } 3149 } else { 3150 assert(CB.getIterator() != CB.getParent()->end()); 3151 Next = CB.getNextNode(); 3152 } 3153 3154 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) { 3155 // Loads the return value shadow. 3156 IRBuilder<> NextIRB(Next); 3157 const DataLayout &DL = getDataLayout(); 3158 unsigned Size = DL.getTypeAllocSize(DFSF.DFS.getShadowTy(&CB)); 3159 if (Size > RetvalTLSSize) { 3160 // Set overflowed return shadow to be zero. 3161 DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB)); 3162 } else { 3163 LoadInst *LI = NextIRB.CreateAlignedLoad( 3164 DFSF.DFS.getShadowTy(&CB), DFSF.getRetvalTLS(CB.getType(), NextIRB), 3165 ShadowTLSAlignment, "_dfsret"); 3166 DFSF.SkipInsts.insert(LI); 3167 DFSF.setShadow(&CB, LI); 3168 DFSF.NonZeroChecks.push_back(LI); 3169 } 3170 3171 if (ShouldTrackOrigins) { 3172 LoadInst *LI = NextIRB.CreateLoad( 3173 DFSF.DFS.OriginTy, DFSF.getRetvalOriginTLS(), "_dfsret_o"); 3174 DFSF.SkipInsts.insert(LI); 3175 DFSF.setOrigin(&CB, LI); 3176 } 3177 } 3178 } 3179 3180 // Do all instrumentation for IA_Args down here to defer tampering with the 3181 // CFG in a way that SplitEdge may be able to detect. 3182 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) { 3183 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT); 3184 Value *Func = 3185 IRB.CreateBitCast(CB.getCalledOperand(), PointerType::getUnqual(NewFT)); 3186 3187 const unsigned NumParams = FT->getNumParams(); 3188 3189 // Copy original arguments. 3190 auto *ArgIt = CB.arg_begin(), *ArgEnd = CB.arg_end(); 3191 std::vector<Value *> Args(NumParams); 3192 std::copy_n(ArgIt, NumParams, Args.begin()); 3193 3194 // Add shadow arguments by transforming original arguments. 3195 std::generate_n(std::back_inserter(Args), NumParams, 3196 [&]() { return DFSF.getShadow(*ArgIt++); }); 3197 3198 if (FT->isVarArg()) { 3199 unsigned VarArgSize = CB.arg_size() - NumParams; 3200 ArrayType *VarArgArrayTy = 3201 ArrayType::get(DFSF.DFS.PrimitiveShadowTy, VarArgSize); 3202 AllocaInst *VarArgShadow = 3203 new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(), 3204 "", &DFSF.F->getEntryBlock().front()); 3205 Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0)); 3206 3207 // Copy remaining var args. 3208 unsigned GepIndex = 0; 3209 std::for_each(ArgIt, ArgEnd, [&](Value *Arg) { 3210 IRB.CreateStore( 3211 DFSF.getShadow(Arg), 3212 IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, GepIndex++)); 3213 Args.push_back(Arg); 3214 }); 3215 } 3216 3217 CallBase *NewCB; 3218 if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) { 3219 NewCB = IRB.CreateInvoke(NewFT, Func, II->getNormalDest(), 3220 II->getUnwindDest(), Args); 3221 } else { 3222 NewCB = IRB.CreateCall(NewFT, Func, Args); 3223 } 3224 NewCB->setCallingConv(CB.getCallingConv()); 3225 NewCB->setAttributes(CB.getAttributes().removeAttributes( 3226 *DFSF.DFS.Ctx, AttributeList::ReturnIndex, 3227 AttributeFuncs::typeIncompatible(NewCB->getType()))); 3228 3229 if (Next) { 3230 ExtractValueInst *ExVal = ExtractValueInst::Create(NewCB, 0, "", Next); 3231 DFSF.SkipInsts.insert(ExVal); 3232 ExtractValueInst *ExShadow = ExtractValueInst::Create(NewCB, 1, "", Next); 3233 DFSF.SkipInsts.insert(ExShadow); 3234 DFSF.setShadow(ExVal, ExShadow); 3235 DFSF.NonZeroChecks.push_back(ExShadow); 3236 3237 CB.replaceAllUsesWith(ExVal); 3238 } 3239 3240 CB.eraseFromParent(); 3241 } 3242 } 3243 3244 void DFSanVisitor::visitPHINode(PHINode &PN) { 3245 Type *ShadowTy = DFSF.DFS.getShadowTy(&PN); 3246 PHINode *ShadowPN = 3247 PHINode::Create(ShadowTy, PN.getNumIncomingValues(), "", &PN); 3248 3249 // Give the shadow phi node valid predecessors to fool SplitEdge into working. 3250 Value *UndefShadow = UndefValue::get(ShadowTy); 3251 for (BasicBlock *BB : PN.blocks()) 3252 ShadowPN->addIncoming(UndefShadow, BB); 3253 3254 DFSF.setShadow(&PN, ShadowPN); 3255 3256 PHINode *OriginPN = nullptr; 3257 if (DFSF.DFS.shouldTrackOrigins()) { 3258 OriginPN = 3259 PHINode::Create(DFSF.DFS.OriginTy, PN.getNumIncomingValues(), "", &PN); 3260 Value *UndefOrigin = UndefValue::get(DFSF.DFS.OriginTy); 3261 for (BasicBlock *BB : PN.blocks()) 3262 OriginPN->addIncoming(UndefOrigin, BB); 3263 DFSF.setOrigin(&PN, OriginPN); 3264 } 3265 3266 DFSF.PHIFixups.push_back({&PN, ShadowPN, OriginPN}); 3267 } 3268 3269 namespace { 3270 class DataFlowSanitizerLegacyPass : public ModulePass { 3271 private: 3272 std::vector<std::string> ABIListFiles; 3273 3274 public: 3275 static char ID; 3276 3277 DataFlowSanitizerLegacyPass( 3278 const std::vector<std::string> &ABIListFiles = std::vector<std::string>()) 3279 : ModulePass(ID), ABIListFiles(ABIListFiles) {} 3280 3281 bool runOnModule(Module &M) override { 3282 return DataFlowSanitizer(ABIListFiles).runImpl(M); 3283 } 3284 }; 3285 } // namespace 3286 3287 char DataFlowSanitizerLegacyPass::ID; 3288 3289 INITIALIZE_PASS(DataFlowSanitizerLegacyPass, "dfsan", 3290 "DataFlowSanitizer: dynamic data flow analysis.", false, false) 3291 3292 ModulePass *llvm::createDataFlowSanitizerLegacyPassPass( 3293 const std::vector<std::string> &ABIListFiles) { 3294 return new DataFlowSanitizerLegacyPass(ABIListFiles); 3295 } 3296 3297 PreservedAnalyses DataFlowSanitizerPass::run(Module &M, 3298 ModuleAnalysisManager &AM) { 3299 if (DataFlowSanitizer(ABIListFiles).runImpl(M)) { 3300 return PreservedAnalyses::none(); 3301 } 3302 return PreservedAnalyses::all(); 3303 } 3304