1 //===- MemorySanitizer.cpp - detector of uninitialized reads --------------===// 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 MemorySanitizer, a detector of uninitialized 11 /// reads. 12 /// 13 /// The algorithm of the tool is similar to Memcheck 14 /// (http://goo.gl/QKbem). We associate a few shadow bits with every 15 /// byte of the application memory, poison the shadow of the malloc-ed 16 /// or alloca-ed memory, load the shadow bits on every memory read, 17 /// propagate the shadow bits through some of the arithmetic 18 /// instruction (including MOV), store the shadow bits on every memory 19 /// write, report a bug on some other instructions (e.g. JMP) if the 20 /// associated shadow is poisoned. 21 /// 22 /// But there are differences too. The first and the major one: 23 /// compiler instrumentation instead of binary instrumentation. This 24 /// gives us much better register allocation, possible compiler 25 /// optimizations and a fast start-up. But this brings the major issue 26 /// as well: msan needs to see all program events, including system 27 /// calls and reads/writes in system libraries, so we either need to 28 /// compile *everything* with msan or use a binary translation 29 /// component (e.g. DynamoRIO) to instrument pre-built libraries. 30 /// Another difference from Memcheck is that we use 8 shadow bits per 31 /// byte of application memory and use a direct shadow mapping. This 32 /// greatly simplifies the instrumentation code and avoids races on 33 /// shadow updates (Memcheck is single-threaded so races are not a 34 /// concern there. Memcheck uses 2 shadow bits per byte with a slow 35 /// path storage that uses 8 bits per byte). 36 /// 37 /// The default value of shadow is 0, which means "clean" (not poisoned). 38 /// 39 /// Every module initializer should call __msan_init to ensure that the 40 /// shadow memory is ready. On error, __msan_warning is called. Since 41 /// parameters and return values may be passed via registers, we have a 42 /// specialized thread-local shadow for return values 43 /// (__msan_retval_tls) and parameters (__msan_param_tls). 44 /// 45 /// Origin tracking. 46 /// 47 /// MemorySanitizer can track origins (allocation points) of all uninitialized 48 /// values. This behavior is controlled with a flag (msan-track-origins) and is 49 /// disabled by default. 50 /// 51 /// Origins are 4-byte values created and interpreted by the runtime library. 52 /// They are stored in a second shadow mapping, one 4-byte value for 4 bytes 53 /// of application memory. Propagation of origins is basically a bunch of 54 /// "select" instructions that pick the origin of a dirty argument, if an 55 /// instruction has one. 56 /// 57 /// Every 4 aligned, consecutive bytes of application memory have one origin 58 /// value associated with them. If these bytes contain uninitialized data 59 /// coming from 2 different allocations, the last store wins. Because of this, 60 /// MemorySanitizer reports can show unrelated origins, but this is unlikely in 61 /// practice. 62 /// 63 /// Origins are meaningless for fully initialized values, so MemorySanitizer 64 /// avoids storing origin to memory when a fully initialized value is stored. 65 /// This way it avoids needless overwriting origin of the 4-byte region on 66 /// a short (i.e. 1 byte) clean store, and it is also good for performance. 67 /// 68 /// Atomic handling. 69 /// 70 /// Ideally, every atomic store of application value should update the 71 /// corresponding shadow location in an atomic way. Unfortunately, atomic store 72 /// of two disjoint locations can not be done without severe slowdown. 73 /// 74 /// Therefore, we implement an approximation that may err on the safe side. 75 /// In this implementation, every atomically accessed location in the program 76 /// may only change from (partially) uninitialized to fully initialized, but 77 /// not the other way around. We load the shadow _after_ the application load, 78 /// and we store the shadow _before_ the app store. Also, we always store clean 79 /// shadow (if the application store is atomic). This way, if the store-load 80 /// pair constitutes a happens-before arc, shadow store and load are correctly 81 /// ordered such that the load will get either the value that was stored, or 82 /// some later value (which is always clean). 83 /// 84 /// This does not work very well with Compare-And-Swap (CAS) and 85 /// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW 86 /// must store the new shadow before the app operation, and load the shadow 87 /// after the app operation. Computers don't work this way. Current 88 /// implementation ignores the load aspect of CAS/RMW, always returning a clean 89 /// value. It implements the store part as a simple atomic store by storing a 90 /// clean shadow. 91 /// 92 /// Instrumenting inline assembly. 93 /// 94 /// For inline assembly code LLVM has little idea about which memory locations 95 /// become initialized depending on the arguments. It can be possible to figure 96 /// out which arguments are meant to point to inputs and outputs, but the 97 /// actual semantics can be only visible at runtime. In the Linux kernel it's 98 /// also possible that the arguments only indicate the offset for a base taken 99 /// from a segment register, so it's dangerous to treat any asm() arguments as 100 /// pointers. We take a conservative approach generating calls to 101 /// __msan_instrument_asm_store(ptr, size) 102 /// , which defer the memory unpoisoning to the runtime library. 103 /// The latter can perform more complex address checks to figure out whether 104 /// it's safe to touch the shadow memory. 105 /// Like with atomic operations, we call __msan_instrument_asm_store() before 106 /// the assembly call, so that changes to the shadow memory will be seen by 107 /// other threads together with main memory initialization. 108 /// 109 /// KernelMemorySanitizer (KMSAN) implementation. 110 /// 111 /// The major differences between KMSAN and MSan instrumentation are: 112 /// - KMSAN always tracks the origins and implies msan-keep-going=true; 113 /// - KMSAN allocates shadow and origin memory for each page separately, so 114 /// there are no explicit accesses to shadow and origin in the 115 /// instrumentation. 116 /// Shadow and origin values for a particular X-byte memory location 117 /// (X=1,2,4,8) are accessed through pointers obtained via the 118 /// __msan_metadata_ptr_for_load_X(ptr) 119 /// __msan_metadata_ptr_for_store_X(ptr) 120 /// functions. The corresponding functions check that the X-byte accesses 121 /// are possible and returns the pointers to shadow and origin memory. 122 /// Arbitrary sized accesses are handled with: 123 /// __msan_metadata_ptr_for_load_n(ptr, size) 124 /// __msan_metadata_ptr_for_store_n(ptr, size); 125 /// - TLS variables are stored in a single per-task struct. A call to a 126 /// function __msan_get_context_state() returning a pointer to that struct 127 /// is inserted into every instrumented function before the entry block; 128 /// - __msan_warning() takes a 32-bit origin parameter; 129 /// - local variables are poisoned with __msan_poison_alloca() upon function 130 /// entry and unpoisoned with __msan_unpoison_alloca() before leaving the 131 /// function; 132 /// - the pass doesn't declare any global variables or add global constructors 133 /// to the translation unit. 134 /// 135 /// Also, KMSAN currently ignores uninitialized memory passed into inline asm 136 /// calls, making sure we're on the safe side wrt. possible false positives. 137 /// 138 /// KernelMemorySanitizer only supports X86_64 at the moment. 139 /// 140 //===----------------------------------------------------------------------===// 141 142 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h" 143 #include "llvm/ADT/APInt.h" 144 #include "llvm/ADT/ArrayRef.h" 145 #include "llvm/ADT/DepthFirstIterator.h" 146 #include "llvm/ADT/SmallSet.h" 147 #include "llvm/ADT/SmallString.h" 148 #include "llvm/ADT/SmallVector.h" 149 #include "llvm/ADT/StringExtras.h" 150 #include "llvm/ADT/StringRef.h" 151 #include "llvm/ADT/Triple.h" 152 #include "llvm/Analysis/TargetLibraryInfo.h" 153 #include "llvm/IR/Argument.h" 154 #include "llvm/IR/Attributes.h" 155 #include "llvm/IR/BasicBlock.h" 156 #include "llvm/IR/CallingConv.h" 157 #include "llvm/IR/Constant.h" 158 #include "llvm/IR/Constants.h" 159 #include "llvm/IR/DataLayout.h" 160 #include "llvm/IR/DerivedTypes.h" 161 #include "llvm/IR/Function.h" 162 #include "llvm/IR/GlobalValue.h" 163 #include "llvm/IR/GlobalVariable.h" 164 #include "llvm/IR/IRBuilder.h" 165 #include "llvm/IR/InlineAsm.h" 166 #include "llvm/IR/InstVisitor.h" 167 #include "llvm/IR/InstrTypes.h" 168 #include "llvm/IR/Instruction.h" 169 #include "llvm/IR/Instructions.h" 170 #include "llvm/IR/IntrinsicInst.h" 171 #include "llvm/IR/Intrinsics.h" 172 #include "llvm/IR/IntrinsicsX86.h" 173 #include "llvm/IR/LLVMContext.h" 174 #include "llvm/IR/MDBuilder.h" 175 #include "llvm/IR/Module.h" 176 #include "llvm/IR/Type.h" 177 #include "llvm/IR/Value.h" 178 #include "llvm/IR/ValueMap.h" 179 #include "llvm/InitializePasses.h" 180 #include "llvm/Pass.h" 181 #include "llvm/Support/AtomicOrdering.h" 182 #include "llvm/Support/Casting.h" 183 #include "llvm/Support/CommandLine.h" 184 #include "llvm/Support/Compiler.h" 185 #include "llvm/Support/Debug.h" 186 #include "llvm/Support/ErrorHandling.h" 187 #include "llvm/Support/MathExtras.h" 188 #include "llvm/Support/raw_ostream.h" 189 #include "llvm/Transforms/Instrumentation.h" 190 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 191 #include "llvm/Transforms/Utils/Local.h" 192 #include "llvm/Transforms/Utils/ModuleUtils.h" 193 #include <algorithm> 194 #include <cassert> 195 #include <cstddef> 196 #include <cstdint> 197 #include <memory> 198 #include <string> 199 #include <tuple> 200 201 using namespace llvm; 202 203 #define DEBUG_TYPE "msan" 204 205 static const unsigned kOriginSize = 4; 206 static const Align kMinOriginAlignment = Align(4); 207 static const Align kShadowTLSAlignment = Align(8); 208 209 // These constants must be kept in sync with the ones in msan.h. 210 static const unsigned kParamTLSSize = 800; 211 static const unsigned kRetvalTLSSize = 800; 212 213 // Accesses sizes are powers of two: 1, 2, 4, 8. 214 static const size_t kNumberOfAccessSizes = 4; 215 216 /// Track origins of uninitialized values. 217 /// 218 /// Adds a section to MemorySanitizer report that points to the allocation 219 /// (stack or heap) the uninitialized bits came from originally. 220 static cl::opt<int> ClTrackOrigins("msan-track-origins", 221 cl::desc("Track origins (allocation sites) of poisoned memory"), 222 cl::Hidden, cl::init(0)); 223 224 static cl::opt<bool> ClKeepGoing("msan-keep-going", 225 cl::desc("keep going after reporting a UMR"), 226 cl::Hidden, cl::init(false)); 227 228 static cl::opt<bool> ClPoisonStack("msan-poison-stack", 229 cl::desc("poison uninitialized stack variables"), 230 cl::Hidden, cl::init(true)); 231 232 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call", 233 cl::desc("poison uninitialized stack variables with a call"), 234 cl::Hidden, cl::init(false)); 235 236 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern", 237 cl::desc("poison uninitialized stack variables with the given pattern"), 238 cl::Hidden, cl::init(0xff)); 239 240 static cl::opt<bool> ClPoisonUndef("msan-poison-undef", 241 cl::desc("poison undef temps"), 242 cl::Hidden, cl::init(true)); 243 244 static cl::opt<bool> ClHandleICmp("msan-handle-icmp", 245 cl::desc("propagate shadow through ICmpEQ and ICmpNE"), 246 cl::Hidden, cl::init(true)); 247 248 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact", 249 cl::desc("exact handling of relational integer ICmp"), 250 cl::Hidden, cl::init(false)); 251 252 static cl::opt<bool> ClHandleLifetimeIntrinsics( 253 "msan-handle-lifetime-intrinsics", 254 cl::desc( 255 "when possible, poison scoped variables at the beginning of the scope " 256 "(slower, but more precise)"), 257 cl::Hidden, cl::init(true)); 258 259 // When compiling the Linux kernel, we sometimes see false positives related to 260 // MSan being unable to understand that inline assembly calls may initialize 261 // local variables. 262 // This flag makes the compiler conservatively unpoison every memory location 263 // passed into an assembly call. Note that this may cause false positives. 264 // Because it's impossible to figure out the array sizes, we can only unpoison 265 // the first sizeof(type) bytes for each type* pointer. 266 // The instrumentation is only enabled in KMSAN builds, and only if 267 // -msan-handle-asm-conservative is on. This is done because we may want to 268 // quickly disable assembly instrumentation when it breaks. 269 static cl::opt<bool> ClHandleAsmConservative( 270 "msan-handle-asm-conservative", 271 cl::desc("conservative handling of inline assembly"), cl::Hidden, 272 cl::init(true)); 273 274 // This flag controls whether we check the shadow of the address 275 // operand of load or store. Such bugs are very rare, since load from 276 // a garbage address typically results in SEGV, but still happen 277 // (e.g. only lower bits of address are garbage, or the access happens 278 // early at program startup where malloc-ed memory is more likely to 279 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown. 280 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address", 281 cl::desc("report accesses through a pointer which has poisoned shadow"), 282 cl::Hidden, cl::init(true)); 283 284 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions", 285 cl::desc("print out instructions with default strict semantics"), 286 cl::Hidden, cl::init(false)); 287 288 static cl::opt<int> ClInstrumentationWithCallThreshold( 289 "msan-instrumentation-with-call-threshold", 290 cl::desc( 291 "If the function being instrumented requires more than " 292 "this number of checks and origin stores, use callbacks instead of " 293 "inline checks (-1 means never use callbacks)."), 294 cl::Hidden, cl::init(3500)); 295 296 static cl::opt<bool> 297 ClEnableKmsan("msan-kernel", 298 cl::desc("Enable KernelMemorySanitizer instrumentation"), 299 cl::Hidden, cl::init(false)); 300 301 // This is an experiment to enable handling of cases where shadow is a non-zero 302 // compile-time constant. For some unexplainable reason they were silently 303 // ignored in the instrumentation. 304 static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow", 305 cl::desc("Insert checks for constant shadow values"), 306 cl::Hidden, cl::init(false)); 307 308 // This is off by default because of a bug in gold: 309 // https://sourceware.org/bugzilla/show_bug.cgi?id=19002 310 static cl::opt<bool> ClWithComdat("msan-with-comdat", 311 cl::desc("Place MSan constructors in comdat sections"), 312 cl::Hidden, cl::init(false)); 313 314 // These options allow to specify custom memory map parameters 315 // See MemoryMapParams for details. 316 static cl::opt<uint64_t> ClAndMask("msan-and-mask", 317 cl::desc("Define custom MSan AndMask"), 318 cl::Hidden, cl::init(0)); 319 320 static cl::opt<uint64_t> ClXorMask("msan-xor-mask", 321 cl::desc("Define custom MSan XorMask"), 322 cl::Hidden, cl::init(0)); 323 324 static cl::opt<uint64_t> ClShadowBase("msan-shadow-base", 325 cl::desc("Define custom MSan ShadowBase"), 326 cl::Hidden, cl::init(0)); 327 328 static cl::opt<uint64_t> ClOriginBase("msan-origin-base", 329 cl::desc("Define custom MSan OriginBase"), 330 cl::Hidden, cl::init(0)); 331 332 static const char *const kMsanModuleCtorName = "msan.module_ctor"; 333 static const char *const kMsanInitName = "__msan_init"; 334 335 namespace { 336 337 // Memory map parameters used in application-to-shadow address calculation. 338 // Offset = (Addr & ~AndMask) ^ XorMask 339 // Shadow = ShadowBase + Offset 340 // Origin = OriginBase + Offset 341 struct MemoryMapParams { 342 uint64_t AndMask; 343 uint64_t XorMask; 344 uint64_t ShadowBase; 345 uint64_t OriginBase; 346 }; 347 348 struct PlatformMemoryMapParams { 349 const MemoryMapParams *bits32; 350 const MemoryMapParams *bits64; 351 }; 352 353 } // end anonymous namespace 354 355 // i386 Linux 356 static const MemoryMapParams Linux_I386_MemoryMapParams = { 357 0x000080000000, // AndMask 358 0, // XorMask (not used) 359 0, // ShadowBase (not used) 360 0x000040000000, // OriginBase 361 }; 362 363 // x86_64 Linux 364 static const MemoryMapParams Linux_X86_64_MemoryMapParams = { 365 #ifdef MSAN_LINUX_X86_64_OLD_MAPPING 366 0x400000000000, // AndMask 367 0, // XorMask (not used) 368 0, // ShadowBase (not used) 369 0x200000000000, // OriginBase 370 #else 371 0, // AndMask (not used) 372 0x500000000000, // XorMask 373 0, // ShadowBase (not used) 374 0x100000000000, // OriginBase 375 #endif 376 }; 377 378 // mips64 Linux 379 static const MemoryMapParams Linux_MIPS64_MemoryMapParams = { 380 0, // AndMask (not used) 381 0x008000000000, // XorMask 382 0, // ShadowBase (not used) 383 0x002000000000, // OriginBase 384 }; 385 386 // ppc64 Linux 387 static const MemoryMapParams Linux_PowerPC64_MemoryMapParams = { 388 0xE00000000000, // AndMask 389 0x100000000000, // XorMask 390 0x080000000000, // ShadowBase 391 0x1C0000000000, // OriginBase 392 }; 393 394 // s390x Linux 395 static const MemoryMapParams Linux_S390X_MemoryMapParams = { 396 0xC00000000000, // AndMask 397 0, // XorMask (not used) 398 0x080000000000, // ShadowBase 399 0x1C0000000000, // OriginBase 400 }; 401 402 // aarch64 Linux 403 static const MemoryMapParams Linux_AArch64_MemoryMapParams = { 404 0, // AndMask (not used) 405 0x06000000000, // XorMask 406 0, // ShadowBase (not used) 407 0x01000000000, // OriginBase 408 }; 409 410 // i386 FreeBSD 411 static const MemoryMapParams FreeBSD_I386_MemoryMapParams = { 412 0x000180000000, // AndMask 413 0x000040000000, // XorMask 414 0x000020000000, // ShadowBase 415 0x000700000000, // OriginBase 416 }; 417 418 // x86_64 FreeBSD 419 static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = { 420 0xc00000000000, // AndMask 421 0x200000000000, // XorMask 422 0x100000000000, // ShadowBase 423 0x380000000000, // OriginBase 424 }; 425 426 // x86_64 NetBSD 427 static const MemoryMapParams NetBSD_X86_64_MemoryMapParams = { 428 0, // AndMask 429 0x500000000000, // XorMask 430 0, // ShadowBase 431 0x100000000000, // OriginBase 432 }; 433 434 static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = { 435 &Linux_I386_MemoryMapParams, 436 &Linux_X86_64_MemoryMapParams, 437 }; 438 439 static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = { 440 nullptr, 441 &Linux_MIPS64_MemoryMapParams, 442 }; 443 444 static const PlatformMemoryMapParams Linux_PowerPC_MemoryMapParams = { 445 nullptr, 446 &Linux_PowerPC64_MemoryMapParams, 447 }; 448 449 static const PlatformMemoryMapParams Linux_S390_MemoryMapParams = { 450 nullptr, 451 &Linux_S390X_MemoryMapParams, 452 }; 453 454 static const PlatformMemoryMapParams Linux_ARM_MemoryMapParams = { 455 nullptr, 456 &Linux_AArch64_MemoryMapParams, 457 }; 458 459 static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = { 460 &FreeBSD_I386_MemoryMapParams, 461 &FreeBSD_X86_64_MemoryMapParams, 462 }; 463 464 static const PlatformMemoryMapParams NetBSD_X86_MemoryMapParams = { 465 nullptr, 466 &NetBSD_X86_64_MemoryMapParams, 467 }; 468 469 namespace { 470 471 /// Instrument functions of a module to detect uninitialized reads. 472 /// 473 /// Instantiating MemorySanitizer inserts the msan runtime library API function 474 /// declarations into the module if they don't exist already. Instantiating 475 /// ensures the __msan_init function is in the list of global constructors for 476 /// the module. 477 class MemorySanitizer { 478 public: 479 MemorySanitizer(Module &M, MemorySanitizerOptions Options) 480 : CompileKernel(Options.Kernel), TrackOrigins(Options.TrackOrigins), 481 Recover(Options.Recover) { 482 initializeModule(M); 483 } 484 485 // MSan cannot be moved or copied because of MapParams. 486 MemorySanitizer(MemorySanitizer &&) = delete; 487 MemorySanitizer &operator=(MemorySanitizer &&) = delete; 488 MemorySanitizer(const MemorySanitizer &) = delete; 489 MemorySanitizer &operator=(const MemorySanitizer &) = delete; 490 491 bool sanitizeFunction(Function &F, TargetLibraryInfo &TLI); 492 493 private: 494 friend struct MemorySanitizerVisitor; 495 friend struct VarArgAMD64Helper; 496 friend struct VarArgMIPS64Helper; 497 friend struct VarArgAArch64Helper; 498 friend struct VarArgPowerPC64Helper; 499 friend struct VarArgSystemZHelper; 500 501 void initializeModule(Module &M); 502 void initializeCallbacks(Module &M); 503 void createKernelApi(Module &M); 504 void createUserspaceApi(Module &M); 505 506 /// True if we're compiling the Linux kernel. 507 bool CompileKernel; 508 /// Track origins (allocation points) of uninitialized values. 509 int TrackOrigins; 510 bool Recover; 511 512 LLVMContext *C; 513 Type *IntptrTy; 514 Type *OriginTy; 515 516 // XxxTLS variables represent the per-thread state in MSan and per-task state 517 // in KMSAN. 518 // For the userspace these point to thread-local globals. In the kernel land 519 // they point to the members of a per-task struct obtained via a call to 520 // __msan_get_context_state(). 521 522 /// Thread-local shadow storage for function parameters. 523 Value *ParamTLS; 524 525 /// Thread-local origin storage for function parameters. 526 Value *ParamOriginTLS; 527 528 /// Thread-local shadow storage for function return value. 529 Value *RetvalTLS; 530 531 /// Thread-local origin storage for function return value. 532 Value *RetvalOriginTLS; 533 534 /// Thread-local shadow storage for in-register va_arg function 535 /// parameters (x86_64-specific). 536 Value *VAArgTLS; 537 538 /// Thread-local shadow storage for in-register va_arg function 539 /// parameters (x86_64-specific). 540 Value *VAArgOriginTLS; 541 542 /// Thread-local shadow storage for va_arg overflow area 543 /// (x86_64-specific). 544 Value *VAArgOverflowSizeTLS; 545 546 /// Are the instrumentation callbacks set up? 547 bool CallbacksInitialized = false; 548 549 /// The run-time callback to print a warning. 550 FunctionCallee WarningFn; 551 552 // These arrays are indexed by log2(AccessSize). 553 FunctionCallee MaybeWarningFn[kNumberOfAccessSizes]; 554 FunctionCallee MaybeStoreOriginFn[kNumberOfAccessSizes]; 555 556 /// Run-time helper that generates a new origin value for a stack 557 /// allocation. 558 FunctionCallee MsanSetAllocaOrigin4Fn; 559 560 /// Run-time helper that poisons stack on function entry. 561 FunctionCallee MsanPoisonStackFn; 562 563 /// Run-time helper that records a store (or any event) of an 564 /// uninitialized value and returns an updated origin id encoding this info. 565 FunctionCallee MsanChainOriginFn; 566 567 /// MSan runtime replacements for memmove, memcpy and memset. 568 FunctionCallee MemmoveFn, MemcpyFn, MemsetFn; 569 570 /// KMSAN callback for task-local function argument shadow. 571 StructType *MsanContextStateTy; 572 FunctionCallee MsanGetContextStateFn; 573 574 /// Functions for poisoning/unpoisoning local variables 575 FunctionCallee MsanPoisonAllocaFn, MsanUnpoisonAllocaFn; 576 577 /// Each of the MsanMetadataPtrXxx functions returns a pair of shadow/origin 578 /// pointers. 579 FunctionCallee MsanMetadataPtrForLoadN, MsanMetadataPtrForStoreN; 580 FunctionCallee MsanMetadataPtrForLoad_1_8[4]; 581 FunctionCallee MsanMetadataPtrForStore_1_8[4]; 582 FunctionCallee MsanInstrumentAsmStoreFn; 583 584 /// Helper to choose between different MsanMetadataPtrXxx(). 585 FunctionCallee getKmsanShadowOriginAccessFn(bool isStore, int size); 586 587 /// Memory map parameters used in application-to-shadow calculation. 588 const MemoryMapParams *MapParams; 589 590 /// Custom memory map parameters used when -msan-shadow-base or 591 // -msan-origin-base is provided. 592 MemoryMapParams CustomMapParams; 593 594 MDNode *ColdCallWeights; 595 596 /// Branch weights for origin store. 597 MDNode *OriginStoreWeights; 598 }; 599 600 void insertModuleCtor(Module &M) { 601 getOrCreateSanitizerCtorAndInitFunctions( 602 M, kMsanModuleCtorName, kMsanInitName, 603 /*InitArgTypes=*/{}, 604 /*InitArgs=*/{}, 605 // This callback is invoked when the functions are created the first 606 // time. Hook them into the global ctors list in that case: 607 [&](Function *Ctor, FunctionCallee) { 608 if (!ClWithComdat) { 609 appendToGlobalCtors(M, Ctor, 0); 610 return; 611 } 612 Comdat *MsanCtorComdat = M.getOrInsertComdat(kMsanModuleCtorName); 613 Ctor->setComdat(MsanCtorComdat); 614 appendToGlobalCtors(M, Ctor, 0, Ctor); 615 }); 616 } 617 618 /// A legacy function pass for msan instrumentation. 619 /// 620 /// Instruments functions to detect uninitialized reads. 621 struct MemorySanitizerLegacyPass : public FunctionPass { 622 // Pass identification, replacement for typeid. 623 static char ID; 624 625 MemorySanitizerLegacyPass(MemorySanitizerOptions Options = {}) 626 : FunctionPass(ID), Options(Options) { 627 initializeMemorySanitizerLegacyPassPass(*PassRegistry::getPassRegistry()); 628 } 629 StringRef getPassName() const override { return "MemorySanitizerLegacyPass"; } 630 631 void getAnalysisUsage(AnalysisUsage &AU) const override { 632 AU.addRequired<TargetLibraryInfoWrapperPass>(); 633 } 634 635 bool runOnFunction(Function &F) override { 636 return MSan->sanitizeFunction( 637 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F)); 638 } 639 bool doInitialization(Module &M) override; 640 641 Optional<MemorySanitizer> MSan; 642 MemorySanitizerOptions Options; 643 }; 644 645 template <class T> T getOptOrDefault(const cl::opt<T> &Opt, T Default) { 646 return (Opt.getNumOccurrences() > 0) ? Opt : Default; 647 } 648 649 } // end anonymous namespace 650 651 MemorySanitizerOptions::MemorySanitizerOptions(int TO, bool R, bool K) 652 : Kernel(getOptOrDefault(ClEnableKmsan, K)), 653 TrackOrigins(getOptOrDefault(ClTrackOrigins, Kernel ? 2 : TO)), 654 Recover(getOptOrDefault(ClKeepGoing, Kernel || R)) {} 655 656 PreservedAnalyses MemorySanitizerPass::run(Function &F, 657 FunctionAnalysisManager &FAM) { 658 MemorySanitizer Msan(*F.getParent(), Options); 659 if (Msan.sanitizeFunction(F, FAM.getResult<TargetLibraryAnalysis>(F))) 660 return PreservedAnalyses::none(); 661 return PreservedAnalyses::all(); 662 } 663 664 PreservedAnalyses MemorySanitizerPass::run(Module &M, 665 ModuleAnalysisManager &AM) { 666 if (Options.Kernel) 667 return PreservedAnalyses::all(); 668 insertModuleCtor(M); 669 return PreservedAnalyses::none(); 670 } 671 672 char MemorySanitizerLegacyPass::ID = 0; 673 674 INITIALIZE_PASS_BEGIN(MemorySanitizerLegacyPass, "msan", 675 "MemorySanitizer: detects uninitialized reads.", false, 676 false) 677 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 678 INITIALIZE_PASS_END(MemorySanitizerLegacyPass, "msan", 679 "MemorySanitizer: detects uninitialized reads.", false, 680 false) 681 682 FunctionPass * 683 llvm::createMemorySanitizerLegacyPassPass(MemorySanitizerOptions Options) { 684 return new MemorySanitizerLegacyPass(Options); 685 } 686 687 /// Create a non-const global initialized with the given string. 688 /// 689 /// Creates a writable global for Str so that we can pass it to the 690 /// run-time lib. Runtime uses first 4 bytes of the string to store the 691 /// frame ID, so the string needs to be mutable. 692 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M, 693 StringRef Str) { 694 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str); 695 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false, 696 GlobalValue::PrivateLinkage, StrConst, ""); 697 } 698 699 /// Create KMSAN API callbacks. 700 void MemorySanitizer::createKernelApi(Module &M) { 701 IRBuilder<> IRB(*C); 702 703 // These will be initialized in insertKmsanPrologue(). 704 RetvalTLS = nullptr; 705 RetvalOriginTLS = nullptr; 706 ParamTLS = nullptr; 707 ParamOriginTLS = nullptr; 708 VAArgTLS = nullptr; 709 VAArgOriginTLS = nullptr; 710 VAArgOverflowSizeTLS = nullptr; 711 712 WarningFn = M.getOrInsertFunction("__msan_warning", IRB.getVoidTy(), 713 IRB.getInt32Ty()); 714 // Requests the per-task context state (kmsan_context_state*) from the 715 // runtime library. 716 MsanContextStateTy = StructType::get( 717 ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), 718 ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), 719 ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), 720 ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), /* va_arg_origin */ 721 IRB.getInt64Ty(), ArrayType::get(OriginTy, kParamTLSSize / 4), OriginTy, 722 OriginTy); 723 MsanGetContextStateFn = M.getOrInsertFunction( 724 "__msan_get_context_state", PointerType::get(MsanContextStateTy, 0)); 725 726 Type *RetTy = StructType::get(PointerType::get(IRB.getInt8Ty(), 0), 727 PointerType::get(IRB.getInt32Ty(), 0)); 728 729 for (int ind = 0, size = 1; ind < 4; ind++, size <<= 1) { 730 std::string name_load = 731 "__msan_metadata_ptr_for_load_" + std::to_string(size); 732 std::string name_store = 733 "__msan_metadata_ptr_for_store_" + std::to_string(size); 734 MsanMetadataPtrForLoad_1_8[ind] = M.getOrInsertFunction( 735 name_load, RetTy, PointerType::get(IRB.getInt8Ty(), 0)); 736 MsanMetadataPtrForStore_1_8[ind] = M.getOrInsertFunction( 737 name_store, RetTy, PointerType::get(IRB.getInt8Ty(), 0)); 738 } 739 740 MsanMetadataPtrForLoadN = M.getOrInsertFunction( 741 "__msan_metadata_ptr_for_load_n", RetTy, 742 PointerType::get(IRB.getInt8Ty(), 0), IRB.getInt64Ty()); 743 MsanMetadataPtrForStoreN = M.getOrInsertFunction( 744 "__msan_metadata_ptr_for_store_n", RetTy, 745 PointerType::get(IRB.getInt8Ty(), 0), IRB.getInt64Ty()); 746 747 // Functions for poisoning and unpoisoning memory. 748 MsanPoisonAllocaFn = 749 M.getOrInsertFunction("__msan_poison_alloca", IRB.getVoidTy(), 750 IRB.getInt8PtrTy(), IntptrTy, IRB.getInt8PtrTy()); 751 MsanUnpoisonAllocaFn = M.getOrInsertFunction( 752 "__msan_unpoison_alloca", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy); 753 } 754 755 static Constant *getOrInsertGlobal(Module &M, StringRef Name, Type *Ty) { 756 return M.getOrInsertGlobal(Name, Ty, [&] { 757 return new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, 758 nullptr, Name, nullptr, 759 GlobalVariable::InitialExecTLSModel); 760 }); 761 } 762 763 /// Insert declarations for userspace-specific functions and globals. 764 void MemorySanitizer::createUserspaceApi(Module &M) { 765 IRBuilder<> IRB(*C); 766 767 // Create the callback. 768 // FIXME: this function should have "Cold" calling conv, 769 // which is not yet implemented. 770 StringRef WarningFnName = Recover ? "__msan_warning_with_origin" 771 : "__msan_warning_with_origin_noreturn"; 772 WarningFn = 773 M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), IRB.getInt32Ty()); 774 775 // Create the global TLS variables. 776 RetvalTLS = 777 getOrInsertGlobal(M, "__msan_retval_tls", 778 ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8)); 779 780 RetvalOriginTLS = getOrInsertGlobal(M, "__msan_retval_origin_tls", OriginTy); 781 782 ParamTLS = 783 getOrInsertGlobal(M, "__msan_param_tls", 784 ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8)); 785 786 ParamOriginTLS = 787 getOrInsertGlobal(M, "__msan_param_origin_tls", 788 ArrayType::get(OriginTy, kParamTLSSize / 4)); 789 790 VAArgTLS = 791 getOrInsertGlobal(M, "__msan_va_arg_tls", 792 ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8)); 793 794 VAArgOriginTLS = 795 getOrInsertGlobal(M, "__msan_va_arg_origin_tls", 796 ArrayType::get(OriginTy, kParamTLSSize / 4)); 797 798 VAArgOverflowSizeTLS = 799 getOrInsertGlobal(M, "__msan_va_arg_overflow_size_tls", IRB.getInt64Ty()); 800 801 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes; 802 AccessSizeIndex++) { 803 unsigned AccessSize = 1 << AccessSizeIndex; 804 std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize); 805 SmallVector<std::pair<unsigned, Attribute>, 2> MaybeWarningFnAttrs; 806 MaybeWarningFnAttrs.push_back(std::make_pair( 807 AttributeList::FirstArgIndex, Attribute::get(*C, Attribute::ZExt))); 808 MaybeWarningFnAttrs.push_back(std::make_pair( 809 AttributeList::FirstArgIndex + 1, Attribute::get(*C, Attribute::ZExt))); 810 MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction( 811 FunctionName, AttributeList::get(*C, MaybeWarningFnAttrs), 812 IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8), IRB.getInt32Ty()); 813 814 FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize); 815 SmallVector<std::pair<unsigned, Attribute>, 2> MaybeStoreOriginFnAttrs; 816 MaybeStoreOriginFnAttrs.push_back(std::make_pair( 817 AttributeList::FirstArgIndex, Attribute::get(*C, Attribute::ZExt))); 818 MaybeStoreOriginFnAttrs.push_back(std::make_pair( 819 AttributeList::FirstArgIndex + 2, Attribute::get(*C, Attribute::ZExt))); 820 MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction( 821 FunctionName, AttributeList::get(*C, MaybeStoreOriginFnAttrs), 822 IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8), IRB.getInt8PtrTy(), 823 IRB.getInt32Ty()); 824 } 825 826 MsanSetAllocaOrigin4Fn = M.getOrInsertFunction( 827 "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, 828 IRB.getInt8PtrTy(), IntptrTy); 829 MsanPoisonStackFn = 830 M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(), 831 IRB.getInt8PtrTy(), IntptrTy); 832 } 833 834 /// Insert extern declaration of runtime-provided functions and globals. 835 void MemorySanitizer::initializeCallbacks(Module &M) { 836 // Only do this once. 837 if (CallbacksInitialized) 838 return; 839 840 IRBuilder<> IRB(*C); 841 // Initialize callbacks that are common for kernel and userspace 842 // instrumentation. 843 MsanChainOriginFn = M.getOrInsertFunction( 844 "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty()); 845 MemmoveFn = M.getOrInsertFunction( 846 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), 847 IRB.getInt8PtrTy(), IntptrTy); 848 MemcpyFn = M.getOrInsertFunction( 849 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), 850 IntptrTy); 851 MemsetFn = M.getOrInsertFunction( 852 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(), 853 IntptrTy); 854 855 MsanInstrumentAsmStoreFn = 856 M.getOrInsertFunction("__msan_instrument_asm_store", IRB.getVoidTy(), 857 PointerType::get(IRB.getInt8Ty(), 0), IntptrTy); 858 859 if (CompileKernel) { 860 createKernelApi(M); 861 } else { 862 createUserspaceApi(M); 863 } 864 CallbacksInitialized = true; 865 } 866 867 FunctionCallee MemorySanitizer::getKmsanShadowOriginAccessFn(bool isStore, 868 int size) { 869 FunctionCallee *Fns = 870 isStore ? MsanMetadataPtrForStore_1_8 : MsanMetadataPtrForLoad_1_8; 871 switch (size) { 872 case 1: 873 return Fns[0]; 874 case 2: 875 return Fns[1]; 876 case 4: 877 return Fns[2]; 878 case 8: 879 return Fns[3]; 880 default: 881 return nullptr; 882 } 883 } 884 885 /// Module-level initialization. 886 /// 887 /// inserts a call to __msan_init to the module's constructor list. 888 void MemorySanitizer::initializeModule(Module &M) { 889 auto &DL = M.getDataLayout(); 890 891 bool ShadowPassed = ClShadowBase.getNumOccurrences() > 0; 892 bool OriginPassed = ClOriginBase.getNumOccurrences() > 0; 893 // Check the overrides first 894 if (ShadowPassed || OriginPassed) { 895 CustomMapParams.AndMask = ClAndMask; 896 CustomMapParams.XorMask = ClXorMask; 897 CustomMapParams.ShadowBase = ClShadowBase; 898 CustomMapParams.OriginBase = ClOriginBase; 899 MapParams = &CustomMapParams; 900 } else { 901 Triple TargetTriple(M.getTargetTriple()); 902 switch (TargetTriple.getOS()) { 903 case Triple::FreeBSD: 904 switch (TargetTriple.getArch()) { 905 case Triple::x86_64: 906 MapParams = FreeBSD_X86_MemoryMapParams.bits64; 907 break; 908 case Triple::x86: 909 MapParams = FreeBSD_X86_MemoryMapParams.bits32; 910 break; 911 default: 912 report_fatal_error("unsupported architecture"); 913 } 914 break; 915 case Triple::NetBSD: 916 switch (TargetTriple.getArch()) { 917 case Triple::x86_64: 918 MapParams = NetBSD_X86_MemoryMapParams.bits64; 919 break; 920 default: 921 report_fatal_error("unsupported architecture"); 922 } 923 break; 924 case Triple::Linux: 925 switch (TargetTriple.getArch()) { 926 case Triple::x86_64: 927 MapParams = Linux_X86_MemoryMapParams.bits64; 928 break; 929 case Triple::x86: 930 MapParams = Linux_X86_MemoryMapParams.bits32; 931 break; 932 case Triple::mips64: 933 case Triple::mips64el: 934 MapParams = Linux_MIPS_MemoryMapParams.bits64; 935 break; 936 case Triple::ppc64: 937 case Triple::ppc64le: 938 MapParams = Linux_PowerPC_MemoryMapParams.bits64; 939 break; 940 case Triple::systemz: 941 MapParams = Linux_S390_MemoryMapParams.bits64; 942 break; 943 case Triple::aarch64: 944 case Triple::aarch64_be: 945 MapParams = Linux_ARM_MemoryMapParams.bits64; 946 break; 947 default: 948 report_fatal_error("unsupported architecture"); 949 } 950 break; 951 default: 952 report_fatal_error("unsupported operating system"); 953 } 954 } 955 956 C = &(M.getContext()); 957 IRBuilder<> IRB(*C); 958 IntptrTy = IRB.getIntPtrTy(DL); 959 OriginTy = IRB.getInt32Ty(); 960 961 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000); 962 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000); 963 964 if (!CompileKernel) { 965 if (TrackOrigins) 966 M.getOrInsertGlobal("__msan_track_origins", IRB.getInt32Ty(), [&] { 967 return new GlobalVariable( 968 M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage, 969 IRB.getInt32(TrackOrigins), "__msan_track_origins"); 970 }); 971 972 if (Recover) 973 M.getOrInsertGlobal("__msan_keep_going", IRB.getInt32Ty(), [&] { 974 return new GlobalVariable(M, IRB.getInt32Ty(), true, 975 GlobalValue::WeakODRLinkage, 976 IRB.getInt32(Recover), "__msan_keep_going"); 977 }); 978 } 979 } 980 981 bool MemorySanitizerLegacyPass::doInitialization(Module &M) { 982 if (!Options.Kernel) 983 insertModuleCtor(M); 984 MSan.emplace(M, Options); 985 return true; 986 } 987 988 namespace { 989 990 /// A helper class that handles instrumentation of VarArg 991 /// functions on a particular platform. 992 /// 993 /// Implementations are expected to insert the instrumentation 994 /// necessary to propagate argument shadow through VarArg function 995 /// calls. Visit* methods are called during an InstVisitor pass over 996 /// the function, and should avoid creating new basic blocks. A new 997 /// instance of this class is created for each instrumented function. 998 struct VarArgHelper { 999 virtual ~VarArgHelper() = default; 1000 1001 /// Visit a CallBase. 1002 virtual void visitCallBase(CallBase &CB, IRBuilder<> &IRB) = 0; 1003 1004 /// Visit a va_start call. 1005 virtual void visitVAStartInst(VAStartInst &I) = 0; 1006 1007 /// Visit a va_copy call. 1008 virtual void visitVACopyInst(VACopyInst &I) = 0; 1009 1010 /// Finalize function instrumentation. 1011 /// 1012 /// This method is called after visiting all interesting (see above) 1013 /// instructions in a function. 1014 virtual void finalizeInstrumentation() = 0; 1015 }; 1016 1017 struct MemorySanitizerVisitor; 1018 1019 } // end anonymous namespace 1020 1021 static VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan, 1022 MemorySanitizerVisitor &Visitor); 1023 1024 static unsigned TypeSizeToSizeIndex(unsigned TypeSize) { 1025 if (TypeSize <= 8) return 0; 1026 return Log2_32_Ceil((TypeSize + 7) / 8); 1027 } 1028 1029 namespace { 1030 1031 /// This class does all the work for a given function. Store and Load 1032 /// instructions store and load corresponding shadow and origin 1033 /// values. Most instructions propagate shadow from arguments to their 1034 /// return values. Certain instructions (most importantly, BranchInst) 1035 /// test their argument shadow and print reports (with a runtime call) if it's 1036 /// non-zero. 1037 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> { 1038 Function &F; 1039 MemorySanitizer &MS; 1040 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes; 1041 ValueMap<Value*, Value*> ShadowMap, OriginMap; 1042 std::unique_ptr<VarArgHelper> VAHelper; 1043 const TargetLibraryInfo *TLI; 1044 BasicBlock *ActualFnStart; 1045 1046 // The following flags disable parts of MSan instrumentation based on 1047 // exclusion list contents and command-line options. 1048 bool InsertChecks; 1049 bool PropagateShadow; 1050 bool PoisonStack; 1051 bool PoisonUndef; 1052 bool CheckReturnValue; 1053 1054 struct ShadowOriginAndInsertPoint { 1055 Value *Shadow; 1056 Value *Origin; 1057 Instruction *OrigIns; 1058 1059 ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I) 1060 : Shadow(S), Origin(O), OrigIns(I) {} 1061 }; 1062 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList; 1063 bool InstrumentLifetimeStart = ClHandleLifetimeIntrinsics; 1064 SmallSet<AllocaInst *, 16> AllocaSet; 1065 SmallVector<std::pair<IntrinsicInst *, AllocaInst *>, 16> LifetimeStartList; 1066 SmallVector<StoreInst *, 16> StoreList; 1067 1068 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS, 1069 const TargetLibraryInfo &TLI) 1070 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)), TLI(&TLI) { 1071 bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeMemory); 1072 InsertChecks = SanitizeFunction; 1073 PropagateShadow = SanitizeFunction; 1074 PoisonStack = SanitizeFunction && ClPoisonStack; 1075 PoisonUndef = SanitizeFunction && ClPoisonUndef; 1076 // FIXME: Consider using SpecialCaseList to specify a list of functions that 1077 // must always return fully initialized values. For now, we hardcode "main". 1078 CheckReturnValue = SanitizeFunction && (F.getName() == "main"); 1079 1080 MS.initializeCallbacks(*F.getParent()); 1081 if (MS.CompileKernel) 1082 ActualFnStart = insertKmsanPrologue(F); 1083 else 1084 ActualFnStart = &F.getEntryBlock(); 1085 1086 LLVM_DEBUG(if (!InsertChecks) dbgs() 1087 << "MemorySanitizer is not inserting checks into '" 1088 << F.getName() << "'\n"); 1089 } 1090 1091 Value *updateOrigin(Value *V, IRBuilder<> &IRB) { 1092 if (MS.TrackOrigins <= 1) return V; 1093 return IRB.CreateCall(MS.MsanChainOriginFn, V); 1094 } 1095 1096 Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) { 1097 const DataLayout &DL = F.getParent()->getDataLayout(); 1098 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy); 1099 if (IntptrSize == kOriginSize) return Origin; 1100 assert(IntptrSize == kOriginSize * 2); 1101 Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false); 1102 return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8)); 1103 } 1104 1105 /// Fill memory range with the given origin value. 1106 void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr, 1107 unsigned Size, Align Alignment) { 1108 const DataLayout &DL = F.getParent()->getDataLayout(); 1109 const Align IntptrAlignment = Align(DL.getABITypeAlignment(MS.IntptrTy)); 1110 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy); 1111 assert(IntptrAlignment >= kMinOriginAlignment); 1112 assert(IntptrSize >= kOriginSize); 1113 1114 unsigned Ofs = 0; 1115 Align CurrentAlignment = Alignment; 1116 if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) { 1117 Value *IntptrOrigin = originToIntptr(IRB, Origin); 1118 Value *IntptrOriginPtr = 1119 IRB.CreatePointerCast(OriginPtr, PointerType::get(MS.IntptrTy, 0)); 1120 for (unsigned i = 0; i < Size / IntptrSize; ++i) { 1121 Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i) 1122 : IntptrOriginPtr; 1123 IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment); 1124 Ofs += IntptrSize / kOriginSize; 1125 CurrentAlignment = IntptrAlignment; 1126 } 1127 } 1128 1129 for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) { 1130 Value *GEP = 1131 i ? IRB.CreateConstGEP1_32(MS.OriginTy, OriginPtr, i) : OriginPtr; 1132 IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment); 1133 CurrentAlignment = kMinOriginAlignment; 1134 } 1135 } 1136 1137 void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin, 1138 Value *OriginPtr, Align Alignment, bool AsCall) { 1139 const DataLayout &DL = F.getParent()->getDataLayout(); 1140 const Align OriginAlignment = std::max(kMinOriginAlignment, Alignment); 1141 unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType()); 1142 if (Shadow->getType()->isAggregateType()) { 1143 paintOrigin(IRB, updateOrigin(Origin, IRB), OriginPtr, StoreSize, 1144 OriginAlignment); 1145 } else { 1146 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB); 1147 if (auto *ConstantShadow = dyn_cast<Constant>(ConvertedShadow)) { 1148 if (ClCheckConstantShadow && !ConstantShadow->isZeroValue()) 1149 paintOrigin(IRB, updateOrigin(Origin, IRB), OriginPtr, StoreSize, 1150 OriginAlignment); 1151 return; 1152 } 1153 1154 unsigned TypeSizeInBits = 1155 DL.getTypeSizeInBits(ConvertedShadow->getType()); 1156 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits); 1157 if (AsCall && SizeIndex < kNumberOfAccessSizes && !MS.CompileKernel) { 1158 FunctionCallee Fn = MS.MaybeStoreOriginFn[SizeIndex]; 1159 Value *ConvertedShadow2 = IRB.CreateZExt( 1160 ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex))); 1161 IRB.CreateCall(Fn, {ConvertedShadow2, 1162 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()), 1163 Origin}); 1164 } else { 1165 Value *Cmp = IRB.CreateICmpNE( 1166 ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp"); 1167 Instruction *CheckTerm = SplitBlockAndInsertIfThen( 1168 Cmp, &*IRB.GetInsertPoint(), false, MS.OriginStoreWeights); 1169 IRBuilder<> IRBNew(CheckTerm); 1170 paintOrigin(IRBNew, updateOrigin(Origin, IRBNew), OriginPtr, StoreSize, 1171 OriginAlignment); 1172 } 1173 } 1174 } 1175 1176 void materializeStores(bool InstrumentWithCalls) { 1177 for (StoreInst *SI : StoreList) { 1178 IRBuilder<> IRB(SI); 1179 Value *Val = SI->getValueOperand(); 1180 Value *Addr = SI->getPointerOperand(); 1181 Value *Shadow = SI->isAtomic() ? getCleanShadow(Val) : getShadow(Val); 1182 Value *ShadowPtr, *OriginPtr; 1183 Type *ShadowTy = Shadow->getType(); 1184 const Align Alignment = assumeAligned(SI->getAlignment()); 1185 const Align OriginAlignment = std::max(kMinOriginAlignment, Alignment); 1186 std::tie(ShadowPtr, OriginPtr) = 1187 getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ true); 1188 1189 StoreInst *NewSI = IRB.CreateAlignedStore(Shadow, ShadowPtr, Alignment); 1190 LLVM_DEBUG(dbgs() << " STORE: " << *NewSI << "\n"); 1191 (void)NewSI; 1192 1193 if (SI->isAtomic()) 1194 SI->setOrdering(addReleaseOrdering(SI->getOrdering())); 1195 1196 if (MS.TrackOrigins && !SI->isAtomic()) 1197 storeOrigin(IRB, Addr, Shadow, getOrigin(Val), OriginPtr, 1198 OriginAlignment, InstrumentWithCalls); 1199 } 1200 } 1201 1202 /// Helper function to insert a warning at IRB's current insert point. 1203 void insertWarningFn(IRBuilder<> &IRB, Value *Origin) { 1204 if (!Origin) 1205 Origin = (Value *)IRB.getInt32(0); 1206 assert(Origin->getType()->isIntegerTy()); 1207 IRB.CreateCall(MS.WarningFn, Origin)->setCannotMerge(); 1208 // FIXME: Insert UnreachableInst if !MS.Recover? 1209 // This may invalidate some of the following checks and needs to be done 1210 // at the very end. 1211 } 1212 1213 void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin, 1214 bool AsCall) { 1215 IRBuilder<> IRB(OrigIns); 1216 LLVM_DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n"); 1217 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB); 1218 LLVM_DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n"); 1219 1220 if (auto *ConstantShadow = dyn_cast<Constant>(ConvertedShadow)) { 1221 if (ClCheckConstantShadow && !ConstantShadow->isZeroValue()) { 1222 insertWarningFn(IRB, Origin); 1223 } 1224 return; 1225 } 1226 1227 const DataLayout &DL = OrigIns->getModule()->getDataLayout(); 1228 1229 unsigned TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType()); 1230 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits); 1231 if (AsCall && SizeIndex < kNumberOfAccessSizes && !MS.CompileKernel) { 1232 FunctionCallee Fn = MS.MaybeWarningFn[SizeIndex]; 1233 Value *ConvertedShadow2 = 1234 IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex))); 1235 IRB.CreateCall(Fn, {ConvertedShadow2, MS.TrackOrigins && Origin 1236 ? Origin 1237 : (Value *)IRB.getInt32(0)}); 1238 } else { 1239 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow, 1240 getCleanShadow(ConvertedShadow), "_mscmp"); 1241 Instruction *CheckTerm = SplitBlockAndInsertIfThen( 1242 Cmp, OrigIns, 1243 /* Unreachable */ !MS.Recover, MS.ColdCallWeights); 1244 1245 IRB.SetInsertPoint(CheckTerm); 1246 insertWarningFn(IRB, Origin); 1247 LLVM_DEBUG(dbgs() << " CHECK: " << *Cmp << "\n"); 1248 } 1249 } 1250 1251 void materializeChecks(bool InstrumentWithCalls) { 1252 for (const auto &ShadowData : InstrumentationList) { 1253 Instruction *OrigIns = ShadowData.OrigIns; 1254 Value *Shadow = ShadowData.Shadow; 1255 Value *Origin = ShadowData.Origin; 1256 materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls); 1257 } 1258 LLVM_DEBUG(dbgs() << "DONE:\n" << F); 1259 } 1260 1261 BasicBlock *insertKmsanPrologue(Function &F) { 1262 BasicBlock *ret = 1263 SplitBlock(&F.getEntryBlock(), F.getEntryBlock().getFirstNonPHI()); 1264 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI()); 1265 Value *ContextState = IRB.CreateCall(MS.MsanGetContextStateFn, {}); 1266 Constant *Zero = IRB.getInt32(0); 1267 MS.ParamTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState, 1268 {Zero, IRB.getInt32(0)}, "param_shadow"); 1269 MS.RetvalTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState, 1270 {Zero, IRB.getInt32(1)}, "retval_shadow"); 1271 MS.VAArgTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState, 1272 {Zero, IRB.getInt32(2)}, "va_arg_shadow"); 1273 MS.VAArgOriginTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState, 1274 {Zero, IRB.getInt32(3)}, "va_arg_origin"); 1275 MS.VAArgOverflowSizeTLS = 1276 IRB.CreateGEP(MS.MsanContextStateTy, ContextState, 1277 {Zero, IRB.getInt32(4)}, "va_arg_overflow_size"); 1278 MS.ParamOriginTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState, 1279 {Zero, IRB.getInt32(5)}, "param_origin"); 1280 MS.RetvalOriginTLS = 1281 IRB.CreateGEP(MS.MsanContextStateTy, ContextState, 1282 {Zero, IRB.getInt32(6)}, "retval_origin"); 1283 return ret; 1284 } 1285 1286 /// Add MemorySanitizer instrumentation to a function. 1287 bool runOnFunction() { 1288 // In the presence of unreachable blocks, we may see Phi nodes with 1289 // incoming nodes from such blocks. Since InstVisitor skips unreachable 1290 // blocks, such nodes will not have any shadow value associated with them. 1291 // It's easier to remove unreachable blocks than deal with missing shadow. 1292 removeUnreachableBlocks(F); 1293 1294 // Iterate all BBs in depth-first order and create shadow instructions 1295 // for all instructions (where applicable). 1296 // For PHI nodes we create dummy shadow PHIs which will be finalized later. 1297 for (BasicBlock *BB : depth_first(ActualFnStart)) 1298 visit(*BB); 1299 1300 // Finalize PHI nodes. 1301 for (PHINode *PN : ShadowPHINodes) { 1302 PHINode *PNS = cast<PHINode>(getShadow(PN)); 1303 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr; 1304 size_t NumValues = PN->getNumIncomingValues(); 1305 for (size_t v = 0; v < NumValues; v++) { 1306 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v)); 1307 if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v)); 1308 } 1309 } 1310 1311 VAHelper->finalizeInstrumentation(); 1312 1313 // Poison llvm.lifetime.start intrinsics, if we haven't fallen back to 1314 // instrumenting only allocas. 1315 if (InstrumentLifetimeStart) { 1316 for (auto Item : LifetimeStartList) { 1317 instrumentAlloca(*Item.second, Item.first); 1318 AllocaSet.erase(Item.second); 1319 } 1320 } 1321 // Poison the allocas for which we didn't instrument the corresponding 1322 // lifetime intrinsics. 1323 for (AllocaInst *AI : AllocaSet) 1324 instrumentAlloca(*AI); 1325 1326 bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 && 1327 InstrumentationList.size() + StoreList.size() > 1328 (unsigned)ClInstrumentationWithCallThreshold; 1329 1330 // Insert shadow value checks. 1331 materializeChecks(InstrumentWithCalls); 1332 1333 // Delayed instrumentation of StoreInst. 1334 // This may not add new address checks. 1335 materializeStores(InstrumentWithCalls); 1336 1337 return true; 1338 } 1339 1340 /// Compute the shadow type that corresponds to a given Value. 1341 Type *getShadowTy(Value *V) { 1342 return getShadowTy(V->getType()); 1343 } 1344 1345 /// Compute the shadow type that corresponds to a given Type. 1346 Type *getShadowTy(Type *OrigTy) { 1347 if (!OrigTy->isSized()) { 1348 return nullptr; 1349 } 1350 // For integer type, shadow is the same as the original type. 1351 // This may return weird-sized types like i1. 1352 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy)) 1353 return IT; 1354 const DataLayout &DL = F.getParent()->getDataLayout(); 1355 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) { 1356 uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType()); 1357 return FixedVectorType::get(IntegerType::get(*MS.C, EltSize), 1358 VT->getNumElements()); 1359 } 1360 if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) { 1361 return ArrayType::get(getShadowTy(AT->getElementType()), 1362 AT->getNumElements()); 1363 } 1364 if (StructType *ST = dyn_cast<StructType>(OrigTy)) { 1365 SmallVector<Type*, 4> Elements; 1366 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++) 1367 Elements.push_back(getShadowTy(ST->getElementType(i))); 1368 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked()); 1369 LLVM_DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n"); 1370 return Res; 1371 } 1372 uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy); 1373 return IntegerType::get(*MS.C, TypeSize); 1374 } 1375 1376 /// Flatten a vector type. 1377 Type *getShadowTyNoVec(Type *ty) { 1378 if (VectorType *vt = dyn_cast<VectorType>(ty)) 1379 return IntegerType::get(*MS.C, 1380 vt->getPrimitiveSizeInBits().getFixedSize()); 1381 return ty; 1382 } 1383 1384 /// Convert a shadow value to it's flattened variant. 1385 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) { 1386 Type *Ty = V->getType(); 1387 Type *NoVecTy = getShadowTyNoVec(Ty); 1388 if (Ty == NoVecTy) return V; 1389 return IRB.CreateBitCast(V, NoVecTy); 1390 } 1391 1392 /// Compute the integer shadow offset that corresponds to a given 1393 /// application address. 1394 /// 1395 /// Offset = (Addr & ~AndMask) ^ XorMask 1396 Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) { 1397 Value *OffsetLong = IRB.CreatePointerCast(Addr, MS.IntptrTy); 1398 1399 uint64_t AndMask = MS.MapParams->AndMask; 1400 if (AndMask) 1401 OffsetLong = 1402 IRB.CreateAnd(OffsetLong, ConstantInt::get(MS.IntptrTy, ~AndMask)); 1403 1404 uint64_t XorMask = MS.MapParams->XorMask; 1405 if (XorMask) 1406 OffsetLong = 1407 IRB.CreateXor(OffsetLong, ConstantInt::get(MS.IntptrTy, XorMask)); 1408 return OffsetLong; 1409 } 1410 1411 /// Compute the shadow and origin addresses corresponding to a given 1412 /// application address. 1413 /// 1414 /// Shadow = ShadowBase + Offset 1415 /// Origin = (OriginBase + Offset) & ~3ULL 1416 std::pair<Value *, Value *> 1417 getShadowOriginPtrUserspace(Value *Addr, IRBuilder<> &IRB, Type *ShadowTy, 1418 MaybeAlign Alignment) { 1419 Value *ShadowOffset = getShadowPtrOffset(Addr, IRB); 1420 Value *ShadowLong = ShadowOffset; 1421 uint64_t ShadowBase = MS.MapParams->ShadowBase; 1422 if (ShadowBase != 0) { 1423 ShadowLong = 1424 IRB.CreateAdd(ShadowLong, 1425 ConstantInt::get(MS.IntptrTy, ShadowBase)); 1426 } 1427 Value *ShadowPtr = 1428 IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0)); 1429 Value *OriginPtr = nullptr; 1430 if (MS.TrackOrigins) { 1431 Value *OriginLong = ShadowOffset; 1432 uint64_t OriginBase = MS.MapParams->OriginBase; 1433 if (OriginBase != 0) 1434 OriginLong = IRB.CreateAdd(OriginLong, 1435 ConstantInt::get(MS.IntptrTy, OriginBase)); 1436 if (!Alignment || *Alignment < kMinOriginAlignment) { 1437 uint64_t Mask = kMinOriginAlignment.value() - 1; 1438 OriginLong = 1439 IRB.CreateAnd(OriginLong, ConstantInt::get(MS.IntptrTy, ~Mask)); 1440 } 1441 OriginPtr = 1442 IRB.CreateIntToPtr(OriginLong, PointerType::get(MS.OriginTy, 0)); 1443 } 1444 return std::make_pair(ShadowPtr, OriginPtr); 1445 } 1446 1447 std::pair<Value *, Value *> getShadowOriginPtrKernel(Value *Addr, 1448 IRBuilder<> &IRB, 1449 Type *ShadowTy, 1450 bool isStore) { 1451 Value *ShadowOriginPtrs; 1452 const DataLayout &DL = F.getParent()->getDataLayout(); 1453 int Size = DL.getTypeStoreSize(ShadowTy); 1454 1455 FunctionCallee Getter = MS.getKmsanShadowOriginAccessFn(isStore, Size); 1456 Value *AddrCast = 1457 IRB.CreatePointerCast(Addr, PointerType::get(IRB.getInt8Ty(), 0)); 1458 if (Getter) { 1459 ShadowOriginPtrs = IRB.CreateCall(Getter, AddrCast); 1460 } else { 1461 Value *SizeVal = ConstantInt::get(MS.IntptrTy, Size); 1462 ShadowOriginPtrs = IRB.CreateCall(isStore ? MS.MsanMetadataPtrForStoreN 1463 : MS.MsanMetadataPtrForLoadN, 1464 {AddrCast, SizeVal}); 1465 } 1466 Value *ShadowPtr = IRB.CreateExtractValue(ShadowOriginPtrs, 0); 1467 ShadowPtr = IRB.CreatePointerCast(ShadowPtr, PointerType::get(ShadowTy, 0)); 1468 Value *OriginPtr = IRB.CreateExtractValue(ShadowOriginPtrs, 1); 1469 1470 return std::make_pair(ShadowPtr, OriginPtr); 1471 } 1472 1473 std::pair<Value *, Value *> getShadowOriginPtr(Value *Addr, IRBuilder<> &IRB, 1474 Type *ShadowTy, 1475 MaybeAlign Alignment, 1476 bool isStore) { 1477 if (MS.CompileKernel) 1478 return getShadowOriginPtrKernel(Addr, IRB, ShadowTy, isStore); 1479 return getShadowOriginPtrUserspace(Addr, IRB, ShadowTy, Alignment); 1480 } 1481 1482 /// Compute the shadow address for a given function argument. 1483 /// 1484 /// Shadow = ParamTLS+ArgOffset. 1485 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB, 1486 int ArgOffset) { 1487 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy); 1488 if (ArgOffset) 1489 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); 1490 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0), 1491 "_msarg"); 1492 } 1493 1494 /// Compute the origin address for a given function argument. 1495 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB, 1496 int ArgOffset) { 1497 if (!MS.TrackOrigins) 1498 return nullptr; 1499 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy); 1500 if (ArgOffset) 1501 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); 1502 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0), 1503 "_msarg_o"); 1504 } 1505 1506 /// Compute the shadow address for a retval. 1507 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) { 1508 return IRB.CreatePointerCast(MS.RetvalTLS, 1509 PointerType::get(getShadowTy(A), 0), 1510 "_msret"); 1511 } 1512 1513 /// Compute the origin address for a retval. 1514 Value *getOriginPtrForRetval(IRBuilder<> &IRB) { 1515 // We keep a single origin for the entire retval. Might be too optimistic. 1516 return MS.RetvalOriginTLS; 1517 } 1518 1519 /// Set SV to be the shadow value for V. 1520 void setShadow(Value *V, Value *SV) { 1521 assert(!ShadowMap.count(V) && "Values may only have one shadow"); 1522 ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V); 1523 } 1524 1525 /// Set Origin to be the origin value for V. 1526 void setOrigin(Value *V, Value *Origin) { 1527 if (!MS.TrackOrigins) return; 1528 assert(!OriginMap.count(V) && "Values may only have one origin"); 1529 LLVM_DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n"); 1530 OriginMap[V] = Origin; 1531 } 1532 1533 Constant *getCleanShadow(Type *OrigTy) { 1534 Type *ShadowTy = getShadowTy(OrigTy); 1535 if (!ShadowTy) 1536 return nullptr; 1537 return Constant::getNullValue(ShadowTy); 1538 } 1539 1540 /// Create a clean shadow value for a given value. 1541 /// 1542 /// Clean shadow (all zeroes) means all bits of the value are defined 1543 /// (initialized). 1544 Constant *getCleanShadow(Value *V) { 1545 return getCleanShadow(V->getType()); 1546 } 1547 1548 /// Create a dirty shadow of a given shadow type. 1549 Constant *getPoisonedShadow(Type *ShadowTy) { 1550 assert(ShadowTy); 1551 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) 1552 return Constant::getAllOnesValue(ShadowTy); 1553 if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) { 1554 SmallVector<Constant *, 4> Vals(AT->getNumElements(), 1555 getPoisonedShadow(AT->getElementType())); 1556 return ConstantArray::get(AT, Vals); 1557 } 1558 if (StructType *ST = dyn_cast<StructType>(ShadowTy)) { 1559 SmallVector<Constant *, 4> Vals; 1560 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++) 1561 Vals.push_back(getPoisonedShadow(ST->getElementType(i))); 1562 return ConstantStruct::get(ST, Vals); 1563 } 1564 llvm_unreachable("Unexpected shadow type"); 1565 } 1566 1567 /// Create a dirty shadow for a given value. 1568 Constant *getPoisonedShadow(Value *V) { 1569 Type *ShadowTy = getShadowTy(V); 1570 if (!ShadowTy) 1571 return nullptr; 1572 return getPoisonedShadow(ShadowTy); 1573 } 1574 1575 /// Create a clean (zero) origin. 1576 Value *getCleanOrigin() { 1577 return Constant::getNullValue(MS.OriginTy); 1578 } 1579 1580 /// Get the shadow value for a given Value. 1581 /// 1582 /// This function either returns the value set earlier with setShadow, 1583 /// or extracts if from ParamTLS (for function arguments). 1584 Value *getShadow(Value *V) { 1585 if (!PropagateShadow) return getCleanShadow(V); 1586 if (Instruction *I = dyn_cast<Instruction>(V)) { 1587 if (I->getMetadata("nosanitize")) 1588 return getCleanShadow(V); 1589 // For instructions the shadow is already stored in the map. 1590 Value *Shadow = ShadowMap[V]; 1591 if (!Shadow) { 1592 LLVM_DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent())); 1593 (void)I; 1594 assert(Shadow && "No shadow for a value"); 1595 } 1596 return Shadow; 1597 } 1598 if (UndefValue *U = dyn_cast<UndefValue>(V)) { 1599 Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V); 1600 LLVM_DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n"); 1601 (void)U; 1602 return AllOnes; 1603 } 1604 if (Argument *A = dyn_cast<Argument>(V)) { 1605 // For arguments we compute the shadow on demand and store it in the map. 1606 Value **ShadowPtr = &ShadowMap[V]; 1607 if (*ShadowPtr) 1608 return *ShadowPtr; 1609 Function *F = A->getParent(); 1610 IRBuilder<> EntryIRB(ActualFnStart->getFirstNonPHI()); 1611 unsigned ArgOffset = 0; 1612 const DataLayout &DL = F->getParent()->getDataLayout(); 1613 for (auto &FArg : F->args()) { 1614 if (!FArg.getType()->isSized()) { 1615 LLVM_DEBUG(dbgs() << "Arg is not sized\n"); 1616 continue; 1617 } 1618 unsigned Size = 1619 FArg.hasByValAttr() 1620 ? DL.getTypeAllocSize(FArg.getParamByValType()) 1621 : DL.getTypeAllocSize(FArg.getType()); 1622 if (A == &FArg) { 1623 bool Overflow = ArgOffset + Size > kParamTLSSize; 1624 Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset); 1625 if (FArg.hasByValAttr()) { 1626 // ByVal pointer itself has clean shadow. We copy the actual 1627 // argument shadow to the underlying memory. 1628 // Figure out maximal valid memcpy alignment. 1629 const Align ArgAlign = DL.getValueOrABITypeAlignment( 1630 MaybeAlign(FArg.getParamAlignment()), FArg.getParamByValType()); 1631 Value *CpShadowPtr = 1632 getShadowOriginPtr(V, EntryIRB, EntryIRB.getInt8Ty(), ArgAlign, 1633 /*isStore*/ true) 1634 .first; 1635 // TODO(glider): need to copy origins. 1636 if (Overflow) { 1637 // ParamTLS overflow. 1638 EntryIRB.CreateMemSet( 1639 CpShadowPtr, Constant::getNullValue(EntryIRB.getInt8Ty()), 1640 Size, ArgAlign); 1641 } else { 1642 const Align CopyAlign = std::min(ArgAlign, kShadowTLSAlignment); 1643 Value *Cpy = EntryIRB.CreateMemCpy(CpShadowPtr, CopyAlign, Base, 1644 CopyAlign, Size); 1645 LLVM_DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n"); 1646 (void)Cpy; 1647 } 1648 *ShadowPtr = getCleanShadow(V); 1649 } else { 1650 if (Overflow) { 1651 // ParamTLS overflow. 1652 *ShadowPtr = getCleanShadow(V); 1653 } else { 1654 *ShadowPtr = EntryIRB.CreateAlignedLoad(getShadowTy(&FArg), Base, 1655 kShadowTLSAlignment); 1656 } 1657 } 1658 LLVM_DEBUG(dbgs() 1659 << " ARG: " << FArg << " ==> " << **ShadowPtr << "\n"); 1660 if (MS.TrackOrigins && !Overflow) { 1661 Value *OriginPtr = 1662 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset); 1663 setOrigin(A, EntryIRB.CreateLoad(MS.OriginTy, OriginPtr)); 1664 } else { 1665 setOrigin(A, getCleanOrigin()); 1666 } 1667 } 1668 ArgOffset += alignTo(Size, kShadowTLSAlignment); 1669 } 1670 assert(*ShadowPtr && "Could not find shadow for an argument"); 1671 return *ShadowPtr; 1672 } 1673 // For everything else the shadow is zero. 1674 return getCleanShadow(V); 1675 } 1676 1677 /// Get the shadow for i-th argument of the instruction I. 1678 Value *getShadow(Instruction *I, int i) { 1679 return getShadow(I->getOperand(i)); 1680 } 1681 1682 /// Get the origin for a value. 1683 Value *getOrigin(Value *V) { 1684 if (!MS.TrackOrigins) return nullptr; 1685 if (!PropagateShadow) return getCleanOrigin(); 1686 if (isa<Constant>(V)) return getCleanOrigin(); 1687 assert((isa<Instruction>(V) || isa<Argument>(V)) && 1688 "Unexpected value type in getOrigin()"); 1689 if (Instruction *I = dyn_cast<Instruction>(V)) { 1690 if (I->getMetadata("nosanitize")) 1691 return getCleanOrigin(); 1692 } 1693 Value *Origin = OriginMap[V]; 1694 assert(Origin && "Missing origin"); 1695 return Origin; 1696 } 1697 1698 /// Get the origin for i-th argument of the instruction I. 1699 Value *getOrigin(Instruction *I, int i) { 1700 return getOrigin(I->getOperand(i)); 1701 } 1702 1703 /// Remember the place where a shadow check should be inserted. 1704 /// 1705 /// This location will be later instrumented with a check that will print a 1706 /// UMR warning in runtime if the shadow value is not 0. 1707 void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) { 1708 assert(Shadow); 1709 if (!InsertChecks) return; 1710 #ifndef NDEBUG 1711 Type *ShadowTy = Shadow->getType(); 1712 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) && 1713 "Can only insert checks for integer and vector shadow types"); 1714 #endif 1715 InstrumentationList.push_back( 1716 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns)); 1717 } 1718 1719 /// Remember the place where a shadow check should be inserted. 1720 /// 1721 /// This location will be later instrumented with a check that will print a 1722 /// UMR warning in runtime if the value is not fully defined. 1723 void insertShadowCheck(Value *Val, Instruction *OrigIns) { 1724 assert(Val); 1725 Value *Shadow, *Origin; 1726 if (ClCheckConstantShadow) { 1727 Shadow = getShadow(Val); 1728 if (!Shadow) return; 1729 Origin = getOrigin(Val); 1730 } else { 1731 Shadow = dyn_cast_or_null<Instruction>(getShadow(Val)); 1732 if (!Shadow) return; 1733 Origin = dyn_cast_or_null<Instruction>(getOrigin(Val)); 1734 } 1735 insertShadowCheck(Shadow, Origin, OrigIns); 1736 } 1737 1738 AtomicOrdering addReleaseOrdering(AtomicOrdering a) { 1739 switch (a) { 1740 case AtomicOrdering::NotAtomic: 1741 return AtomicOrdering::NotAtomic; 1742 case AtomicOrdering::Unordered: 1743 case AtomicOrdering::Monotonic: 1744 case AtomicOrdering::Release: 1745 return AtomicOrdering::Release; 1746 case AtomicOrdering::Acquire: 1747 case AtomicOrdering::AcquireRelease: 1748 return AtomicOrdering::AcquireRelease; 1749 case AtomicOrdering::SequentiallyConsistent: 1750 return AtomicOrdering::SequentiallyConsistent; 1751 } 1752 llvm_unreachable("Unknown ordering"); 1753 } 1754 1755 AtomicOrdering addAcquireOrdering(AtomicOrdering a) { 1756 switch (a) { 1757 case AtomicOrdering::NotAtomic: 1758 return AtomicOrdering::NotAtomic; 1759 case AtomicOrdering::Unordered: 1760 case AtomicOrdering::Monotonic: 1761 case AtomicOrdering::Acquire: 1762 return AtomicOrdering::Acquire; 1763 case AtomicOrdering::Release: 1764 case AtomicOrdering::AcquireRelease: 1765 return AtomicOrdering::AcquireRelease; 1766 case AtomicOrdering::SequentiallyConsistent: 1767 return AtomicOrdering::SequentiallyConsistent; 1768 } 1769 llvm_unreachable("Unknown ordering"); 1770 } 1771 1772 // ------------------- Visitors. 1773 using InstVisitor<MemorySanitizerVisitor>::visit; 1774 void visit(Instruction &I) { 1775 if (!I.getMetadata("nosanitize")) 1776 InstVisitor<MemorySanitizerVisitor>::visit(I); 1777 } 1778 1779 /// Instrument LoadInst 1780 /// 1781 /// Loads the corresponding shadow and (optionally) origin. 1782 /// Optionally, checks that the load address is fully defined. 1783 void visitLoadInst(LoadInst &I) { 1784 assert(I.getType()->isSized() && "Load type must have size"); 1785 assert(!I.getMetadata("nosanitize")); 1786 IRBuilder<> IRB(I.getNextNode()); 1787 Type *ShadowTy = getShadowTy(&I); 1788 Value *Addr = I.getPointerOperand(); 1789 Value *ShadowPtr = nullptr, *OriginPtr = nullptr; 1790 const Align Alignment = assumeAligned(I.getAlignment()); 1791 if (PropagateShadow) { 1792 std::tie(ShadowPtr, OriginPtr) = 1793 getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ false); 1794 setShadow(&I, 1795 IRB.CreateAlignedLoad(ShadowTy, ShadowPtr, Alignment, "_msld")); 1796 } else { 1797 setShadow(&I, getCleanShadow(&I)); 1798 } 1799 1800 if (ClCheckAccessAddress) 1801 insertShadowCheck(I.getPointerOperand(), &I); 1802 1803 if (I.isAtomic()) 1804 I.setOrdering(addAcquireOrdering(I.getOrdering())); 1805 1806 if (MS.TrackOrigins) { 1807 if (PropagateShadow) { 1808 const Align OriginAlignment = std::max(kMinOriginAlignment, Alignment); 1809 setOrigin( 1810 &I, IRB.CreateAlignedLoad(MS.OriginTy, OriginPtr, OriginAlignment)); 1811 } else { 1812 setOrigin(&I, getCleanOrigin()); 1813 } 1814 } 1815 } 1816 1817 /// Instrument StoreInst 1818 /// 1819 /// Stores the corresponding shadow and (optionally) origin. 1820 /// Optionally, checks that the store address is fully defined. 1821 void visitStoreInst(StoreInst &I) { 1822 StoreList.push_back(&I); 1823 if (ClCheckAccessAddress) 1824 insertShadowCheck(I.getPointerOperand(), &I); 1825 } 1826 1827 void handleCASOrRMW(Instruction &I) { 1828 assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I)); 1829 1830 IRBuilder<> IRB(&I); 1831 Value *Addr = I.getOperand(0); 1832 Value *ShadowPtr = getShadowOriginPtr(Addr, IRB, I.getType(), Align(1), 1833 /*isStore*/ true) 1834 .first; 1835 1836 if (ClCheckAccessAddress) 1837 insertShadowCheck(Addr, &I); 1838 1839 // Only test the conditional argument of cmpxchg instruction. 1840 // The other argument can potentially be uninitialized, but we can not 1841 // detect this situation reliably without possible false positives. 1842 if (isa<AtomicCmpXchgInst>(I)) 1843 insertShadowCheck(I.getOperand(1), &I); 1844 1845 IRB.CreateStore(getCleanShadow(&I), ShadowPtr); 1846 1847 setShadow(&I, getCleanShadow(&I)); 1848 setOrigin(&I, getCleanOrigin()); 1849 } 1850 1851 void visitAtomicRMWInst(AtomicRMWInst &I) { 1852 handleCASOrRMW(I); 1853 I.setOrdering(addReleaseOrdering(I.getOrdering())); 1854 } 1855 1856 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) { 1857 handleCASOrRMW(I); 1858 I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering())); 1859 } 1860 1861 // Vector manipulation. 1862 void visitExtractElementInst(ExtractElementInst &I) { 1863 insertShadowCheck(I.getOperand(1), &I); 1864 IRBuilder<> IRB(&I); 1865 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1), 1866 "_msprop")); 1867 setOrigin(&I, getOrigin(&I, 0)); 1868 } 1869 1870 void visitInsertElementInst(InsertElementInst &I) { 1871 insertShadowCheck(I.getOperand(2), &I); 1872 IRBuilder<> IRB(&I); 1873 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1), 1874 I.getOperand(2), "_msprop")); 1875 setOriginForNaryOp(I); 1876 } 1877 1878 void visitShuffleVectorInst(ShuffleVectorInst &I) { 1879 IRBuilder<> IRB(&I); 1880 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1), 1881 I.getShuffleMask(), "_msprop")); 1882 setOriginForNaryOp(I); 1883 } 1884 1885 // Casts. 1886 void visitSExtInst(SExtInst &I) { 1887 IRBuilder<> IRB(&I); 1888 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop")); 1889 setOrigin(&I, getOrigin(&I, 0)); 1890 } 1891 1892 void visitZExtInst(ZExtInst &I) { 1893 IRBuilder<> IRB(&I); 1894 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop")); 1895 setOrigin(&I, getOrigin(&I, 0)); 1896 } 1897 1898 void visitTruncInst(TruncInst &I) { 1899 IRBuilder<> IRB(&I); 1900 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop")); 1901 setOrigin(&I, getOrigin(&I, 0)); 1902 } 1903 1904 void visitBitCastInst(BitCastInst &I) { 1905 // Special case: if this is the bitcast (there is exactly 1 allowed) between 1906 // a musttail call and a ret, don't instrument. New instructions are not 1907 // allowed after a musttail call. 1908 if (auto *CI = dyn_cast<CallInst>(I.getOperand(0))) 1909 if (CI->isMustTailCall()) 1910 return; 1911 IRBuilder<> IRB(&I); 1912 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I))); 1913 setOrigin(&I, getOrigin(&I, 0)); 1914 } 1915 1916 void visitPtrToIntInst(PtrToIntInst &I) { 1917 IRBuilder<> IRB(&I); 1918 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false, 1919 "_msprop_ptrtoint")); 1920 setOrigin(&I, getOrigin(&I, 0)); 1921 } 1922 1923 void visitIntToPtrInst(IntToPtrInst &I) { 1924 IRBuilder<> IRB(&I); 1925 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false, 1926 "_msprop_inttoptr")); 1927 setOrigin(&I, getOrigin(&I, 0)); 1928 } 1929 1930 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); } 1931 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); } 1932 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); } 1933 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); } 1934 void visitFPExtInst(CastInst& I) { handleShadowOr(I); } 1935 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); } 1936 1937 /// Propagate shadow for bitwise AND. 1938 /// 1939 /// This code is exact, i.e. if, for example, a bit in the left argument 1940 /// is defined and 0, then neither the value not definedness of the 1941 /// corresponding bit in B don't affect the resulting shadow. 1942 void visitAnd(BinaryOperator &I) { 1943 IRBuilder<> IRB(&I); 1944 // "And" of 0 and a poisoned value results in unpoisoned value. 1945 // 1&1 => 1; 0&1 => 0; p&1 => p; 1946 // 1&0 => 0; 0&0 => 0; p&0 => 0; 1947 // 1&p => p; 0&p => 0; p&p => p; 1948 // S = (S1 & S2) | (V1 & S2) | (S1 & V2) 1949 Value *S1 = getShadow(&I, 0); 1950 Value *S2 = getShadow(&I, 1); 1951 Value *V1 = I.getOperand(0); 1952 Value *V2 = I.getOperand(1); 1953 if (V1->getType() != S1->getType()) { 1954 V1 = IRB.CreateIntCast(V1, S1->getType(), false); 1955 V2 = IRB.CreateIntCast(V2, S2->getType(), false); 1956 } 1957 Value *S1S2 = IRB.CreateAnd(S1, S2); 1958 Value *V1S2 = IRB.CreateAnd(V1, S2); 1959 Value *S1V2 = IRB.CreateAnd(S1, V2); 1960 setShadow(&I, IRB.CreateOr({S1S2, V1S2, S1V2})); 1961 setOriginForNaryOp(I); 1962 } 1963 1964 void visitOr(BinaryOperator &I) { 1965 IRBuilder<> IRB(&I); 1966 // "Or" of 1 and a poisoned value results in unpoisoned value. 1967 // 1|1 => 1; 0|1 => 1; p|1 => 1; 1968 // 1|0 => 1; 0|0 => 0; p|0 => p; 1969 // 1|p => 1; 0|p => p; p|p => p; 1970 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2) 1971 Value *S1 = getShadow(&I, 0); 1972 Value *S2 = getShadow(&I, 1); 1973 Value *V1 = IRB.CreateNot(I.getOperand(0)); 1974 Value *V2 = IRB.CreateNot(I.getOperand(1)); 1975 if (V1->getType() != S1->getType()) { 1976 V1 = IRB.CreateIntCast(V1, S1->getType(), false); 1977 V2 = IRB.CreateIntCast(V2, S2->getType(), false); 1978 } 1979 Value *S1S2 = IRB.CreateAnd(S1, S2); 1980 Value *V1S2 = IRB.CreateAnd(V1, S2); 1981 Value *S1V2 = IRB.CreateAnd(S1, V2); 1982 setShadow(&I, IRB.CreateOr({S1S2, V1S2, S1V2})); 1983 setOriginForNaryOp(I); 1984 } 1985 1986 /// Default propagation of shadow and/or origin. 1987 /// 1988 /// This class implements the general case of shadow propagation, used in all 1989 /// cases where we don't know and/or don't care about what the operation 1990 /// actually does. It converts all input shadow values to a common type 1991 /// (extending or truncating as necessary), and bitwise OR's them. 1992 /// 1993 /// This is much cheaper than inserting checks (i.e. requiring inputs to be 1994 /// fully initialized), and less prone to false positives. 1995 /// 1996 /// This class also implements the general case of origin propagation. For a 1997 /// Nary operation, result origin is set to the origin of an argument that is 1998 /// not entirely initialized. If there is more than one such arguments, the 1999 /// rightmost of them is picked. It does not matter which one is picked if all 2000 /// arguments are initialized. 2001 template <bool CombineShadow> 2002 class Combiner { 2003 Value *Shadow = nullptr; 2004 Value *Origin = nullptr; 2005 IRBuilder<> &IRB; 2006 MemorySanitizerVisitor *MSV; 2007 2008 public: 2009 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) 2010 : IRB(IRB), MSV(MSV) {} 2011 2012 /// Add a pair of shadow and origin values to the mix. 2013 Combiner &Add(Value *OpShadow, Value *OpOrigin) { 2014 if (CombineShadow) { 2015 assert(OpShadow); 2016 if (!Shadow) 2017 Shadow = OpShadow; 2018 else { 2019 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType()); 2020 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop"); 2021 } 2022 } 2023 2024 if (MSV->MS.TrackOrigins) { 2025 assert(OpOrigin); 2026 if (!Origin) { 2027 Origin = OpOrigin; 2028 } else { 2029 Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin); 2030 // No point in adding something that might result in 0 origin value. 2031 if (!ConstOrigin || !ConstOrigin->isNullValue()) { 2032 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB); 2033 Value *Cond = 2034 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow)); 2035 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin); 2036 } 2037 } 2038 } 2039 return *this; 2040 } 2041 2042 /// Add an application value to the mix. 2043 Combiner &Add(Value *V) { 2044 Value *OpShadow = MSV->getShadow(V); 2045 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr; 2046 return Add(OpShadow, OpOrigin); 2047 } 2048 2049 /// Set the current combined values as the given instruction's shadow 2050 /// and origin. 2051 void Done(Instruction *I) { 2052 if (CombineShadow) { 2053 assert(Shadow); 2054 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I)); 2055 MSV->setShadow(I, Shadow); 2056 } 2057 if (MSV->MS.TrackOrigins) { 2058 assert(Origin); 2059 MSV->setOrigin(I, Origin); 2060 } 2061 } 2062 }; 2063 2064 using ShadowAndOriginCombiner = Combiner<true>; 2065 using OriginCombiner = Combiner<false>; 2066 2067 /// Propagate origin for arbitrary operation. 2068 void setOriginForNaryOp(Instruction &I) { 2069 if (!MS.TrackOrigins) return; 2070 IRBuilder<> IRB(&I); 2071 OriginCombiner OC(this, IRB); 2072 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI) 2073 OC.Add(OI->get()); 2074 OC.Done(&I); 2075 } 2076 2077 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) { 2078 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) && 2079 "Vector of pointers is not a valid shadow type"); 2080 return Ty->isVectorTy() ? cast<VectorType>(Ty)->getNumElements() * 2081 Ty->getScalarSizeInBits() 2082 : Ty->getPrimitiveSizeInBits(); 2083 } 2084 2085 /// Cast between two shadow types, extending or truncating as 2086 /// necessary. 2087 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy, 2088 bool Signed = false) { 2089 Type *srcTy = V->getType(); 2090 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy); 2091 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy); 2092 if (srcSizeInBits > 1 && dstSizeInBits == 1) 2093 return IRB.CreateICmpNE(V, getCleanShadow(V)); 2094 2095 if (dstTy->isIntegerTy() && srcTy->isIntegerTy()) 2096 return IRB.CreateIntCast(V, dstTy, Signed); 2097 if (dstTy->isVectorTy() && srcTy->isVectorTy() && 2098 cast<VectorType>(dstTy)->getNumElements() == 2099 cast<VectorType>(srcTy)->getNumElements()) 2100 return IRB.CreateIntCast(V, dstTy, Signed); 2101 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits)); 2102 Value *V2 = 2103 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed); 2104 return IRB.CreateBitCast(V2, dstTy); 2105 // TODO: handle struct types. 2106 } 2107 2108 /// Cast an application value to the type of its own shadow. 2109 Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) { 2110 Type *ShadowTy = getShadowTy(V); 2111 if (V->getType() == ShadowTy) 2112 return V; 2113 if (V->getType()->isPtrOrPtrVectorTy()) 2114 return IRB.CreatePtrToInt(V, ShadowTy); 2115 else 2116 return IRB.CreateBitCast(V, ShadowTy); 2117 } 2118 2119 /// Propagate shadow for arbitrary operation. 2120 void handleShadowOr(Instruction &I) { 2121 IRBuilder<> IRB(&I); 2122 ShadowAndOriginCombiner SC(this, IRB); 2123 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI) 2124 SC.Add(OI->get()); 2125 SC.Done(&I); 2126 } 2127 2128 void visitFNeg(UnaryOperator &I) { handleShadowOr(I); } 2129 2130 // Handle multiplication by constant. 2131 // 2132 // Handle a special case of multiplication by constant that may have one or 2133 // more zeros in the lower bits. This makes corresponding number of lower bits 2134 // of the result zero as well. We model it by shifting the other operand 2135 // shadow left by the required number of bits. Effectively, we transform 2136 // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B). 2137 // We use multiplication by 2**N instead of shift to cover the case of 2138 // multiplication by 0, which may occur in some elements of a vector operand. 2139 void handleMulByConstant(BinaryOperator &I, Constant *ConstArg, 2140 Value *OtherArg) { 2141 Constant *ShadowMul; 2142 Type *Ty = ConstArg->getType(); 2143 if (auto *VTy = dyn_cast<VectorType>(Ty)) { 2144 unsigned NumElements = VTy->getNumElements(); 2145 Type *EltTy = VTy->getElementType(); 2146 SmallVector<Constant *, 16> Elements; 2147 for (unsigned Idx = 0; Idx < NumElements; ++Idx) { 2148 if (ConstantInt *Elt = 2149 dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx))) { 2150 const APInt &V = Elt->getValue(); 2151 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros(); 2152 Elements.push_back(ConstantInt::get(EltTy, V2)); 2153 } else { 2154 Elements.push_back(ConstantInt::get(EltTy, 1)); 2155 } 2156 } 2157 ShadowMul = ConstantVector::get(Elements); 2158 } else { 2159 if (ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg)) { 2160 const APInt &V = Elt->getValue(); 2161 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros(); 2162 ShadowMul = ConstantInt::get(Ty, V2); 2163 } else { 2164 ShadowMul = ConstantInt::get(Ty, 1); 2165 } 2166 } 2167 2168 IRBuilder<> IRB(&I); 2169 setShadow(&I, 2170 IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst")); 2171 setOrigin(&I, getOrigin(OtherArg)); 2172 } 2173 2174 void visitMul(BinaryOperator &I) { 2175 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0)); 2176 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1)); 2177 if (constOp0 && !constOp1) 2178 handleMulByConstant(I, constOp0, I.getOperand(1)); 2179 else if (constOp1 && !constOp0) 2180 handleMulByConstant(I, constOp1, I.getOperand(0)); 2181 else 2182 handleShadowOr(I); 2183 } 2184 2185 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); } 2186 void visitFSub(BinaryOperator &I) { handleShadowOr(I); } 2187 void visitFMul(BinaryOperator &I) { handleShadowOr(I); } 2188 void visitAdd(BinaryOperator &I) { handleShadowOr(I); } 2189 void visitSub(BinaryOperator &I) { handleShadowOr(I); } 2190 void visitXor(BinaryOperator &I) { handleShadowOr(I); } 2191 2192 void handleIntegerDiv(Instruction &I) { 2193 IRBuilder<> IRB(&I); 2194 // Strict on the second argument. 2195 insertShadowCheck(I.getOperand(1), &I); 2196 setShadow(&I, getShadow(&I, 0)); 2197 setOrigin(&I, getOrigin(&I, 0)); 2198 } 2199 2200 void visitUDiv(BinaryOperator &I) { handleIntegerDiv(I); } 2201 void visitSDiv(BinaryOperator &I) { handleIntegerDiv(I); } 2202 void visitURem(BinaryOperator &I) { handleIntegerDiv(I); } 2203 void visitSRem(BinaryOperator &I) { handleIntegerDiv(I); } 2204 2205 // Floating point division is side-effect free. We can not require that the 2206 // divisor is fully initialized and must propagate shadow. See PR37523. 2207 void visitFDiv(BinaryOperator &I) { handleShadowOr(I); } 2208 void visitFRem(BinaryOperator &I) { handleShadowOr(I); } 2209 2210 /// Instrument == and != comparisons. 2211 /// 2212 /// Sometimes the comparison result is known even if some of the bits of the 2213 /// arguments are not. 2214 void handleEqualityComparison(ICmpInst &I) { 2215 IRBuilder<> IRB(&I); 2216 Value *A = I.getOperand(0); 2217 Value *B = I.getOperand(1); 2218 Value *Sa = getShadow(A); 2219 Value *Sb = getShadow(B); 2220 2221 // Get rid of pointers and vectors of pointers. 2222 // For ints (and vectors of ints), types of A and Sa match, 2223 // and this is a no-op. 2224 A = IRB.CreatePointerCast(A, Sa->getType()); 2225 B = IRB.CreatePointerCast(B, Sb->getType()); 2226 2227 // A == B <==> (C = A^B) == 0 2228 // A != B <==> (C = A^B) != 0 2229 // Sc = Sa | Sb 2230 Value *C = IRB.CreateXor(A, B); 2231 Value *Sc = IRB.CreateOr(Sa, Sb); 2232 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now) 2233 // Result is defined if one of the following is true 2234 // * there is a defined 1 bit in C 2235 // * C is fully defined 2236 // Si = !(C & ~Sc) && Sc 2237 Value *Zero = Constant::getNullValue(Sc->getType()); 2238 Value *MinusOne = Constant::getAllOnesValue(Sc->getType()); 2239 Value *Si = 2240 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero), 2241 IRB.CreateICmpEQ( 2242 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero)); 2243 Si->setName("_msprop_icmp"); 2244 setShadow(&I, Si); 2245 setOriginForNaryOp(I); 2246 } 2247 2248 /// Build the lowest possible value of V, taking into account V's 2249 /// uninitialized bits. 2250 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa, 2251 bool isSigned) { 2252 if (isSigned) { 2253 // Split shadow into sign bit and other bits. 2254 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1); 2255 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits); 2256 // Maximise the undefined shadow bit, minimize other undefined bits. 2257 return 2258 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit); 2259 } else { 2260 // Minimize undefined bits. 2261 return IRB.CreateAnd(A, IRB.CreateNot(Sa)); 2262 } 2263 } 2264 2265 /// Build the highest possible value of V, taking into account V's 2266 /// uninitialized bits. 2267 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa, 2268 bool isSigned) { 2269 if (isSigned) { 2270 // Split shadow into sign bit and other bits. 2271 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1); 2272 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits); 2273 // Minimise the undefined shadow bit, maximise other undefined bits. 2274 return 2275 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits); 2276 } else { 2277 // Maximize undefined bits. 2278 return IRB.CreateOr(A, Sa); 2279 } 2280 } 2281 2282 /// Instrument relational comparisons. 2283 /// 2284 /// This function does exact shadow propagation for all relational 2285 /// comparisons of integers, pointers and vectors of those. 2286 /// FIXME: output seems suboptimal when one of the operands is a constant 2287 void handleRelationalComparisonExact(ICmpInst &I) { 2288 IRBuilder<> IRB(&I); 2289 Value *A = I.getOperand(0); 2290 Value *B = I.getOperand(1); 2291 Value *Sa = getShadow(A); 2292 Value *Sb = getShadow(B); 2293 2294 // Get rid of pointers and vectors of pointers. 2295 // For ints (and vectors of ints), types of A and Sa match, 2296 // and this is a no-op. 2297 A = IRB.CreatePointerCast(A, Sa->getType()); 2298 B = IRB.CreatePointerCast(B, Sb->getType()); 2299 2300 // Let [a0, a1] be the interval of possible values of A, taking into account 2301 // its undefined bits. Let [b0, b1] be the interval of possible values of B. 2302 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0). 2303 bool IsSigned = I.isSigned(); 2304 Value *S1 = IRB.CreateICmp(I.getPredicate(), 2305 getLowestPossibleValue(IRB, A, Sa, IsSigned), 2306 getHighestPossibleValue(IRB, B, Sb, IsSigned)); 2307 Value *S2 = IRB.CreateICmp(I.getPredicate(), 2308 getHighestPossibleValue(IRB, A, Sa, IsSigned), 2309 getLowestPossibleValue(IRB, B, Sb, IsSigned)); 2310 Value *Si = IRB.CreateXor(S1, S2); 2311 setShadow(&I, Si); 2312 setOriginForNaryOp(I); 2313 } 2314 2315 /// Instrument signed relational comparisons. 2316 /// 2317 /// Handle sign bit tests: x<0, x>=0, x<=-1, x>-1 by propagating the highest 2318 /// bit of the shadow. Everything else is delegated to handleShadowOr(). 2319 void handleSignedRelationalComparison(ICmpInst &I) { 2320 Constant *constOp; 2321 Value *op = nullptr; 2322 CmpInst::Predicate pre; 2323 if ((constOp = dyn_cast<Constant>(I.getOperand(1)))) { 2324 op = I.getOperand(0); 2325 pre = I.getPredicate(); 2326 } else if ((constOp = dyn_cast<Constant>(I.getOperand(0)))) { 2327 op = I.getOperand(1); 2328 pre = I.getSwappedPredicate(); 2329 } else { 2330 handleShadowOr(I); 2331 return; 2332 } 2333 2334 if ((constOp->isNullValue() && 2335 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) || 2336 (constOp->isAllOnesValue() && 2337 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE))) { 2338 IRBuilder<> IRB(&I); 2339 Value *Shadow = IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), 2340 "_msprop_icmp_s"); 2341 setShadow(&I, Shadow); 2342 setOrigin(&I, getOrigin(op)); 2343 } else { 2344 handleShadowOr(I); 2345 } 2346 } 2347 2348 void visitICmpInst(ICmpInst &I) { 2349 if (!ClHandleICmp) { 2350 handleShadowOr(I); 2351 return; 2352 } 2353 if (I.isEquality()) { 2354 handleEqualityComparison(I); 2355 return; 2356 } 2357 2358 assert(I.isRelational()); 2359 if (ClHandleICmpExact) { 2360 handleRelationalComparisonExact(I); 2361 return; 2362 } 2363 if (I.isSigned()) { 2364 handleSignedRelationalComparison(I); 2365 return; 2366 } 2367 2368 assert(I.isUnsigned()); 2369 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) { 2370 handleRelationalComparisonExact(I); 2371 return; 2372 } 2373 2374 handleShadowOr(I); 2375 } 2376 2377 void visitFCmpInst(FCmpInst &I) { 2378 handleShadowOr(I); 2379 } 2380 2381 void handleShift(BinaryOperator &I) { 2382 IRBuilder<> IRB(&I); 2383 // If any of the S2 bits are poisoned, the whole thing is poisoned. 2384 // Otherwise perform the same shift on S1. 2385 Value *S1 = getShadow(&I, 0); 2386 Value *S2 = getShadow(&I, 1); 2387 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)), 2388 S2->getType()); 2389 Value *V2 = I.getOperand(1); 2390 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2); 2391 setShadow(&I, IRB.CreateOr(Shift, S2Conv)); 2392 setOriginForNaryOp(I); 2393 } 2394 2395 void visitShl(BinaryOperator &I) { handleShift(I); } 2396 void visitAShr(BinaryOperator &I) { handleShift(I); } 2397 void visitLShr(BinaryOperator &I) { handleShift(I); } 2398 2399 /// Instrument llvm.memmove 2400 /// 2401 /// At this point we don't know if llvm.memmove will be inlined or not. 2402 /// If we don't instrument it and it gets inlined, 2403 /// our interceptor will not kick in and we will lose the memmove. 2404 /// If we instrument the call here, but it does not get inlined, 2405 /// we will memove the shadow twice: which is bad in case 2406 /// of overlapping regions. So, we simply lower the intrinsic to a call. 2407 /// 2408 /// Similar situation exists for memcpy and memset. 2409 void visitMemMoveInst(MemMoveInst &I) { 2410 IRBuilder<> IRB(&I); 2411 IRB.CreateCall( 2412 MS.MemmoveFn, 2413 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()), 2414 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()), 2415 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)}); 2416 I.eraseFromParent(); 2417 } 2418 2419 // Similar to memmove: avoid copying shadow twice. 2420 // This is somewhat unfortunate as it may slowdown small constant memcpys. 2421 // FIXME: consider doing manual inline for small constant sizes and proper 2422 // alignment. 2423 void visitMemCpyInst(MemCpyInst &I) { 2424 IRBuilder<> IRB(&I); 2425 IRB.CreateCall( 2426 MS.MemcpyFn, 2427 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()), 2428 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()), 2429 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)}); 2430 I.eraseFromParent(); 2431 } 2432 2433 // Same as memcpy. 2434 void visitMemSetInst(MemSetInst &I) { 2435 IRBuilder<> IRB(&I); 2436 IRB.CreateCall( 2437 MS.MemsetFn, 2438 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()), 2439 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false), 2440 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)}); 2441 I.eraseFromParent(); 2442 } 2443 2444 void visitVAStartInst(VAStartInst &I) { 2445 VAHelper->visitVAStartInst(I); 2446 } 2447 2448 void visitVACopyInst(VACopyInst &I) { 2449 VAHelper->visitVACopyInst(I); 2450 } 2451 2452 /// Handle vector store-like intrinsics. 2453 /// 2454 /// Instrument intrinsics that look like a simple SIMD store: writes memory, 2455 /// has 1 pointer argument and 1 vector argument, returns void. 2456 bool handleVectorStoreIntrinsic(IntrinsicInst &I) { 2457 IRBuilder<> IRB(&I); 2458 Value* Addr = I.getArgOperand(0); 2459 Value *Shadow = getShadow(&I, 1); 2460 Value *ShadowPtr, *OriginPtr; 2461 2462 // We don't know the pointer alignment (could be unaligned SSE store!). 2463 // Have to assume to worst case. 2464 std::tie(ShadowPtr, OriginPtr) = getShadowOriginPtr( 2465 Addr, IRB, Shadow->getType(), Align(1), /*isStore*/ true); 2466 IRB.CreateAlignedStore(Shadow, ShadowPtr, Align(1)); 2467 2468 if (ClCheckAccessAddress) 2469 insertShadowCheck(Addr, &I); 2470 2471 // FIXME: factor out common code from materializeStores 2472 if (MS.TrackOrigins) IRB.CreateStore(getOrigin(&I, 1), OriginPtr); 2473 return true; 2474 } 2475 2476 /// Handle vector load-like intrinsics. 2477 /// 2478 /// Instrument intrinsics that look like a simple SIMD load: reads memory, 2479 /// has 1 pointer argument, returns a vector. 2480 bool handleVectorLoadIntrinsic(IntrinsicInst &I) { 2481 IRBuilder<> IRB(&I); 2482 Value *Addr = I.getArgOperand(0); 2483 2484 Type *ShadowTy = getShadowTy(&I); 2485 Value *ShadowPtr = nullptr, *OriginPtr = nullptr; 2486 if (PropagateShadow) { 2487 // We don't know the pointer alignment (could be unaligned SSE load!). 2488 // Have to assume to worst case. 2489 const Align Alignment = Align(1); 2490 std::tie(ShadowPtr, OriginPtr) = 2491 getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ false); 2492 setShadow(&I, 2493 IRB.CreateAlignedLoad(ShadowTy, ShadowPtr, Alignment, "_msld")); 2494 } else { 2495 setShadow(&I, getCleanShadow(&I)); 2496 } 2497 2498 if (ClCheckAccessAddress) 2499 insertShadowCheck(Addr, &I); 2500 2501 if (MS.TrackOrigins) { 2502 if (PropagateShadow) 2503 setOrigin(&I, IRB.CreateLoad(MS.OriginTy, OriginPtr)); 2504 else 2505 setOrigin(&I, getCleanOrigin()); 2506 } 2507 return true; 2508 } 2509 2510 /// Handle (SIMD arithmetic)-like intrinsics. 2511 /// 2512 /// Instrument intrinsics with any number of arguments of the same type, 2513 /// equal to the return type. The type should be simple (no aggregates or 2514 /// pointers; vectors are fine). 2515 /// Caller guarantees that this intrinsic does not access memory. 2516 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) { 2517 Type *RetTy = I.getType(); 2518 if (!(RetTy->isIntOrIntVectorTy() || 2519 RetTy->isFPOrFPVectorTy() || 2520 RetTy->isX86_MMXTy())) 2521 return false; 2522 2523 unsigned NumArgOperands = I.getNumArgOperands(); 2524 2525 for (unsigned i = 0; i < NumArgOperands; ++i) { 2526 Type *Ty = I.getArgOperand(i)->getType(); 2527 if (Ty != RetTy) 2528 return false; 2529 } 2530 2531 IRBuilder<> IRB(&I); 2532 ShadowAndOriginCombiner SC(this, IRB); 2533 for (unsigned i = 0; i < NumArgOperands; ++i) 2534 SC.Add(I.getArgOperand(i)); 2535 SC.Done(&I); 2536 2537 return true; 2538 } 2539 2540 /// Heuristically instrument unknown intrinsics. 2541 /// 2542 /// The main purpose of this code is to do something reasonable with all 2543 /// random intrinsics we might encounter, most importantly - SIMD intrinsics. 2544 /// We recognize several classes of intrinsics by their argument types and 2545 /// ModRefBehaviour and apply special instrumentation when we are reasonably 2546 /// sure that we know what the intrinsic does. 2547 /// 2548 /// We special-case intrinsics where this approach fails. See llvm.bswap 2549 /// handling as an example of that. 2550 bool handleUnknownIntrinsic(IntrinsicInst &I) { 2551 unsigned NumArgOperands = I.getNumArgOperands(); 2552 if (NumArgOperands == 0) 2553 return false; 2554 2555 if (NumArgOperands == 2 && 2556 I.getArgOperand(0)->getType()->isPointerTy() && 2557 I.getArgOperand(1)->getType()->isVectorTy() && 2558 I.getType()->isVoidTy() && 2559 !I.onlyReadsMemory()) { 2560 // This looks like a vector store. 2561 return handleVectorStoreIntrinsic(I); 2562 } 2563 2564 if (NumArgOperands == 1 && 2565 I.getArgOperand(0)->getType()->isPointerTy() && 2566 I.getType()->isVectorTy() && 2567 I.onlyReadsMemory()) { 2568 // This looks like a vector load. 2569 return handleVectorLoadIntrinsic(I); 2570 } 2571 2572 if (I.doesNotAccessMemory()) 2573 if (maybeHandleSimpleNomemIntrinsic(I)) 2574 return true; 2575 2576 // FIXME: detect and handle SSE maskstore/maskload 2577 return false; 2578 } 2579 2580 void handleInvariantGroup(IntrinsicInst &I) { 2581 setShadow(&I, getShadow(&I, 0)); 2582 setOrigin(&I, getOrigin(&I, 0)); 2583 } 2584 2585 void handleLifetimeStart(IntrinsicInst &I) { 2586 if (!PoisonStack) 2587 return; 2588 DenseMap<Value *, AllocaInst *> AllocaForValue; 2589 AllocaInst *AI = 2590 llvm::findAllocaForValue(I.getArgOperand(1), AllocaForValue); 2591 if (!AI) 2592 InstrumentLifetimeStart = false; 2593 LifetimeStartList.push_back(std::make_pair(&I, AI)); 2594 } 2595 2596 void handleBswap(IntrinsicInst &I) { 2597 IRBuilder<> IRB(&I); 2598 Value *Op = I.getArgOperand(0); 2599 Type *OpType = Op->getType(); 2600 Function *BswapFunc = Intrinsic::getDeclaration( 2601 F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1)); 2602 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op))); 2603 setOrigin(&I, getOrigin(Op)); 2604 } 2605 2606 // Instrument vector convert intrinsic. 2607 // 2608 // This function instruments intrinsics like cvtsi2ss: 2609 // %Out = int_xxx_cvtyyy(%ConvertOp) 2610 // or 2611 // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp) 2612 // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same 2613 // number \p Out elements, and (if has 2 arguments) copies the rest of the 2614 // elements from \p CopyOp. 2615 // In most cases conversion involves floating-point value which may trigger a 2616 // hardware exception when not fully initialized. For this reason we require 2617 // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise. 2618 // We copy the shadow of \p CopyOp[NumUsedElements:] to \p 2619 // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always 2620 // return a fully initialized value. 2621 void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) { 2622 IRBuilder<> IRB(&I); 2623 Value *CopyOp, *ConvertOp; 2624 2625 switch (I.getNumArgOperands()) { 2626 case 3: 2627 assert(isa<ConstantInt>(I.getArgOperand(2)) && "Invalid rounding mode"); 2628 LLVM_FALLTHROUGH; 2629 case 2: 2630 CopyOp = I.getArgOperand(0); 2631 ConvertOp = I.getArgOperand(1); 2632 break; 2633 case 1: 2634 ConvertOp = I.getArgOperand(0); 2635 CopyOp = nullptr; 2636 break; 2637 default: 2638 llvm_unreachable("Cvt intrinsic with unsupported number of arguments."); 2639 } 2640 2641 // The first *NumUsedElements* elements of ConvertOp are converted to the 2642 // same number of output elements. The rest of the output is copied from 2643 // CopyOp, or (if not available) filled with zeroes. 2644 // Combine shadow for elements of ConvertOp that are used in this operation, 2645 // and insert a check. 2646 // FIXME: consider propagating shadow of ConvertOp, at least in the case of 2647 // int->any conversion. 2648 Value *ConvertShadow = getShadow(ConvertOp); 2649 Value *AggShadow = nullptr; 2650 if (ConvertOp->getType()->isVectorTy()) { 2651 AggShadow = IRB.CreateExtractElement( 2652 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0)); 2653 for (int i = 1; i < NumUsedElements; ++i) { 2654 Value *MoreShadow = IRB.CreateExtractElement( 2655 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i)); 2656 AggShadow = IRB.CreateOr(AggShadow, MoreShadow); 2657 } 2658 } else { 2659 AggShadow = ConvertShadow; 2660 } 2661 assert(AggShadow->getType()->isIntegerTy()); 2662 insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I); 2663 2664 // Build result shadow by zero-filling parts of CopyOp shadow that come from 2665 // ConvertOp. 2666 if (CopyOp) { 2667 assert(CopyOp->getType() == I.getType()); 2668 assert(CopyOp->getType()->isVectorTy()); 2669 Value *ResultShadow = getShadow(CopyOp); 2670 Type *EltTy = cast<VectorType>(ResultShadow->getType())->getElementType(); 2671 for (int i = 0; i < NumUsedElements; ++i) { 2672 ResultShadow = IRB.CreateInsertElement( 2673 ResultShadow, ConstantInt::getNullValue(EltTy), 2674 ConstantInt::get(IRB.getInt32Ty(), i)); 2675 } 2676 setShadow(&I, ResultShadow); 2677 setOrigin(&I, getOrigin(CopyOp)); 2678 } else { 2679 setShadow(&I, getCleanShadow(&I)); 2680 setOrigin(&I, getCleanOrigin()); 2681 } 2682 } 2683 2684 // Given a scalar or vector, extract lower 64 bits (or less), and return all 2685 // zeroes if it is zero, and all ones otherwise. 2686 Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) { 2687 if (S->getType()->isVectorTy()) 2688 S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true); 2689 assert(S->getType()->getPrimitiveSizeInBits() <= 64); 2690 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S)); 2691 return CreateShadowCast(IRB, S2, T, /* Signed */ true); 2692 } 2693 2694 // Given a vector, extract its first element, and return all 2695 // zeroes if it is zero, and all ones otherwise. 2696 Value *LowerElementShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) { 2697 Value *S1 = IRB.CreateExtractElement(S, (uint64_t)0); 2698 Value *S2 = IRB.CreateICmpNE(S1, getCleanShadow(S1)); 2699 return CreateShadowCast(IRB, S2, T, /* Signed */ true); 2700 } 2701 2702 Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) { 2703 Type *T = S->getType(); 2704 assert(T->isVectorTy()); 2705 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S)); 2706 return IRB.CreateSExt(S2, T); 2707 } 2708 2709 // Instrument vector shift intrinsic. 2710 // 2711 // This function instruments intrinsics like int_x86_avx2_psll_w. 2712 // Intrinsic shifts %In by %ShiftSize bits. 2713 // %ShiftSize may be a vector. In that case the lower 64 bits determine shift 2714 // size, and the rest is ignored. Behavior is defined even if shift size is 2715 // greater than register (or field) width. 2716 void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) { 2717 assert(I.getNumArgOperands() == 2); 2718 IRBuilder<> IRB(&I); 2719 // If any of the S2 bits are poisoned, the whole thing is poisoned. 2720 // Otherwise perform the same shift on S1. 2721 Value *S1 = getShadow(&I, 0); 2722 Value *S2 = getShadow(&I, 1); 2723 Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2) 2724 : Lower64ShadowExtend(IRB, S2, getShadowTy(&I)); 2725 Value *V1 = I.getOperand(0); 2726 Value *V2 = I.getOperand(1); 2727 Value *Shift = IRB.CreateCall(I.getFunctionType(), I.getCalledOperand(), 2728 {IRB.CreateBitCast(S1, V1->getType()), V2}); 2729 Shift = IRB.CreateBitCast(Shift, getShadowTy(&I)); 2730 setShadow(&I, IRB.CreateOr(Shift, S2Conv)); 2731 setOriginForNaryOp(I); 2732 } 2733 2734 // Get an X86_MMX-sized vector type. 2735 Type *getMMXVectorTy(unsigned EltSizeInBits) { 2736 const unsigned X86_MMXSizeInBits = 64; 2737 assert(EltSizeInBits != 0 && (X86_MMXSizeInBits % EltSizeInBits) == 0 && 2738 "Illegal MMX vector element size"); 2739 return FixedVectorType::get(IntegerType::get(*MS.C, EltSizeInBits), 2740 X86_MMXSizeInBits / EltSizeInBits); 2741 } 2742 2743 // Returns a signed counterpart for an (un)signed-saturate-and-pack 2744 // intrinsic. 2745 Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) { 2746 switch (id) { 2747 case Intrinsic::x86_sse2_packsswb_128: 2748 case Intrinsic::x86_sse2_packuswb_128: 2749 return Intrinsic::x86_sse2_packsswb_128; 2750 2751 case Intrinsic::x86_sse2_packssdw_128: 2752 case Intrinsic::x86_sse41_packusdw: 2753 return Intrinsic::x86_sse2_packssdw_128; 2754 2755 case Intrinsic::x86_avx2_packsswb: 2756 case Intrinsic::x86_avx2_packuswb: 2757 return Intrinsic::x86_avx2_packsswb; 2758 2759 case Intrinsic::x86_avx2_packssdw: 2760 case Intrinsic::x86_avx2_packusdw: 2761 return Intrinsic::x86_avx2_packssdw; 2762 2763 case Intrinsic::x86_mmx_packsswb: 2764 case Intrinsic::x86_mmx_packuswb: 2765 return Intrinsic::x86_mmx_packsswb; 2766 2767 case Intrinsic::x86_mmx_packssdw: 2768 return Intrinsic::x86_mmx_packssdw; 2769 default: 2770 llvm_unreachable("unexpected intrinsic id"); 2771 } 2772 } 2773 2774 // Instrument vector pack intrinsic. 2775 // 2776 // This function instruments intrinsics like x86_mmx_packsswb, that 2777 // packs elements of 2 input vectors into half as many bits with saturation. 2778 // Shadow is propagated with the signed variant of the same intrinsic applied 2779 // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer). 2780 // EltSizeInBits is used only for x86mmx arguments. 2781 void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) { 2782 assert(I.getNumArgOperands() == 2); 2783 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy(); 2784 IRBuilder<> IRB(&I); 2785 Value *S1 = getShadow(&I, 0); 2786 Value *S2 = getShadow(&I, 1); 2787 assert(isX86_MMX || S1->getType()->isVectorTy()); 2788 2789 // SExt and ICmpNE below must apply to individual elements of input vectors. 2790 // In case of x86mmx arguments, cast them to appropriate vector types and 2791 // back. 2792 Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType(); 2793 if (isX86_MMX) { 2794 S1 = IRB.CreateBitCast(S1, T); 2795 S2 = IRB.CreateBitCast(S2, T); 2796 } 2797 Value *S1_ext = IRB.CreateSExt( 2798 IRB.CreateICmpNE(S1, Constant::getNullValue(T)), T); 2799 Value *S2_ext = IRB.CreateSExt( 2800 IRB.CreateICmpNE(S2, Constant::getNullValue(T)), T); 2801 if (isX86_MMX) { 2802 Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C); 2803 S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy); 2804 S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy); 2805 } 2806 2807 Function *ShadowFn = Intrinsic::getDeclaration( 2808 F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID())); 2809 2810 Value *S = 2811 IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack"); 2812 if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I)); 2813 setShadow(&I, S); 2814 setOriginForNaryOp(I); 2815 } 2816 2817 // Instrument sum-of-absolute-differences intrinsic. 2818 void handleVectorSadIntrinsic(IntrinsicInst &I) { 2819 const unsigned SignificantBitsPerResultElement = 16; 2820 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy(); 2821 Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType(); 2822 unsigned ZeroBitsPerResultElement = 2823 ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement; 2824 2825 IRBuilder<> IRB(&I); 2826 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1)); 2827 S = IRB.CreateBitCast(S, ResTy); 2828 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)), 2829 ResTy); 2830 S = IRB.CreateLShr(S, ZeroBitsPerResultElement); 2831 S = IRB.CreateBitCast(S, getShadowTy(&I)); 2832 setShadow(&I, S); 2833 setOriginForNaryOp(I); 2834 } 2835 2836 // Instrument multiply-add intrinsic. 2837 void handleVectorPmaddIntrinsic(IntrinsicInst &I, 2838 unsigned EltSizeInBits = 0) { 2839 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy(); 2840 Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType(); 2841 IRBuilder<> IRB(&I); 2842 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1)); 2843 S = IRB.CreateBitCast(S, ResTy); 2844 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)), 2845 ResTy); 2846 S = IRB.CreateBitCast(S, getShadowTy(&I)); 2847 setShadow(&I, S); 2848 setOriginForNaryOp(I); 2849 } 2850 2851 // Instrument compare-packed intrinsic. 2852 // Basically, an or followed by sext(icmp ne 0) to end up with all-zeros or 2853 // all-ones shadow. 2854 void handleVectorComparePackedIntrinsic(IntrinsicInst &I) { 2855 IRBuilder<> IRB(&I); 2856 Type *ResTy = getShadowTy(&I); 2857 Value *S0 = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1)); 2858 Value *S = IRB.CreateSExt( 2859 IRB.CreateICmpNE(S0, Constant::getNullValue(ResTy)), ResTy); 2860 setShadow(&I, S); 2861 setOriginForNaryOp(I); 2862 } 2863 2864 // Instrument compare-scalar intrinsic. 2865 // This handles both cmp* intrinsics which return the result in the first 2866 // element of a vector, and comi* which return the result as i32. 2867 void handleVectorCompareScalarIntrinsic(IntrinsicInst &I) { 2868 IRBuilder<> IRB(&I); 2869 Value *S0 = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1)); 2870 Value *S = LowerElementShadowExtend(IRB, S0, getShadowTy(&I)); 2871 setShadow(&I, S); 2872 setOriginForNaryOp(I); 2873 } 2874 2875 void handleStmxcsr(IntrinsicInst &I) { 2876 IRBuilder<> IRB(&I); 2877 Value* Addr = I.getArgOperand(0); 2878 Type *Ty = IRB.getInt32Ty(); 2879 Value *ShadowPtr = 2880 getShadowOriginPtr(Addr, IRB, Ty, Align(1), /*isStore*/ true).first; 2881 2882 IRB.CreateStore(getCleanShadow(Ty), 2883 IRB.CreatePointerCast(ShadowPtr, Ty->getPointerTo())); 2884 2885 if (ClCheckAccessAddress) 2886 insertShadowCheck(Addr, &I); 2887 } 2888 2889 void handleLdmxcsr(IntrinsicInst &I) { 2890 if (!InsertChecks) return; 2891 2892 IRBuilder<> IRB(&I); 2893 Value *Addr = I.getArgOperand(0); 2894 Type *Ty = IRB.getInt32Ty(); 2895 const Align Alignment = Align(1); 2896 Value *ShadowPtr, *OriginPtr; 2897 std::tie(ShadowPtr, OriginPtr) = 2898 getShadowOriginPtr(Addr, IRB, Ty, Alignment, /*isStore*/ false); 2899 2900 if (ClCheckAccessAddress) 2901 insertShadowCheck(Addr, &I); 2902 2903 Value *Shadow = IRB.CreateAlignedLoad(Ty, ShadowPtr, Alignment, "_ldmxcsr"); 2904 Value *Origin = MS.TrackOrigins ? IRB.CreateLoad(MS.OriginTy, OriginPtr) 2905 : getCleanOrigin(); 2906 insertShadowCheck(Shadow, Origin, &I); 2907 } 2908 2909 void handleMaskedStore(IntrinsicInst &I) { 2910 IRBuilder<> IRB(&I); 2911 Value *V = I.getArgOperand(0); 2912 Value *Addr = I.getArgOperand(1); 2913 const Align Alignment( 2914 cast<ConstantInt>(I.getArgOperand(2))->getZExtValue()); 2915 Value *Mask = I.getArgOperand(3); 2916 Value *Shadow = getShadow(V); 2917 2918 Value *ShadowPtr; 2919 Value *OriginPtr; 2920 std::tie(ShadowPtr, OriginPtr) = getShadowOriginPtr( 2921 Addr, IRB, Shadow->getType(), Alignment, /*isStore*/ true); 2922 2923 if (ClCheckAccessAddress) { 2924 insertShadowCheck(Addr, &I); 2925 // Uninitialized mask is kind of like uninitialized address, but not as 2926 // scary. 2927 insertShadowCheck(Mask, &I); 2928 } 2929 2930 IRB.CreateMaskedStore(Shadow, ShadowPtr, Alignment, Mask); 2931 2932 if (MS.TrackOrigins) { 2933 auto &DL = F.getParent()->getDataLayout(); 2934 paintOrigin(IRB, getOrigin(V), OriginPtr, 2935 DL.getTypeStoreSize(Shadow->getType()), 2936 std::max(Alignment, kMinOriginAlignment)); 2937 } 2938 } 2939 2940 bool handleMaskedLoad(IntrinsicInst &I) { 2941 IRBuilder<> IRB(&I); 2942 Value *Addr = I.getArgOperand(0); 2943 const Align Alignment( 2944 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 2945 Value *Mask = I.getArgOperand(2); 2946 Value *PassThru = I.getArgOperand(3); 2947 2948 Type *ShadowTy = getShadowTy(&I); 2949 Value *ShadowPtr, *OriginPtr; 2950 if (PropagateShadow) { 2951 std::tie(ShadowPtr, OriginPtr) = 2952 getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ false); 2953 setShadow(&I, IRB.CreateMaskedLoad(ShadowPtr, Alignment, Mask, 2954 getShadow(PassThru), "_msmaskedld")); 2955 } else { 2956 setShadow(&I, getCleanShadow(&I)); 2957 } 2958 2959 if (ClCheckAccessAddress) { 2960 insertShadowCheck(Addr, &I); 2961 insertShadowCheck(Mask, &I); 2962 } 2963 2964 if (MS.TrackOrigins) { 2965 if (PropagateShadow) { 2966 // Choose between PassThru's and the loaded value's origins. 2967 Value *MaskedPassThruShadow = IRB.CreateAnd( 2968 getShadow(PassThru), IRB.CreateSExt(IRB.CreateNeg(Mask), ShadowTy)); 2969 2970 Value *Acc = IRB.CreateExtractElement( 2971 MaskedPassThruShadow, ConstantInt::get(IRB.getInt32Ty(), 0)); 2972 for (int i = 1, 2973 N = cast<VectorType>(PassThru->getType())->getNumElements(); 2974 i < N; ++i) { 2975 Value *More = IRB.CreateExtractElement( 2976 MaskedPassThruShadow, ConstantInt::get(IRB.getInt32Ty(), i)); 2977 Acc = IRB.CreateOr(Acc, More); 2978 } 2979 2980 Value *Origin = IRB.CreateSelect( 2981 IRB.CreateICmpNE(Acc, Constant::getNullValue(Acc->getType())), 2982 getOrigin(PassThru), IRB.CreateLoad(MS.OriginTy, OriginPtr)); 2983 2984 setOrigin(&I, Origin); 2985 } else { 2986 setOrigin(&I, getCleanOrigin()); 2987 } 2988 } 2989 return true; 2990 } 2991 2992 // Instrument BMI / BMI2 intrinsics. 2993 // All of these intrinsics are Z = I(X, Y) 2994 // where the types of all operands and the result match, and are either i32 or i64. 2995 // The following instrumentation happens to work for all of them: 2996 // Sz = I(Sx, Y) | (sext (Sy != 0)) 2997 void handleBmiIntrinsic(IntrinsicInst &I) { 2998 IRBuilder<> IRB(&I); 2999 Type *ShadowTy = getShadowTy(&I); 3000 3001 // If any bit of the mask operand is poisoned, then the whole thing is. 3002 Value *SMask = getShadow(&I, 1); 3003 SMask = IRB.CreateSExt(IRB.CreateICmpNE(SMask, getCleanShadow(ShadowTy)), 3004 ShadowTy); 3005 // Apply the same intrinsic to the shadow of the first operand. 3006 Value *S = IRB.CreateCall(I.getCalledFunction(), 3007 {getShadow(&I, 0), I.getOperand(1)}); 3008 S = IRB.CreateOr(SMask, S); 3009 setShadow(&I, S); 3010 setOriginForNaryOp(I); 3011 } 3012 3013 SmallVector<int, 8> getPclmulMask(unsigned Width, bool OddElements) { 3014 SmallVector<int, 8> Mask; 3015 for (unsigned X = OddElements ? 1 : 0; X < Width; X += 2) { 3016 Mask.append(2, X); 3017 } 3018 return Mask; 3019 } 3020 3021 // Instrument pclmul intrinsics. 3022 // These intrinsics operate either on odd or on even elements of the input 3023 // vectors, depending on the constant in the 3rd argument, ignoring the rest. 3024 // Replace the unused elements with copies of the used ones, ex: 3025 // (0, 1, 2, 3) -> (0, 0, 2, 2) (even case) 3026 // or 3027 // (0, 1, 2, 3) -> (1, 1, 3, 3) (odd case) 3028 // and then apply the usual shadow combining logic. 3029 void handlePclmulIntrinsic(IntrinsicInst &I) { 3030 IRBuilder<> IRB(&I); 3031 Type *ShadowTy = getShadowTy(&I); 3032 unsigned Width = 3033 cast<VectorType>(I.getArgOperand(0)->getType())->getNumElements(); 3034 assert(isa<ConstantInt>(I.getArgOperand(2)) && 3035 "pclmul 3rd operand must be a constant"); 3036 unsigned Imm = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 3037 Value *Shuf0 = 3038 IRB.CreateShuffleVector(getShadow(&I, 0), UndefValue::get(ShadowTy), 3039 getPclmulMask(Width, Imm & 0x01)); 3040 Value *Shuf1 = 3041 IRB.CreateShuffleVector(getShadow(&I, 1), UndefValue::get(ShadowTy), 3042 getPclmulMask(Width, Imm & 0x10)); 3043 ShadowAndOriginCombiner SOC(this, IRB); 3044 SOC.Add(Shuf0, getOrigin(&I, 0)); 3045 SOC.Add(Shuf1, getOrigin(&I, 1)); 3046 SOC.Done(&I); 3047 } 3048 3049 // Instrument _mm_*_sd intrinsics 3050 void handleUnarySdIntrinsic(IntrinsicInst &I) { 3051 IRBuilder<> IRB(&I); 3052 Value *First = getShadow(&I, 0); 3053 Value *Second = getShadow(&I, 1); 3054 // High word of first operand, low word of second 3055 Value *Shadow = 3056 IRB.CreateShuffleVector(First, Second, llvm::makeArrayRef<int>({2, 1})); 3057 3058 setShadow(&I, Shadow); 3059 setOriginForNaryOp(I); 3060 } 3061 3062 void handleBinarySdIntrinsic(IntrinsicInst &I) { 3063 IRBuilder<> IRB(&I); 3064 Value *First = getShadow(&I, 0); 3065 Value *Second = getShadow(&I, 1); 3066 Value *OrShadow = IRB.CreateOr(First, Second); 3067 // High word of first operand, low word of both OR'd together 3068 Value *Shadow = IRB.CreateShuffleVector(First, OrShadow, 3069 llvm::makeArrayRef<int>({2, 1})); 3070 3071 setShadow(&I, Shadow); 3072 setOriginForNaryOp(I); 3073 } 3074 3075 void visitIntrinsicInst(IntrinsicInst &I) { 3076 switch (I.getIntrinsicID()) { 3077 case Intrinsic::lifetime_start: 3078 handleLifetimeStart(I); 3079 break; 3080 case Intrinsic::launder_invariant_group: 3081 case Intrinsic::strip_invariant_group: 3082 handleInvariantGroup(I); 3083 break; 3084 case Intrinsic::bswap: 3085 handleBswap(I); 3086 break; 3087 case Intrinsic::masked_store: 3088 handleMaskedStore(I); 3089 break; 3090 case Intrinsic::masked_load: 3091 handleMaskedLoad(I); 3092 break; 3093 case Intrinsic::x86_sse_stmxcsr: 3094 handleStmxcsr(I); 3095 break; 3096 case Intrinsic::x86_sse_ldmxcsr: 3097 handleLdmxcsr(I); 3098 break; 3099 case Intrinsic::x86_avx512_vcvtsd2usi64: 3100 case Intrinsic::x86_avx512_vcvtsd2usi32: 3101 case Intrinsic::x86_avx512_vcvtss2usi64: 3102 case Intrinsic::x86_avx512_vcvtss2usi32: 3103 case Intrinsic::x86_avx512_cvttss2usi64: 3104 case Intrinsic::x86_avx512_cvttss2usi: 3105 case Intrinsic::x86_avx512_cvttsd2usi64: 3106 case Intrinsic::x86_avx512_cvttsd2usi: 3107 case Intrinsic::x86_avx512_cvtusi2ss: 3108 case Intrinsic::x86_avx512_cvtusi642sd: 3109 case Intrinsic::x86_avx512_cvtusi642ss: 3110 case Intrinsic::x86_sse2_cvtsd2si64: 3111 case Intrinsic::x86_sse2_cvtsd2si: 3112 case Intrinsic::x86_sse2_cvtsd2ss: 3113 case Intrinsic::x86_sse2_cvttsd2si64: 3114 case Intrinsic::x86_sse2_cvttsd2si: 3115 case Intrinsic::x86_sse_cvtss2si64: 3116 case Intrinsic::x86_sse_cvtss2si: 3117 case Intrinsic::x86_sse_cvttss2si64: 3118 case Intrinsic::x86_sse_cvttss2si: 3119 handleVectorConvertIntrinsic(I, 1); 3120 break; 3121 case Intrinsic::x86_sse_cvtps2pi: 3122 case Intrinsic::x86_sse_cvttps2pi: 3123 handleVectorConvertIntrinsic(I, 2); 3124 break; 3125 3126 case Intrinsic::x86_avx512_psll_w_512: 3127 case Intrinsic::x86_avx512_psll_d_512: 3128 case Intrinsic::x86_avx512_psll_q_512: 3129 case Intrinsic::x86_avx512_pslli_w_512: 3130 case Intrinsic::x86_avx512_pslli_d_512: 3131 case Intrinsic::x86_avx512_pslli_q_512: 3132 case Intrinsic::x86_avx512_psrl_w_512: 3133 case Intrinsic::x86_avx512_psrl_d_512: 3134 case Intrinsic::x86_avx512_psrl_q_512: 3135 case Intrinsic::x86_avx512_psra_w_512: 3136 case Intrinsic::x86_avx512_psra_d_512: 3137 case Intrinsic::x86_avx512_psra_q_512: 3138 case Intrinsic::x86_avx512_psrli_w_512: 3139 case Intrinsic::x86_avx512_psrli_d_512: 3140 case Intrinsic::x86_avx512_psrli_q_512: 3141 case Intrinsic::x86_avx512_psrai_w_512: 3142 case Intrinsic::x86_avx512_psrai_d_512: 3143 case Intrinsic::x86_avx512_psrai_q_512: 3144 case Intrinsic::x86_avx512_psra_q_256: 3145 case Intrinsic::x86_avx512_psra_q_128: 3146 case Intrinsic::x86_avx512_psrai_q_256: 3147 case Intrinsic::x86_avx512_psrai_q_128: 3148 case Intrinsic::x86_avx2_psll_w: 3149 case Intrinsic::x86_avx2_psll_d: 3150 case Intrinsic::x86_avx2_psll_q: 3151 case Intrinsic::x86_avx2_pslli_w: 3152 case Intrinsic::x86_avx2_pslli_d: 3153 case Intrinsic::x86_avx2_pslli_q: 3154 case Intrinsic::x86_avx2_psrl_w: 3155 case Intrinsic::x86_avx2_psrl_d: 3156 case Intrinsic::x86_avx2_psrl_q: 3157 case Intrinsic::x86_avx2_psra_w: 3158 case Intrinsic::x86_avx2_psra_d: 3159 case Intrinsic::x86_avx2_psrli_w: 3160 case Intrinsic::x86_avx2_psrli_d: 3161 case Intrinsic::x86_avx2_psrli_q: 3162 case Intrinsic::x86_avx2_psrai_w: 3163 case Intrinsic::x86_avx2_psrai_d: 3164 case Intrinsic::x86_sse2_psll_w: 3165 case Intrinsic::x86_sse2_psll_d: 3166 case Intrinsic::x86_sse2_psll_q: 3167 case Intrinsic::x86_sse2_pslli_w: 3168 case Intrinsic::x86_sse2_pslli_d: 3169 case Intrinsic::x86_sse2_pslli_q: 3170 case Intrinsic::x86_sse2_psrl_w: 3171 case Intrinsic::x86_sse2_psrl_d: 3172 case Intrinsic::x86_sse2_psrl_q: 3173 case Intrinsic::x86_sse2_psra_w: 3174 case Intrinsic::x86_sse2_psra_d: 3175 case Intrinsic::x86_sse2_psrli_w: 3176 case Intrinsic::x86_sse2_psrli_d: 3177 case Intrinsic::x86_sse2_psrli_q: 3178 case Intrinsic::x86_sse2_psrai_w: 3179 case Intrinsic::x86_sse2_psrai_d: 3180 case Intrinsic::x86_mmx_psll_w: 3181 case Intrinsic::x86_mmx_psll_d: 3182 case Intrinsic::x86_mmx_psll_q: 3183 case Intrinsic::x86_mmx_pslli_w: 3184 case Intrinsic::x86_mmx_pslli_d: 3185 case Intrinsic::x86_mmx_pslli_q: 3186 case Intrinsic::x86_mmx_psrl_w: 3187 case Intrinsic::x86_mmx_psrl_d: 3188 case Intrinsic::x86_mmx_psrl_q: 3189 case Intrinsic::x86_mmx_psra_w: 3190 case Intrinsic::x86_mmx_psra_d: 3191 case Intrinsic::x86_mmx_psrli_w: 3192 case Intrinsic::x86_mmx_psrli_d: 3193 case Intrinsic::x86_mmx_psrli_q: 3194 case Intrinsic::x86_mmx_psrai_w: 3195 case Intrinsic::x86_mmx_psrai_d: 3196 handleVectorShiftIntrinsic(I, /* Variable */ false); 3197 break; 3198 case Intrinsic::x86_avx2_psllv_d: 3199 case Intrinsic::x86_avx2_psllv_d_256: 3200 case Intrinsic::x86_avx512_psllv_d_512: 3201 case Intrinsic::x86_avx2_psllv_q: 3202 case Intrinsic::x86_avx2_psllv_q_256: 3203 case Intrinsic::x86_avx512_psllv_q_512: 3204 case Intrinsic::x86_avx2_psrlv_d: 3205 case Intrinsic::x86_avx2_psrlv_d_256: 3206 case Intrinsic::x86_avx512_psrlv_d_512: 3207 case Intrinsic::x86_avx2_psrlv_q: 3208 case Intrinsic::x86_avx2_psrlv_q_256: 3209 case Intrinsic::x86_avx512_psrlv_q_512: 3210 case Intrinsic::x86_avx2_psrav_d: 3211 case Intrinsic::x86_avx2_psrav_d_256: 3212 case Intrinsic::x86_avx512_psrav_d_512: 3213 case Intrinsic::x86_avx512_psrav_q_128: 3214 case Intrinsic::x86_avx512_psrav_q_256: 3215 case Intrinsic::x86_avx512_psrav_q_512: 3216 handleVectorShiftIntrinsic(I, /* Variable */ true); 3217 break; 3218 3219 case Intrinsic::x86_sse2_packsswb_128: 3220 case Intrinsic::x86_sse2_packssdw_128: 3221 case Intrinsic::x86_sse2_packuswb_128: 3222 case Intrinsic::x86_sse41_packusdw: 3223 case Intrinsic::x86_avx2_packsswb: 3224 case Intrinsic::x86_avx2_packssdw: 3225 case Intrinsic::x86_avx2_packuswb: 3226 case Intrinsic::x86_avx2_packusdw: 3227 handleVectorPackIntrinsic(I); 3228 break; 3229 3230 case Intrinsic::x86_mmx_packsswb: 3231 case Intrinsic::x86_mmx_packuswb: 3232 handleVectorPackIntrinsic(I, 16); 3233 break; 3234 3235 case Intrinsic::x86_mmx_packssdw: 3236 handleVectorPackIntrinsic(I, 32); 3237 break; 3238 3239 case Intrinsic::x86_mmx_psad_bw: 3240 case Intrinsic::x86_sse2_psad_bw: 3241 case Intrinsic::x86_avx2_psad_bw: 3242 handleVectorSadIntrinsic(I); 3243 break; 3244 3245 case Intrinsic::x86_sse2_pmadd_wd: 3246 case Intrinsic::x86_avx2_pmadd_wd: 3247 case Intrinsic::x86_ssse3_pmadd_ub_sw_128: 3248 case Intrinsic::x86_avx2_pmadd_ub_sw: 3249 handleVectorPmaddIntrinsic(I); 3250 break; 3251 3252 case Intrinsic::x86_ssse3_pmadd_ub_sw: 3253 handleVectorPmaddIntrinsic(I, 8); 3254 break; 3255 3256 case Intrinsic::x86_mmx_pmadd_wd: 3257 handleVectorPmaddIntrinsic(I, 16); 3258 break; 3259 3260 case Intrinsic::x86_sse_cmp_ss: 3261 case Intrinsic::x86_sse2_cmp_sd: 3262 case Intrinsic::x86_sse_comieq_ss: 3263 case Intrinsic::x86_sse_comilt_ss: 3264 case Intrinsic::x86_sse_comile_ss: 3265 case Intrinsic::x86_sse_comigt_ss: 3266 case Intrinsic::x86_sse_comige_ss: 3267 case Intrinsic::x86_sse_comineq_ss: 3268 case Intrinsic::x86_sse_ucomieq_ss: 3269 case Intrinsic::x86_sse_ucomilt_ss: 3270 case Intrinsic::x86_sse_ucomile_ss: 3271 case Intrinsic::x86_sse_ucomigt_ss: 3272 case Intrinsic::x86_sse_ucomige_ss: 3273 case Intrinsic::x86_sse_ucomineq_ss: 3274 case Intrinsic::x86_sse2_comieq_sd: 3275 case Intrinsic::x86_sse2_comilt_sd: 3276 case Intrinsic::x86_sse2_comile_sd: 3277 case Intrinsic::x86_sse2_comigt_sd: 3278 case Intrinsic::x86_sse2_comige_sd: 3279 case Intrinsic::x86_sse2_comineq_sd: 3280 case Intrinsic::x86_sse2_ucomieq_sd: 3281 case Intrinsic::x86_sse2_ucomilt_sd: 3282 case Intrinsic::x86_sse2_ucomile_sd: 3283 case Intrinsic::x86_sse2_ucomigt_sd: 3284 case Intrinsic::x86_sse2_ucomige_sd: 3285 case Intrinsic::x86_sse2_ucomineq_sd: 3286 handleVectorCompareScalarIntrinsic(I); 3287 break; 3288 3289 case Intrinsic::x86_sse_cmp_ps: 3290 case Intrinsic::x86_sse2_cmp_pd: 3291 // FIXME: For x86_avx_cmp_pd_256 and x86_avx_cmp_ps_256 this function 3292 // generates reasonably looking IR that fails in the backend with "Do not 3293 // know how to split the result of this operator!". 3294 handleVectorComparePackedIntrinsic(I); 3295 break; 3296 3297 case Intrinsic::x86_bmi_bextr_32: 3298 case Intrinsic::x86_bmi_bextr_64: 3299 case Intrinsic::x86_bmi_bzhi_32: 3300 case Intrinsic::x86_bmi_bzhi_64: 3301 case Intrinsic::x86_bmi_pdep_32: 3302 case Intrinsic::x86_bmi_pdep_64: 3303 case Intrinsic::x86_bmi_pext_32: 3304 case Intrinsic::x86_bmi_pext_64: 3305 handleBmiIntrinsic(I); 3306 break; 3307 3308 case Intrinsic::x86_pclmulqdq: 3309 case Intrinsic::x86_pclmulqdq_256: 3310 case Intrinsic::x86_pclmulqdq_512: 3311 handlePclmulIntrinsic(I); 3312 break; 3313 3314 case Intrinsic::x86_sse41_round_sd: 3315 handleUnarySdIntrinsic(I); 3316 break; 3317 case Intrinsic::x86_sse2_max_sd: 3318 case Intrinsic::x86_sse2_min_sd: 3319 handleBinarySdIntrinsic(I); 3320 break; 3321 3322 case Intrinsic::is_constant: 3323 // The result of llvm.is.constant() is always defined. 3324 setShadow(&I, getCleanShadow(&I)); 3325 setOrigin(&I, getCleanOrigin()); 3326 break; 3327 3328 default: 3329 if (!handleUnknownIntrinsic(I)) 3330 visitInstruction(I); 3331 break; 3332 } 3333 } 3334 3335 void visitCallBase(CallBase &CB) { 3336 assert(!CB.getMetadata("nosanitize")); 3337 if (CB.isInlineAsm()) { 3338 // For inline asm (either a call to asm function, or callbr instruction), 3339 // do the usual thing: check argument shadow and mark all outputs as 3340 // clean. Note that any side effects of the inline asm that are not 3341 // immediately visible in its constraints are not handled. 3342 if (ClHandleAsmConservative && MS.CompileKernel) 3343 visitAsmInstruction(CB); 3344 else 3345 visitInstruction(CB); 3346 return; 3347 } 3348 if (auto *Call = dyn_cast<CallInst>(&CB)) { 3349 assert(!isa<IntrinsicInst>(Call) && "intrinsics are handled elsewhere"); 3350 3351 // We are going to insert code that relies on the fact that the callee 3352 // will become a non-readonly function after it is instrumented by us. To 3353 // prevent this code from being optimized out, mark that function 3354 // non-readonly in advance. 3355 if (Function *Func = Call->getCalledFunction()) { 3356 // Clear out readonly/readnone attributes. 3357 AttrBuilder B; 3358 B.addAttribute(Attribute::ReadOnly) 3359 .addAttribute(Attribute::ReadNone) 3360 .addAttribute(Attribute::WriteOnly) 3361 .addAttribute(Attribute::ArgMemOnly) 3362 .addAttribute(Attribute::Speculatable); 3363 Func->removeAttributes(AttributeList::FunctionIndex, B); 3364 } 3365 3366 maybeMarkSanitizerLibraryCallNoBuiltin(Call, TLI); 3367 } 3368 IRBuilder<> IRB(&CB); 3369 3370 unsigned ArgOffset = 0; 3371 LLVM_DEBUG(dbgs() << " CallSite: " << CB << "\n"); 3372 for (auto ArgIt = CB.arg_begin(), End = CB.arg_end(); ArgIt != End; 3373 ++ArgIt) { 3374 Value *A = *ArgIt; 3375 unsigned i = ArgIt - CB.arg_begin(); 3376 if (!A->getType()->isSized()) { 3377 LLVM_DEBUG(dbgs() << "Arg " << i << " is not sized: " << CB << "\n"); 3378 continue; 3379 } 3380 unsigned Size = 0; 3381 Value *Store = nullptr; 3382 // Compute the Shadow for arg even if it is ByVal, because 3383 // in that case getShadow() will copy the actual arg shadow to 3384 // __msan_param_tls. 3385 Value *ArgShadow = getShadow(A); 3386 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset); 3387 LLVM_DEBUG(dbgs() << " Arg#" << i << ": " << *A 3388 << " Shadow: " << *ArgShadow << "\n"); 3389 bool ArgIsInitialized = false; 3390 const DataLayout &DL = F.getParent()->getDataLayout(); 3391 if (CB.paramHasAttr(i, Attribute::ByVal)) { 3392 assert(A->getType()->isPointerTy() && 3393 "ByVal argument is not a pointer!"); 3394 Size = DL.getTypeAllocSize(CB.getParamByValType(i)); 3395 if (ArgOffset + Size > kParamTLSSize) break; 3396 const MaybeAlign ParamAlignment(CB.getParamAlign(i)); 3397 MaybeAlign Alignment = llvm::None; 3398 if (ParamAlignment) 3399 Alignment = std::min(*ParamAlignment, kShadowTLSAlignment); 3400 Value *AShadowPtr = 3401 getShadowOriginPtr(A, IRB, IRB.getInt8Ty(), Alignment, 3402 /*isStore*/ false) 3403 .first; 3404 3405 Store = IRB.CreateMemCpy(ArgShadowBase, Alignment, AShadowPtr, 3406 Alignment, Size); 3407 // TODO(glider): need to copy origins. 3408 } else { 3409 Size = DL.getTypeAllocSize(A->getType()); 3410 if (ArgOffset + Size > kParamTLSSize) break; 3411 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase, 3412 kShadowTLSAlignment); 3413 Constant *Cst = dyn_cast<Constant>(ArgShadow); 3414 if (Cst && Cst->isNullValue()) ArgIsInitialized = true; 3415 } 3416 if (MS.TrackOrigins && !ArgIsInitialized) 3417 IRB.CreateStore(getOrigin(A), 3418 getOriginPtrForArgument(A, IRB, ArgOffset)); 3419 (void)Store; 3420 assert(Size != 0 && Store != nullptr); 3421 LLVM_DEBUG(dbgs() << " Param:" << *Store << "\n"); 3422 ArgOffset += alignTo(Size, 8); 3423 } 3424 LLVM_DEBUG(dbgs() << " done with call args\n"); 3425 3426 FunctionType *FT = CB.getFunctionType(); 3427 if (FT->isVarArg()) { 3428 VAHelper->visitCallBase(CB, IRB); 3429 } 3430 3431 // Now, get the shadow for the RetVal. 3432 if (!CB.getType()->isSized()) 3433 return; 3434 // Don't emit the epilogue for musttail call returns. 3435 if (isa<CallInst>(CB) && cast<CallInst>(CB).isMustTailCall()) 3436 return; 3437 IRBuilder<> IRBBefore(&CB); 3438 // Until we have full dynamic coverage, make sure the retval shadow is 0. 3439 Value *Base = getShadowPtrForRetval(&CB, IRBBefore); 3440 IRBBefore.CreateAlignedStore(getCleanShadow(&CB), Base, 3441 kShadowTLSAlignment); 3442 BasicBlock::iterator NextInsn; 3443 if (isa<CallInst>(CB)) { 3444 NextInsn = ++CB.getIterator(); 3445 assert(NextInsn != CB.getParent()->end()); 3446 } else { 3447 BasicBlock *NormalDest = cast<InvokeInst>(CB).getNormalDest(); 3448 if (!NormalDest->getSinglePredecessor()) { 3449 // FIXME: this case is tricky, so we are just conservative here. 3450 // Perhaps we need to split the edge between this BB and NormalDest, 3451 // but a naive attempt to use SplitEdge leads to a crash. 3452 setShadow(&CB, getCleanShadow(&CB)); 3453 setOrigin(&CB, getCleanOrigin()); 3454 return; 3455 } 3456 // FIXME: NextInsn is likely in a basic block that has not been visited yet. 3457 // Anything inserted there will be instrumented by MSan later! 3458 NextInsn = NormalDest->getFirstInsertionPt(); 3459 assert(NextInsn != NormalDest->end() && 3460 "Could not find insertion point for retval shadow load"); 3461 } 3462 IRBuilder<> IRBAfter(&*NextInsn); 3463 Value *RetvalShadow = IRBAfter.CreateAlignedLoad( 3464 getShadowTy(&CB), getShadowPtrForRetval(&CB, IRBAfter), 3465 kShadowTLSAlignment, "_msret"); 3466 setShadow(&CB, RetvalShadow); 3467 if (MS.TrackOrigins) 3468 setOrigin(&CB, IRBAfter.CreateLoad(MS.OriginTy, 3469 getOriginPtrForRetval(IRBAfter))); 3470 } 3471 3472 bool isAMustTailRetVal(Value *RetVal) { 3473 if (auto *I = dyn_cast<BitCastInst>(RetVal)) { 3474 RetVal = I->getOperand(0); 3475 } 3476 if (auto *I = dyn_cast<CallInst>(RetVal)) { 3477 return I->isMustTailCall(); 3478 } 3479 return false; 3480 } 3481 3482 void visitReturnInst(ReturnInst &I) { 3483 IRBuilder<> IRB(&I); 3484 Value *RetVal = I.getReturnValue(); 3485 if (!RetVal) return; 3486 // Don't emit the epilogue for musttail call returns. 3487 if (isAMustTailRetVal(RetVal)) return; 3488 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB); 3489 if (CheckReturnValue) { 3490 insertShadowCheck(RetVal, &I); 3491 Value *Shadow = getCleanShadow(RetVal); 3492 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment); 3493 } else { 3494 Value *Shadow = getShadow(RetVal); 3495 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment); 3496 if (MS.TrackOrigins) 3497 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB)); 3498 } 3499 } 3500 3501 void visitPHINode(PHINode &I) { 3502 IRBuilder<> IRB(&I); 3503 if (!PropagateShadow) { 3504 setShadow(&I, getCleanShadow(&I)); 3505 setOrigin(&I, getCleanOrigin()); 3506 return; 3507 } 3508 3509 ShadowPHINodes.push_back(&I); 3510 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(), 3511 "_msphi_s")); 3512 if (MS.TrackOrigins) 3513 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(), 3514 "_msphi_o")); 3515 } 3516 3517 Value *getLocalVarDescription(AllocaInst &I) { 3518 SmallString<2048> StackDescriptionStorage; 3519 raw_svector_ostream StackDescription(StackDescriptionStorage); 3520 // We create a string with a description of the stack allocation and 3521 // pass it into __msan_set_alloca_origin. 3522 // It will be printed by the run-time if stack-originated UMR is found. 3523 // The first 4 bytes of the string are set to '----' and will be replaced 3524 // by __msan_va_arg_overflow_size_tls at the first call. 3525 StackDescription << "----" << I.getName() << "@" << F.getName(); 3526 return createPrivateNonConstGlobalForString(*F.getParent(), 3527 StackDescription.str()); 3528 } 3529 3530 void poisonAllocaUserspace(AllocaInst &I, IRBuilder<> &IRB, Value *Len) { 3531 if (PoisonStack && ClPoisonStackWithCall) { 3532 IRB.CreateCall(MS.MsanPoisonStackFn, 3533 {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len}); 3534 } else { 3535 Value *ShadowBase, *OriginBase; 3536 std::tie(ShadowBase, OriginBase) = getShadowOriginPtr( 3537 &I, IRB, IRB.getInt8Ty(), Align(1), /*isStore*/ true); 3538 3539 Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0); 3540 IRB.CreateMemSet(ShadowBase, PoisonValue, Len, 3541 MaybeAlign(I.getAlignment())); 3542 } 3543 3544 if (PoisonStack && MS.TrackOrigins) { 3545 Value *Descr = getLocalVarDescription(I); 3546 IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn, 3547 {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len, 3548 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()), 3549 IRB.CreatePointerCast(&F, MS.IntptrTy)}); 3550 } 3551 } 3552 3553 void poisonAllocaKmsan(AllocaInst &I, IRBuilder<> &IRB, Value *Len) { 3554 Value *Descr = getLocalVarDescription(I); 3555 if (PoisonStack) { 3556 IRB.CreateCall(MS.MsanPoisonAllocaFn, 3557 {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len, 3558 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy())}); 3559 } else { 3560 IRB.CreateCall(MS.MsanUnpoisonAllocaFn, 3561 {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len}); 3562 } 3563 } 3564 3565 void instrumentAlloca(AllocaInst &I, Instruction *InsPoint = nullptr) { 3566 if (!InsPoint) 3567 InsPoint = &I; 3568 IRBuilder<> IRB(InsPoint->getNextNode()); 3569 const DataLayout &DL = F.getParent()->getDataLayout(); 3570 uint64_t TypeSize = DL.getTypeAllocSize(I.getAllocatedType()); 3571 Value *Len = ConstantInt::get(MS.IntptrTy, TypeSize); 3572 if (I.isArrayAllocation()) 3573 Len = IRB.CreateMul(Len, I.getArraySize()); 3574 3575 if (MS.CompileKernel) 3576 poisonAllocaKmsan(I, IRB, Len); 3577 else 3578 poisonAllocaUserspace(I, IRB, Len); 3579 } 3580 3581 void visitAllocaInst(AllocaInst &I) { 3582 setShadow(&I, getCleanShadow(&I)); 3583 setOrigin(&I, getCleanOrigin()); 3584 // We'll get to this alloca later unless it's poisoned at the corresponding 3585 // llvm.lifetime.start. 3586 AllocaSet.insert(&I); 3587 } 3588 3589 void visitSelectInst(SelectInst& I) { 3590 IRBuilder<> IRB(&I); 3591 // a = select b, c, d 3592 Value *B = I.getCondition(); 3593 Value *C = I.getTrueValue(); 3594 Value *D = I.getFalseValue(); 3595 Value *Sb = getShadow(B); 3596 Value *Sc = getShadow(C); 3597 Value *Sd = getShadow(D); 3598 3599 // Result shadow if condition shadow is 0. 3600 Value *Sa0 = IRB.CreateSelect(B, Sc, Sd); 3601 Value *Sa1; 3602 if (I.getType()->isAggregateType()) { 3603 // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do 3604 // an extra "select". This results in much more compact IR. 3605 // Sa = select Sb, poisoned, (select b, Sc, Sd) 3606 Sa1 = getPoisonedShadow(getShadowTy(I.getType())); 3607 } else { 3608 // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ] 3609 // If Sb (condition is poisoned), look for bits in c and d that are equal 3610 // and both unpoisoned. 3611 // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd. 3612 3613 // Cast arguments to shadow-compatible type. 3614 C = CreateAppToShadowCast(IRB, C); 3615 D = CreateAppToShadowCast(IRB, D); 3616 3617 // Result shadow if condition shadow is 1. 3618 Sa1 = IRB.CreateOr({IRB.CreateXor(C, D), Sc, Sd}); 3619 } 3620 Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select"); 3621 setShadow(&I, Sa); 3622 if (MS.TrackOrigins) { 3623 // Origins are always i32, so any vector conditions must be flattened. 3624 // FIXME: consider tracking vector origins for app vectors? 3625 if (B->getType()->isVectorTy()) { 3626 Type *FlatTy = getShadowTyNoVec(B->getType()); 3627 B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy), 3628 ConstantInt::getNullValue(FlatTy)); 3629 Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy), 3630 ConstantInt::getNullValue(FlatTy)); 3631 } 3632 // a = select b, c, d 3633 // Oa = Sb ? Ob : (b ? Oc : Od) 3634 setOrigin( 3635 &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()), 3636 IRB.CreateSelect(B, getOrigin(I.getTrueValue()), 3637 getOrigin(I.getFalseValue())))); 3638 } 3639 } 3640 3641 void visitLandingPadInst(LandingPadInst &I) { 3642 // Do nothing. 3643 // See https://github.com/google/sanitizers/issues/504 3644 setShadow(&I, getCleanShadow(&I)); 3645 setOrigin(&I, getCleanOrigin()); 3646 } 3647 3648 void visitCatchSwitchInst(CatchSwitchInst &I) { 3649 setShadow(&I, getCleanShadow(&I)); 3650 setOrigin(&I, getCleanOrigin()); 3651 } 3652 3653 void visitFuncletPadInst(FuncletPadInst &I) { 3654 setShadow(&I, getCleanShadow(&I)); 3655 setOrigin(&I, getCleanOrigin()); 3656 } 3657 3658 void visitGetElementPtrInst(GetElementPtrInst &I) { 3659 handleShadowOr(I); 3660 } 3661 3662 void visitExtractValueInst(ExtractValueInst &I) { 3663 IRBuilder<> IRB(&I); 3664 Value *Agg = I.getAggregateOperand(); 3665 LLVM_DEBUG(dbgs() << "ExtractValue: " << I << "\n"); 3666 Value *AggShadow = getShadow(Agg); 3667 LLVM_DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n"); 3668 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices()); 3669 LLVM_DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n"); 3670 setShadow(&I, ResShadow); 3671 setOriginForNaryOp(I); 3672 } 3673 3674 void visitInsertValueInst(InsertValueInst &I) { 3675 IRBuilder<> IRB(&I); 3676 LLVM_DEBUG(dbgs() << "InsertValue: " << I << "\n"); 3677 Value *AggShadow = getShadow(I.getAggregateOperand()); 3678 Value *InsShadow = getShadow(I.getInsertedValueOperand()); 3679 LLVM_DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n"); 3680 LLVM_DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n"); 3681 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices()); 3682 LLVM_DEBUG(dbgs() << " Res: " << *Res << "\n"); 3683 setShadow(&I, Res); 3684 setOriginForNaryOp(I); 3685 } 3686 3687 void dumpInst(Instruction &I) { 3688 if (CallInst *CI = dyn_cast<CallInst>(&I)) { 3689 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n"; 3690 } else { 3691 errs() << "ZZZ " << I.getOpcodeName() << "\n"; 3692 } 3693 errs() << "QQQ " << I << "\n"; 3694 } 3695 3696 void visitResumeInst(ResumeInst &I) { 3697 LLVM_DEBUG(dbgs() << "Resume: " << I << "\n"); 3698 // Nothing to do here. 3699 } 3700 3701 void visitCleanupReturnInst(CleanupReturnInst &CRI) { 3702 LLVM_DEBUG(dbgs() << "CleanupReturn: " << CRI << "\n"); 3703 // Nothing to do here. 3704 } 3705 3706 void visitCatchReturnInst(CatchReturnInst &CRI) { 3707 LLVM_DEBUG(dbgs() << "CatchReturn: " << CRI << "\n"); 3708 // Nothing to do here. 3709 } 3710 3711 void instrumentAsmArgument(Value *Operand, Instruction &I, IRBuilder<> &IRB, 3712 const DataLayout &DL, bool isOutput) { 3713 // For each assembly argument, we check its value for being initialized. 3714 // If the argument is a pointer, we assume it points to a single element 3715 // of the corresponding type (or to a 8-byte word, if the type is unsized). 3716 // Each such pointer is instrumented with a call to the runtime library. 3717 Type *OpType = Operand->getType(); 3718 // Check the operand value itself. 3719 insertShadowCheck(Operand, &I); 3720 if (!OpType->isPointerTy() || !isOutput) { 3721 assert(!isOutput); 3722 return; 3723 } 3724 Type *ElType = OpType->getPointerElementType(); 3725 if (!ElType->isSized()) 3726 return; 3727 int Size = DL.getTypeStoreSize(ElType); 3728 Value *Ptr = IRB.CreatePointerCast(Operand, IRB.getInt8PtrTy()); 3729 Value *SizeVal = ConstantInt::get(MS.IntptrTy, Size); 3730 IRB.CreateCall(MS.MsanInstrumentAsmStoreFn, {Ptr, SizeVal}); 3731 } 3732 3733 /// Get the number of output arguments returned by pointers. 3734 int getNumOutputArgs(InlineAsm *IA, CallBase *CB) { 3735 int NumRetOutputs = 0; 3736 int NumOutputs = 0; 3737 Type *RetTy = cast<Value>(CB)->getType(); 3738 if (!RetTy->isVoidTy()) { 3739 // Register outputs are returned via the CallInst return value. 3740 auto *ST = dyn_cast<StructType>(RetTy); 3741 if (ST) 3742 NumRetOutputs = ST->getNumElements(); 3743 else 3744 NumRetOutputs = 1; 3745 } 3746 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints(); 3747 for (size_t i = 0, n = Constraints.size(); i < n; i++) { 3748 InlineAsm::ConstraintInfo Info = Constraints[i]; 3749 switch (Info.Type) { 3750 case InlineAsm::isOutput: 3751 NumOutputs++; 3752 break; 3753 default: 3754 break; 3755 } 3756 } 3757 return NumOutputs - NumRetOutputs; 3758 } 3759 3760 void visitAsmInstruction(Instruction &I) { 3761 // Conservative inline assembly handling: check for poisoned shadow of 3762 // asm() arguments, then unpoison the result and all the memory locations 3763 // pointed to by those arguments. 3764 // An inline asm() statement in C++ contains lists of input and output 3765 // arguments used by the assembly code. These are mapped to operands of the 3766 // CallInst as follows: 3767 // - nR register outputs ("=r) are returned by value in a single structure 3768 // (SSA value of the CallInst); 3769 // - nO other outputs ("=m" and others) are returned by pointer as first 3770 // nO operands of the CallInst; 3771 // - nI inputs ("r", "m" and others) are passed to CallInst as the 3772 // remaining nI operands. 3773 // The total number of asm() arguments in the source is nR+nO+nI, and the 3774 // corresponding CallInst has nO+nI+1 operands (the last operand is the 3775 // function to be called). 3776 const DataLayout &DL = F.getParent()->getDataLayout(); 3777 CallBase *CB = cast<CallBase>(&I); 3778 IRBuilder<> IRB(&I); 3779 InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand()); 3780 int OutputArgs = getNumOutputArgs(IA, CB); 3781 // The last operand of a CallInst is the function itself. 3782 int NumOperands = CB->getNumOperands() - 1; 3783 3784 // Check input arguments. Doing so before unpoisoning output arguments, so 3785 // that we won't overwrite uninit values before checking them. 3786 for (int i = OutputArgs; i < NumOperands; i++) { 3787 Value *Operand = CB->getOperand(i); 3788 instrumentAsmArgument(Operand, I, IRB, DL, /*isOutput*/ false); 3789 } 3790 // Unpoison output arguments. This must happen before the actual InlineAsm 3791 // call, so that the shadow for memory published in the asm() statement 3792 // remains valid. 3793 for (int i = 0; i < OutputArgs; i++) { 3794 Value *Operand = CB->getOperand(i); 3795 instrumentAsmArgument(Operand, I, IRB, DL, /*isOutput*/ true); 3796 } 3797 3798 setShadow(&I, getCleanShadow(&I)); 3799 setOrigin(&I, getCleanOrigin()); 3800 } 3801 3802 void visitInstruction(Instruction &I) { 3803 // Everything else: stop propagating and check for poisoned shadow. 3804 if (ClDumpStrictInstructions) 3805 dumpInst(I); 3806 LLVM_DEBUG(dbgs() << "DEFAULT: " << I << "\n"); 3807 for (size_t i = 0, n = I.getNumOperands(); i < n; i++) { 3808 Value *Operand = I.getOperand(i); 3809 if (Operand->getType()->isSized()) 3810 insertShadowCheck(Operand, &I); 3811 } 3812 setShadow(&I, getCleanShadow(&I)); 3813 setOrigin(&I, getCleanOrigin()); 3814 } 3815 }; 3816 3817 /// AMD64-specific implementation of VarArgHelper. 3818 struct VarArgAMD64Helper : public VarArgHelper { 3819 // An unfortunate workaround for asymmetric lowering of va_arg stuff. 3820 // See a comment in visitCallBase for more details. 3821 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7 3822 static const unsigned AMD64FpEndOffsetSSE = 176; 3823 // If SSE is disabled, fp_offset in va_list is zero. 3824 static const unsigned AMD64FpEndOffsetNoSSE = AMD64GpEndOffset; 3825 3826 unsigned AMD64FpEndOffset; 3827 Function &F; 3828 MemorySanitizer &MS; 3829 MemorySanitizerVisitor &MSV; 3830 Value *VAArgTLSCopy = nullptr; 3831 Value *VAArgTLSOriginCopy = nullptr; 3832 Value *VAArgOverflowSize = nullptr; 3833 3834 SmallVector<CallInst*, 16> VAStartInstrumentationList; 3835 3836 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory }; 3837 3838 VarArgAMD64Helper(Function &F, MemorySanitizer &MS, 3839 MemorySanitizerVisitor &MSV) 3840 : F(F), MS(MS), MSV(MSV) { 3841 AMD64FpEndOffset = AMD64FpEndOffsetSSE; 3842 for (const auto &Attr : F.getAttributes().getFnAttributes()) { 3843 if (Attr.isStringAttribute() && 3844 (Attr.getKindAsString() == "target-features")) { 3845 if (Attr.getValueAsString().contains("-sse")) 3846 AMD64FpEndOffset = AMD64FpEndOffsetNoSSE; 3847 break; 3848 } 3849 } 3850 } 3851 3852 ArgKind classifyArgument(Value* arg) { 3853 // A very rough approximation of X86_64 argument classification rules. 3854 Type *T = arg->getType(); 3855 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy()) 3856 return AK_FloatingPoint; 3857 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64) 3858 return AK_GeneralPurpose; 3859 if (T->isPointerTy()) 3860 return AK_GeneralPurpose; 3861 return AK_Memory; 3862 } 3863 3864 // For VarArg functions, store the argument shadow in an ABI-specific format 3865 // that corresponds to va_list layout. 3866 // We do this because Clang lowers va_arg in the frontend, and this pass 3867 // only sees the low level code that deals with va_list internals. 3868 // A much easier alternative (provided that Clang emits va_arg instructions) 3869 // would have been to associate each live instance of va_list with a copy of 3870 // MSanParamTLS, and extract shadow on va_arg() call in the argument list 3871 // order. 3872 void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override { 3873 unsigned GpOffset = 0; 3874 unsigned FpOffset = AMD64GpEndOffset; 3875 unsigned OverflowOffset = AMD64FpEndOffset; 3876 const DataLayout &DL = F.getParent()->getDataLayout(); 3877 for (auto ArgIt = CB.arg_begin(), End = CB.arg_end(); ArgIt != End; 3878 ++ArgIt) { 3879 Value *A = *ArgIt; 3880 unsigned ArgNo = CB.getArgOperandNo(ArgIt); 3881 bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams(); 3882 bool IsByVal = CB.paramHasAttr(ArgNo, Attribute::ByVal); 3883 if (IsByVal) { 3884 // ByVal arguments always go to the overflow area. 3885 // Fixed arguments passed through the overflow area will be stepped 3886 // over by va_start, so don't count them towards the offset. 3887 if (IsFixed) 3888 continue; 3889 assert(A->getType()->isPointerTy()); 3890 Type *RealTy = CB.getParamByValType(ArgNo); 3891 uint64_t ArgSize = DL.getTypeAllocSize(RealTy); 3892 Value *ShadowBase = getShadowPtrForVAArgument( 3893 RealTy, IRB, OverflowOffset, alignTo(ArgSize, 8)); 3894 Value *OriginBase = nullptr; 3895 if (MS.TrackOrigins) 3896 OriginBase = getOriginPtrForVAArgument(RealTy, IRB, OverflowOffset); 3897 OverflowOffset += alignTo(ArgSize, 8); 3898 if (!ShadowBase) 3899 continue; 3900 Value *ShadowPtr, *OriginPtr; 3901 std::tie(ShadowPtr, OriginPtr) = 3902 MSV.getShadowOriginPtr(A, IRB, IRB.getInt8Ty(), kShadowTLSAlignment, 3903 /*isStore*/ false); 3904 3905 IRB.CreateMemCpy(ShadowBase, kShadowTLSAlignment, ShadowPtr, 3906 kShadowTLSAlignment, ArgSize); 3907 if (MS.TrackOrigins) 3908 IRB.CreateMemCpy(OriginBase, kShadowTLSAlignment, OriginPtr, 3909 kShadowTLSAlignment, ArgSize); 3910 } else { 3911 ArgKind AK = classifyArgument(A); 3912 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset) 3913 AK = AK_Memory; 3914 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset) 3915 AK = AK_Memory; 3916 Value *ShadowBase, *OriginBase = nullptr; 3917 switch (AK) { 3918 case AK_GeneralPurpose: 3919 ShadowBase = 3920 getShadowPtrForVAArgument(A->getType(), IRB, GpOffset, 8); 3921 if (MS.TrackOrigins) 3922 OriginBase = 3923 getOriginPtrForVAArgument(A->getType(), IRB, GpOffset); 3924 GpOffset += 8; 3925 break; 3926 case AK_FloatingPoint: 3927 ShadowBase = 3928 getShadowPtrForVAArgument(A->getType(), IRB, FpOffset, 16); 3929 if (MS.TrackOrigins) 3930 OriginBase = 3931 getOriginPtrForVAArgument(A->getType(), IRB, FpOffset); 3932 FpOffset += 16; 3933 break; 3934 case AK_Memory: 3935 if (IsFixed) 3936 continue; 3937 uint64_t ArgSize = DL.getTypeAllocSize(A->getType()); 3938 ShadowBase = 3939 getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset, 8); 3940 if (MS.TrackOrigins) 3941 OriginBase = 3942 getOriginPtrForVAArgument(A->getType(), IRB, OverflowOffset); 3943 OverflowOffset += alignTo(ArgSize, 8); 3944 } 3945 // Take fixed arguments into account for GpOffset and FpOffset, 3946 // but don't actually store shadows for them. 3947 // TODO(glider): don't call get*PtrForVAArgument() for them. 3948 if (IsFixed) 3949 continue; 3950 if (!ShadowBase) 3951 continue; 3952 Value *Shadow = MSV.getShadow(A); 3953 IRB.CreateAlignedStore(Shadow, ShadowBase, kShadowTLSAlignment); 3954 if (MS.TrackOrigins) { 3955 Value *Origin = MSV.getOrigin(A); 3956 unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType()); 3957 MSV.paintOrigin(IRB, Origin, OriginBase, StoreSize, 3958 std::max(kShadowTLSAlignment, kMinOriginAlignment)); 3959 } 3960 } 3961 } 3962 Constant *OverflowSize = 3963 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset); 3964 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS); 3965 } 3966 3967 /// Compute the shadow address for a given va_arg. 3968 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB, 3969 unsigned ArgOffset, unsigned ArgSize) { 3970 // Make sure we don't overflow __msan_va_arg_tls. 3971 if (ArgOffset + ArgSize > kParamTLSSize) 3972 return nullptr; 3973 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy); 3974 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); 3975 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0), 3976 "_msarg_va_s"); 3977 } 3978 3979 /// Compute the origin address for a given va_arg. 3980 Value *getOriginPtrForVAArgument(Type *Ty, IRBuilder<> &IRB, int ArgOffset) { 3981 Value *Base = IRB.CreatePointerCast(MS.VAArgOriginTLS, MS.IntptrTy); 3982 // getOriginPtrForVAArgument() is always called after 3983 // getShadowPtrForVAArgument(), so __msan_va_arg_origin_tls can never 3984 // overflow. 3985 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); 3986 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0), 3987 "_msarg_va_o"); 3988 } 3989 3990 void unpoisonVAListTagForInst(IntrinsicInst &I) { 3991 IRBuilder<> IRB(&I); 3992 Value *VAListTag = I.getArgOperand(0); 3993 Value *ShadowPtr, *OriginPtr; 3994 const Align Alignment = Align(8); 3995 std::tie(ShadowPtr, OriginPtr) = 3996 MSV.getShadowOriginPtr(VAListTag, IRB, IRB.getInt8Ty(), Alignment, 3997 /*isStore*/ true); 3998 3999 // Unpoison the whole __va_list_tag. 4000 // FIXME: magic ABI constants. 4001 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), 4002 /* size */ 24, Alignment, false); 4003 // We shouldn't need to zero out the origins, as they're only checked for 4004 // nonzero shadow. 4005 } 4006 4007 void visitVAStartInst(VAStartInst &I) override { 4008 if (F.getCallingConv() == CallingConv::Win64) 4009 return; 4010 VAStartInstrumentationList.push_back(&I); 4011 unpoisonVAListTagForInst(I); 4012 } 4013 4014 void visitVACopyInst(VACopyInst &I) override { 4015 if (F.getCallingConv() == CallingConv::Win64) return; 4016 unpoisonVAListTagForInst(I); 4017 } 4018 4019 void finalizeInstrumentation() override { 4020 assert(!VAArgOverflowSize && !VAArgTLSCopy && 4021 "finalizeInstrumentation called twice"); 4022 if (!VAStartInstrumentationList.empty()) { 4023 // If there is a va_start in this function, make a backup copy of 4024 // va_arg_tls somewhere in the function entry block. 4025 IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI()); 4026 VAArgOverflowSize = 4027 IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS); 4028 Value *CopySize = 4029 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset), 4030 VAArgOverflowSize); 4031 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize); 4032 IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize); 4033 if (MS.TrackOrigins) { 4034 VAArgTLSOriginCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize); 4035 IRB.CreateMemCpy(VAArgTLSOriginCopy, Align(8), MS.VAArgOriginTLS, 4036 Align(8), CopySize); 4037 } 4038 } 4039 4040 // Instrument va_start. 4041 // Copy va_list shadow from the backup copy of the TLS contents. 4042 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) { 4043 CallInst *OrigInst = VAStartInstrumentationList[i]; 4044 IRBuilder<> IRB(OrigInst->getNextNode()); 4045 Value *VAListTag = OrigInst->getArgOperand(0); 4046 4047 Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C); 4048 Value *RegSaveAreaPtrPtr = IRB.CreateIntToPtr( 4049 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), 4050 ConstantInt::get(MS.IntptrTy, 16)), 4051 PointerType::get(RegSaveAreaPtrTy, 0)); 4052 Value *RegSaveAreaPtr = 4053 IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr); 4054 Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr; 4055 const Align Alignment = Align(16); 4056 std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) = 4057 MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(), 4058 Alignment, /*isStore*/ true); 4059 IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment, 4060 AMD64FpEndOffset); 4061 if (MS.TrackOrigins) 4062 IRB.CreateMemCpy(RegSaveAreaOriginPtr, Alignment, VAArgTLSOriginCopy, 4063 Alignment, AMD64FpEndOffset); 4064 Type *OverflowArgAreaPtrTy = Type::getInt64PtrTy(*MS.C); 4065 Value *OverflowArgAreaPtrPtr = IRB.CreateIntToPtr( 4066 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), 4067 ConstantInt::get(MS.IntptrTy, 8)), 4068 PointerType::get(OverflowArgAreaPtrTy, 0)); 4069 Value *OverflowArgAreaPtr = 4070 IRB.CreateLoad(OverflowArgAreaPtrTy, OverflowArgAreaPtrPtr); 4071 Value *OverflowArgAreaShadowPtr, *OverflowArgAreaOriginPtr; 4072 std::tie(OverflowArgAreaShadowPtr, OverflowArgAreaOriginPtr) = 4073 MSV.getShadowOriginPtr(OverflowArgAreaPtr, IRB, IRB.getInt8Ty(), 4074 Alignment, /*isStore*/ true); 4075 Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy, 4076 AMD64FpEndOffset); 4077 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, Alignment, SrcPtr, Alignment, 4078 VAArgOverflowSize); 4079 if (MS.TrackOrigins) { 4080 SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSOriginCopy, 4081 AMD64FpEndOffset); 4082 IRB.CreateMemCpy(OverflowArgAreaOriginPtr, Alignment, SrcPtr, Alignment, 4083 VAArgOverflowSize); 4084 } 4085 } 4086 } 4087 }; 4088 4089 /// MIPS64-specific implementation of VarArgHelper. 4090 struct VarArgMIPS64Helper : public VarArgHelper { 4091 Function &F; 4092 MemorySanitizer &MS; 4093 MemorySanitizerVisitor &MSV; 4094 Value *VAArgTLSCopy = nullptr; 4095 Value *VAArgSize = nullptr; 4096 4097 SmallVector<CallInst*, 16> VAStartInstrumentationList; 4098 4099 VarArgMIPS64Helper(Function &F, MemorySanitizer &MS, 4100 MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {} 4101 4102 void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override { 4103 unsigned VAArgOffset = 0; 4104 const DataLayout &DL = F.getParent()->getDataLayout(); 4105 for (auto ArgIt = CB.arg_begin() + CB.getFunctionType()->getNumParams(), 4106 End = CB.arg_end(); 4107 ArgIt != End; ++ArgIt) { 4108 Triple TargetTriple(F.getParent()->getTargetTriple()); 4109 Value *A = *ArgIt; 4110 Value *Base; 4111 uint64_t ArgSize = DL.getTypeAllocSize(A->getType()); 4112 if (TargetTriple.getArch() == Triple::mips64) { 4113 // Adjusting the shadow for argument with size < 8 to match the placement 4114 // of bits in big endian system 4115 if (ArgSize < 8) 4116 VAArgOffset += (8 - ArgSize); 4117 } 4118 Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset, ArgSize); 4119 VAArgOffset += ArgSize; 4120 VAArgOffset = alignTo(VAArgOffset, 8); 4121 if (!Base) 4122 continue; 4123 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment); 4124 } 4125 4126 Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset); 4127 // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of 4128 // a new class member i.e. it is the total size of all VarArgs. 4129 IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS); 4130 } 4131 4132 /// Compute the shadow address for a given va_arg. 4133 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB, 4134 unsigned ArgOffset, unsigned ArgSize) { 4135 // Make sure we don't overflow __msan_va_arg_tls. 4136 if (ArgOffset + ArgSize > kParamTLSSize) 4137 return nullptr; 4138 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy); 4139 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); 4140 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0), 4141 "_msarg"); 4142 } 4143 4144 void visitVAStartInst(VAStartInst &I) override { 4145 IRBuilder<> IRB(&I); 4146 VAStartInstrumentationList.push_back(&I); 4147 Value *VAListTag = I.getArgOperand(0); 4148 Value *ShadowPtr, *OriginPtr; 4149 const Align Alignment = Align(8); 4150 std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr( 4151 VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true); 4152 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), 4153 /* size */ 8, Alignment, false); 4154 } 4155 4156 void visitVACopyInst(VACopyInst &I) override { 4157 IRBuilder<> IRB(&I); 4158 VAStartInstrumentationList.push_back(&I); 4159 Value *VAListTag = I.getArgOperand(0); 4160 Value *ShadowPtr, *OriginPtr; 4161 const Align Alignment = Align(8); 4162 std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr( 4163 VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true); 4164 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), 4165 /* size */ 8, Alignment, false); 4166 } 4167 4168 void finalizeInstrumentation() override { 4169 assert(!VAArgSize && !VAArgTLSCopy && 4170 "finalizeInstrumentation called twice"); 4171 IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI()); 4172 VAArgSize = IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS); 4173 Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0), 4174 VAArgSize); 4175 4176 if (!VAStartInstrumentationList.empty()) { 4177 // If there is a va_start in this function, make a backup copy of 4178 // va_arg_tls somewhere in the function entry block. 4179 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize); 4180 IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize); 4181 } 4182 4183 // Instrument va_start. 4184 // Copy va_list shadow from the backup copy of the TLS contents. 4185 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) { 4186 CallInst *OrigInst = VAStartInstrumentationList[i]; 4187 IRBuilder<> IRB(OrigInst->getNextNode()); 4188 Value *VAListTag = OrigInst->getArgOperand(0); 4189 Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C); 4190 Value *RegSaveAreaPtrPtr = 4191 IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), 4192 PointerType::get(RegSaveAreaPtrTy, 0)); 4193 Value *RegSaveAreaPtr = 4194 IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr); 4195 Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr; 4196 const Align Alignment = Align(8); 4197 std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) = 4198 MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(), 4199 Alignment, /*isStore*/ true); 4200 IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment, 4201 CopySize); 4202 } 4203 } 4204 }; 4205 4206 /// AArch64-specific implementation of VarArgHelper. 4207 struct VarArgAArch64Helper : public VarArgHelper { 4208 static const unsigned kAArch64GrArgSize = 64; 4209 static const unsigned kAArch64VrArgSize = 128; 4210 4211 static const unsigned AArch64GrBegOffset = 0; 4212 static const unsigned AArch64GrEndOffset = kAArch64GrArgSize; 4213 // Make VR space aligned to 16 bytes. 4214 static const unsigned AArch64VrBegOffset = AArch64GrEndOffset; 4215 static const unsigned AArch64VrEndOffset = AArch64VrBegOffset 4216 + kAArch64VrArgSize; 4217 static const unsigned AArch64VAEndOffset = AArch64VrEndOffset; 4218 4219 Function &F; 4220 MemorySanitizer &MS; 4221 MemorySanitizerVisitor &MSV; 4222 Value *VAArgTLSCopy = nullptr; 4223 Value *VAArgOverflowSize = nullptr; 4224 4225 SmallVector<CallInst*, 16> VAStartInstrumentationList; 4226 4227 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory }; 4228 4229 VarArgAArch64Helper(Function &F, MemorySanitizer &MS, 4230 MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {} 4231 4232 ArgKind classifyArgument(Value* arg) { 4233 Type *T = arg->getType(); 4234 if (T->isFPOrFPVectorTy()) 4235 return AK_FloatingPoint; 4236 if ((T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64) 4237 || (T->isPointerTy())) 4238 return AK_GeneralPurpose; 4239 return AK_Memory; 4240 } 4241 4242 // The instrumentation stores the argument shadow in a non ABI-specific 4243 // format because it does not know which argument is named (since Clang, 4244 // like x86_64 case, lowers the va_args in the frontend and this pass only 4245 // sees the low level code that deals with va_list internals). 4246 // The first seven GR registers are saved in the first 56 bytes of the 4247 // va_arg tls arra, followers by the first 8 FP/SIMD registers, and then 4248 // the remaining arguments. 4249 // Using constant offset within the va_arg TLS array allows fast copy 4250 // in the finalize instrumentation. 4251 void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override { 4252 unsigned GrOffset = AArch64GrBegOffset; 4253 unsigned VrOffset = AArch64VrBegOffset; 4254 unsigned OverflowOffset = AArch64VAEndOffset; 4255 4256 const DataLayout &DL = F.getParent()->getDataLayout(); 4257 for (auto ArgIt = CB.arg_begin(), End = CB.arg_end(); ArgIt != End; 4258 ++ArgIt) { 4259 Value *A = *ArgIt; 4260 unsigned ArgNo = CB.getArgOperandNo(ArgIt); 4261 bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams(); 4262 ArgKind AK = classifyArgument(A); 4263 if (AK == AK_GeneralPurpose && GrOffset >= AArch64GrEndOffset) 4264 AK = AK_Memory; 4265 if (AK == AK_FloatingPoint && VrOffset >= AArch64VrEndOffset) 4266 AK = AK_Memory; 4267 Value *Base; 4268 switch (AK) { 4269 case AK_GeneralPurpose: 4270 Base = getShadowPtrForVAArgument(A->getType(), IRB, GrOffset, 8); 4271 GrOffset += 8; 4272 break; 4273 case AK_FloatingPoint: 4274 Base = getShadowPtrForVAArgument(A->getType(), IRB, VrOffset, 8); 4275 VrOffset += 16; 4276 break; 4277 case AK_Memory: 4278 // Don't count fixed arguments in the overflow area - va_start will 4279 // skip right over them. 4280 if (IsFixed) 4281 continue; 4282 uint64_t ArgSize = DL.getTypeAllocSize(A->getType()); 4283 Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset, 4284 alignTo(ArgSize, 8)); 4285 OverflowOffset += alignTo(ArgSize, 8); 4286 break; 4287 } 4288 // Count Gp/Vr fixed arguments to their respective offsets, but don't 4289 // bother to actually store a shadow. 4290 if (IsFixed) 4291 continue; 4292 if (!Base) 4293 continue; 4294 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment); 4295 } 4296 Constant *OverflowSize = 4297 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AArch64VAEndOffset); 4298 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS); 4299 } 4300 4301 /// Compute the shadow address for a given va_arg. 4302 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB, 4303 unsigned ArgOffset, unsigned ArgSize) { 4304 // Make sure we don't overflow __msan_va_arg_tls. 4305 if (ArgOffset + ArgSize > kParamTLSSize) 4306 return nullptr; 4307 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy); 4308 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); 4309 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0), 4310 "_msarg"); 4311 } 4312 4313 void visitVAStartInst(VAStartInst &I) override { 4314 IRBuilder<> IRB(&I); 4315 VAStartInstrumentationList.push_back(&I); 4316 Value *VAListTag = I.getArgOperand(0); 4317 Value *ShadowPtr, *OriginPtr; 4318 const Align Alignment = Align(8); 4319 std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr( 4320 VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true); 4321 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), 4322 /* size */ 32, Alignment, false); 4323 } 4324 4325 void visitVACopyInst(VACopyInst &I) override { 4326 IRBuilder<> IRB(&I); 4327 VAStartInstrumentationList.push_back(&I); 4328 Value *VAListTag = I.getArgOperand(0); 4329 Value *ShadowPtr, *OriginPtr; 4330 const Align Alignment = Align(8); 4331 std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr( 4332 VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true); 4333 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), 4334 /* size */ 32, Alignment, false); 4335 } 4336 4337 // Retrieve a va_list field of 'void*' size. 4338 Value* getVAField64(IRBuilder<> &IRB, Value *VAListTag, int offset) { 4339 Value *SaveAreaPtrPtr = 4340 IRB.CreateIntToPtr( 4341 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), 4342 ConstantInt::get(MS.IntptrTy, offset)), 4343 Type::getInt64PtrTy(*MS.C)); 4344 return IRB.CreateLoad(Type::getInt64Ty(*MS.C), SaveAreaPtrPtr); 4345 } 4346 4347 // Retrieve a va_list field of 'int' size. 4348 Value* getVAField32(IRBuilder<> &IRB, Value *VAListTag, int offset) { 4349 Value *SaveAreaPtr = 4350 IRB.CreateIntToPtr( 4351 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), 4352 ConstantInt::get(MS.IntptrTy, offset)), 4353 Type::getInt32PtrTy(*MS.C)); 4354 Value *SaveArea32 = IRB.CreateLoad(IRB.getInt32Ty(), SaveAreaPtr); 4355 return IRB.CreateSExt(SaveArea32, MS.IntptrTy); 4356 } 4357 4358 void finalizeInstrumentation() override { 4359 assert(!VAArgOverflowSize && !VAArgTLSCopy && 4360 "finalizeInstrumentation called twice"); 4361 if (!VAStartInstrumentationList.empty()) { 4362 // If there is a va_start in this function, make a backup copy of 4363 // va_arg_tls somewhere in the function entry block. 4364 IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI()); 4365 VAArgOverflowSize = 4366 IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS); 4367 Value *CopySize = 4368 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AArch64VAEndOffset), 4369 VAArgOverflowSize); 4370 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize); 4371 IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize); 4372 } 4373 4374 Value *GrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64GrArgSize); 4375 Value *VrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64VrArgSize); 4376 4377 // Instrument va_start, copy va_list shadow from the backup copy of 4378 // the TLS contents. 4379 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) { 4380 CallInst *OrigInst = VAStartInstrumentationList[i]; 4381 IRBuilder<> IRB(OrigInst->getNextNode()); 4382 4383 Value *VAListTag = OrigInst->getArgOperand(0); 4384 4385 // The variadic ABI for AArch64 creates two areas to save the incoming 4386 // argument registers (one for 64-bit general register xn-x7 and another 4387 // for 128-bit FP/SIMD vn-v7). 4388 // We need then to propagate the shadow arguments on both regions 4389 // 'va::__gr_top + va::__gr_offs' and 'va::__vr_top + va::__vr_offs'. 4390 // The remaining arguments are saved on shadow for 'va::stack'. 4391 // One caveat is it requires only to propagate the non-named arguments, 4392 // however on the call site instrumentation 'all' the arguments are 4393 // saved. So to copy the shadow values from the va_arg TLS array 4394 // we need to adjust the offset for both GR and VR fields based on 4395 // the __{gr,vr}_offs value (since they are stores based on incoming 4396 // named arguments). 4397 4398 // Read the stack pointer from the va_list. 4399 Value *StackSaveAreaPtr = getVAField64(IRB, VAListTag, 0); 4400 4401 // Read both the __gr_top and __gr_off and add them up. 4402 Value *GrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 8); 4403 Value *GrOffSaveArea = getVAField32(IRB, VAListTag, 24); 4404 4405 Value *GrRegSaveAreaPtr = IRB.CreateAdd(GrTopSaveAreaPtr, GrOffSaveArea); 4406 4407 // Read both the __vr_top and __vr_off and add them up. 4408 Value *VrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 16); 4409 Value *VrOffSaveArea = getVAField32(IRB, VAListTag, 28); 4410 4411 Value *VrRegSaveAreaPtr = IRB.CreateAdd(VrTopSaveAreaPtr, VrOffSaveArea); 4412 4413 // It does not know how many named arguments is being used and, on the 4414 // callsite all the arguments were saved. Since __gr_off is defined as 4415 // '0 - ((8 - named_gr) * 8)', the idea is to just propagate the variadic 4416 // argument by ignoring the bytes of shadow from named arguments. 4417 Value *GrRegSaveAreaShadowPtrOff = 4418 IRB.CreateAdd(GrArgSize, GrOffSaveArea); 4419 4420 Value *GrRegSaveAreaShadowPtr = 4421 MSV.getShadowOriginPtr(GrRegSaveAreaPtr, IRB, IRB.getInt8Ty(), 4422 Align(8), /*isStore*/ true) 4423 .first; 4424 4425 Value *GrSrcPtr = IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy, 4426 GrRegSaveAreaShadowPtrOff); 4427 Value *GrCopySize = IRB.CreateSub(GrArgSize, GrRegSaveAreaShadowPtrOff); 4428 4429 IRB.CreateMemCpy(GrRegSaveAreaShadowPtr, Align(8), GrSrcPtr, Align(8), 4430 GrCopySize); 4431 4432 // Again, but for FP/SIMD values. 4433 Value *VrRegSaveAreaShadowPtrOff = 4434 IRB.CreateAdd(VrArgSize, VrOffSaveArea); 4435 4436 Value *VrRegSaveAreaShadowPtr = 4437 MSV.getShadowOriginPtr(VrRegSaveAreaPtr, IRB, IRB.getInt8Ty(), 4438 Align(8), /*isStore*/ true) 4439 .first; 4440 4441 Value *VrSrcPtr = IRB.CreateInBoundsGEP( 4442 IRB.getInt8Ty(), 4443 IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy, 4444 IRB.getInt32(AArch64VrBegOffset)), 4445 VrRegSaveAreaShadowPtrOff); 4446 Value *VrCopySize = IRB.CreateSub(VrArgSize, VrRegSaveAreaShadowPtrOff); 4447 4448 IRB.CreateMemCpy(VrRegSaveAreaShadowPtr, Align(8), VrSrcPtr, Align(8), 4449 VrCopySize); 4450 4451 // And finally for remaining arguments. 4452 Value *StackSaveAreaShadowPtr = 4453 MSV.getShadowOriginPtr(StackSaveAreaPtr, IRB, IRB.getInt8Ty(), 4454 Align(16), /*isStore*/ true) 4455 .first; 4456 4457 Value *StackSrcPtr = 4458 IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy, 4459 IRB.getInt32(AArch64VAEndOffset)); 4460 4461 IRB.CreateMemCpy(StackSaveAreaShadowPtr, Align(16), StackSrcPtr, 4462 Align(16), VAArgOverflowSize); 4463 } 4464 } 4465 }; 4466 4467 /// PowerPC64-specific implementation of VarArgHelper. 4468 struct VarArgPowerPC64Helper : public VarArgHelper { 4469 Function &F; 4470 MemorySanitizer &MS; 4471 MemorySanitizerVisitor &MSV; 4472 Value *VAArgTLSCopy = nullptr; 4473 Value *VAArgSize = nullptr; 4474 4475 SmallVector<CallInst*, 16> VAStartInstrumentationList; 4476 4477 VarArgPowerPC64Helper(Function &F, MemorySanitizer &MS, 4478 MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {} 4479 4480 void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override { 4481 // For PowerPC, we need to deal with alignment of stack arguments - 4482 // they are mostly aligned to 8 bytes, but vectors and i128 arrays 4483 // are aligned to 16 bytes, byvals can be aligned to 8 or 16 bytes, 4484 // and QPX vectors are aligned to 32 bytes. For that reason, we 4485 // compute current offset from stack pointer (which is always properly 4486 // aligned), and offset for the first vararg, then subtract them. 4487 unsigned VAArgBase; 4488 Triple TargetTriple(F.getParent()->getTargetTriple()); 4489 // Parameter save area starts at 48 bytes from frame pointer for ABIv1, 4490 // and 32 bytes for ABIv2. This is usually determined by target 4491 // endianness, but in theory could be overridden by function attribute. 4492 // For simplicity, we ignore it here (it'd only matter for QPX vectors). 4493 if (TargetTriple.getArch() == Triple::ppc64) 4494 VAArgBase = 48; 4495 else 4496 VAArgBase = 32; 4497 unsigned VAArgOffset = VAArgBase; 4498 const DataLayout &DL = F.getParent()->getDataLayout(); 4499 for (auto ArgIt = CB.arg_begin(), End = CB.arg_end(); ArgIt != End; 4500 ++ArgIt) { 4501 Value *A = *ArgIt; 4502 unsigned ArgNo = CB.getArgOperandNo(ArgIt); 4503 bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams(); 4504 bool IsByVal = CB.paramHasAttr(ArgNo, Attribute::ByVal); 4505 if (IsByVal) { 4506 assert(A->getType()->isPointerTy()); 4507 Type *RealTy = CB.getParamByValType(ArgNo); 4508 uint64_t ArgSize = DL.getTypeAllocSize(RealTy); 4509 MaybeAlign ArgAlign = CB.getParamAlign(ArgNo); 4510 if (!ArgAlign || *ArgAlign < Align(8)) 4511 ArgAlign = Align(8); 4512 VAArgOffset = alignTo(VAArgOffset, ArgAlign); 4513 if (!IsFixed) { 4514 Value *Base = getShadowPtrForVAArgument( 4515 RealTy, IRB, VAArgOffset - VAArgBase, ArgSize); 4516 if (Base) { 4517 Value *AShadowPtr, *AOriginPtr; 4518 std::tie(AShadowPtr, AOriginPtr) = 4519 MSV.getShadowOriginPtr(A, IRB, IRB.getInt8Ty(), 4520 kShadowTLSAlignment, /*isStore*/ false); 4521 4522 IRB.CreateMemCpy(Base, kShadowTLSAlignment, AShadowPtr, 4523 kShadowTLSAlignment, ArgSize); 4524 } 4525 } 4526 VAArgOffset += alignTo(ArgSize, 8); 4527 } else { 4528 Value *Base; 4529 uint64_t ArgSize = DL.getTypeAllocSize(A->getType()); 4530 uint64_t ArgAlign = 8; 4531 if (A->getType()->isArrayTy()) { 4532 // Arrays are aligned to element size, except for long double 4533 // arrays, which are aligned to 8 bytes. 4534 Type *ElementTy = A->getType()->getArrayElementType(); 4535 if (!ElementTy->isPPC_FP128Ty()) 4536 ArgAlign = DL.getTypeAllocSize(ElementTy); 4537 } else if (A->getType()->isVectorTy()) { 4538 // Vectors are naturally aligned. 4539 ArgAlign = DL.getTypeAllocSize(A->getType()); 4540 } 4541 if (ArgAlign < 8) 4542 ArgAlign = 8; 4543 VAArgOffset = alignTo(VAArgOffset, ArgAlign); 4544 if (DL.isBigEndian()) { 4545 // Adjusting the shadow for argument with size < 8 to match the placement 4546 // of bits in big endian system 4547 if (ArgSize < 8) 4548 VAArgOffset += (8 - ArgSize); 4549 } 4550 if (!IsFixed) { 4551 Base = getShadowPtrForVAArgument(A->getType(), IRB, 4552 VAArgOffset - VAArgBase, ArgSize); 4553 if (Base) 4554 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment); 4555 } 4556 VAArgOffset += ArgSize; 4557 VAArgOffset = alignTo(VAArgOffset, 8); 4558 } 4559 if (IsFixed) 4560 VAArgBase = VAArgOffset; 4561 } 4562 4563 Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), 4564 VAArgOffset - VAArgBase); 4565 // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of 4566 // a new class member i.e. it is the total size of all VarArgs. 4567 IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS); 4568 } 4569 4570 /// Compute the shadow address for a given va_arg. 4571 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB, 4572 unsigned ArgOffset, unsigned ArgSize) { 4573 // Make sure we don't overflow __msan_va_arg_tls. 4574 if (ArgOffset + ArgSize > kParamTLSSize) 4575 return nullptr; 4576 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy); 4577 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); 4578 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0), 4579 "_msarg"); 4580 } 4581 4582 void visitVAStartInst(VAStartInst &I) override { 4583 IRBuilder<> IRB(&I); 4584 VAStartInstrumentationList.push_back(&I); 4585 Value *VAListTag = I.getArgOperand(0); 4586 Value *ShadowPtr, *OriginPtr; 4587 const Align Alignment = Align(8); 4588 std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr( 4589 VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true); 4590 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), 4591 /* size */ 8, Alignment, false); 4592 } 4593 4594 void visitVACopyInst(VACopyInst &I) override { 4595 IRBuilder<> IRB(&I); 4596 Value *VAListTag = I.getArgOperand(0); 4597 Value *ShadowPtr, *OriginPtr; 4598 const Align Alignment = Align(8); 4599 std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr( 4600 VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true); 4601 // Unpoison the whole __va_list_tag. 4602 // FIXME: magic ABI constants. 4603 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), 4604 /* size */ 8, Alignment, false); 4605 } 4606 4607 void finalizeInstrumentation() override { 4608 assert(!VAArgSize && !VAArgTLSCopy && 4609 "finalizeInstrumentation called twice"); 4610 IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI()); 4611 VAArgSize = IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS); 4612 Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0), 4613 VAArgSize); 4614 4615 if (!VAStartInstrumentationList.empty()) { 4616 // If there is a va_start in this function, make a backup copy of 4617 // va_arg_tls somewhere in the function entry block. 4618 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize); 4619 IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize); 4620 } 4621 4622 // Instrument va_start. 4623 // Copy va_list shadow from the backup copy of the TLS contents. 4624 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) { 4625 CallInst *OrigInst = VAStartInstrumentationList[i]; 4626 IRBuilder<> IRB(OrigInst->getNextNode()); 4627 Value *VAListTag = OrigInst->getArgOperand(0); 4628 Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C); 4629 Value *RegSaveAreaPtrPtr = 4630 IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), 4631 PointerType::get(RegSaveAreaPtrTy, 0)); 4632 Value *RegSaveAreaPtr = 4633 IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr); 4634 Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr; 4635 const Align Alignment = Align(8); 4636 std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) = 4637 MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(), 4638 Alignment, /*isStore*/ true); 4639 IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment, 4640 CopySize); 4641 } 4642 } 4643 }; 4644 4645 /// SystemZ-specific implementation of VarArgHelper. 4646 struct VarArgSystemZHelper : public VarArgHelper { 4647 static const unsigned SystemZGpOffset = 16; 4648 static const unsigned SystemZGpEndOffset = 56; 4649 static const unsigned SystemZFpOffset = 128; 4650 static const unsigned SystemZFpEndOffset = 160; 4651 static const unsigned SystemZMaxVrArgs = 8; 4652 static const unsigned SystemZRegSaveAreaSize = 160; 4653 static const unsigned SystemZOverflowOffset = 160; 4654 static const unsigned SystemZVAListTagSize = 32; 4655 static const unsigned SystemZOverflowArgAreaPtrOffset = 16; 4656 static const unsigned SystemZRegSaveAreaPtrOffset = 24; 4657 4658 Function &F; 4659 MemorySanitizer &MS; 4660 MemorySanitizerVisitor &MSV; 4661 Value *VAArgTLSCopy = nullptr; 4662 Value *VAArgTLSOriginCopy = nullptr; 4663 Value *VAArgOverflowSize = nullptr; 4664 4665 SmallVector<CallInst *, 16> VAStartInstrumentationList; 4666 4667 enum class ArgKind { 4668 GeneralPurpose, 4669 FloatingPoint, 4670 Vector, 4671 Memory, 4672 Indirect, 4673 }; 4674 4675 enum class ShadowExtension { None, Zero, Sign }; 4676 4677 VarArgSystemZHelper(Function &F, MemorySanitizer &MS, 4678 MemorySanitizerVisitor &MSV) 4679 : F(F), MS(MS), MSV(MSV) {} 4680 4681 ArgKind classifyArgument(Type *T, bool IsSoftFloatABI) { 4682 // T is a SystemZABIInfo::classifyArgumentType() output, and there are 4683 // only a few possibilities of what it can be. In particular, enums, single 4684 // element structs and large types have already been taken care of. 4685 4686 // Some i128 and fp128 arguments are converted to pointers only in the 4687 // back end. 4688 if (T->isIntegerTy(128) || T->isFP128Ty()) 4689 return ArgKind::Indirect; 4690 if (T->isFloatingPointTy()) 4691 return IsSoftFloatABI ? ArgKind::GeneralPurpose : ArgKind::FloatingPoint; 4692 if (T->isIntegerTy() || T->isPointerTy()) 4693 return ArgKind::GeneralPurpose; 4694 if (T->isVectorTy()) 4695 return ArgKind::Vector; 4696 return ArgKind::Memory; 4697 } 4698 4699 ShadowExtension getShadowExtension(const CallBase &CB, unsigned ArgNo) { 4700 // ABI says: "One of the simple integer types no more than 64 bits wide. 4701 // ... If such an argument is shorter than 64 bits, replace it by a full 4702 // 64-bit integer representing the same number, using sign or zero 4703 // extension". Shadow for an integer argument has the same type as the 4704 // argument itself, so it can be sign or zero extended as well. 4705 bool ZExt = CB.paramHasAttr(ArgNo, Attribute::ZExt); 4706 bool SExt = CB.paramHasAttr(ArgNo, Attribute::SExt); 4707 if (ZExt) { 4708 assert(!SExt); 4709 return ShadowExtension::Zero; 4710 } 4711 if (SExt) { 4712 assert(!ZExt); 4713 return ShadowExtension::Sign; 4714 } 4715 return ShadowExtension::None; 4716 } 4717 4718 void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override { 4719 bool IsSoftFloatABI = CB.getCalledFunction() 4720 ->getFnAttribute("use-soft-float") 4721 .getValueAsString() == "true"; 4722 unsigned GpOffset = SystemZGpOffset; 4723 unsigned FpOffset = SystemZFpOffset; 4724 unsigned VrIndex = 0; 4725 unsigned OverflowOffset = SystemZOverflowOffset; 4726 const DataLayout &DL = F.getParent()->getDataLayout(); 4727 for (auto ArgIt = CB.arg_begin(), End = CB.arg_end(); ArgIt != End; 4728 ++ArgIt) { 4729 Value *A = *ArgIt; 4730 unsigned ArgNo = CB.getArgOperandNo(ArgIt); 4731 bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams(); 4732 // SystemZABIInfo does not produce ByVal parameters. 4733 assert(!CB.paramHasAttr(ArgNo, Attribute::ByVal)); 4734 Type *T = A->getType(); 4735 ArgKind AK = classifyArgument(T, IsSoftFloatABI); 4736 if (AK == ArgKind::Indirect) { 4737 T = PointerType::get(T, 0); 4738 AK = ArgKind::GeneralPurpose; 4739 } 4740 if (AK == ArgKind::GeneralPurpose && GpOffset >= SystemZGpEndOffset) 4741 AK = ArgKind::Memory; 4742 if (AK == ArgKind::FloatingPoint && FpOffset >= SystemZFpEndOffset) 4743 AK = ArgKind::Memory; 4744 if (AK == ArgKind::Vector && (VrIndex >= SystemZMaxVrArgs || !IsFixed)) 4745 AK = ArgKind::Memory; 4746 Value *ShadowBase = nullptr; 4747 Value *OriginBase = nullptr; 4748 ShadowExtension SE = ShadowExtension::None; 4749 switch (AK) { 4750 case ArgKind::GeneralPurpose: { 4751 // Always keep track of GpOffset, but store shadow only for varargs. 4752 uint64_t ArgSize = 8; 4753 if (GpOffset + ArgSize <= kParamTLSSize) { 4754 if (!IsFixed) { 4755 SE = getShadowExtension(CB, ArgNo); 4756 uint64_t GapSize = 0; 4757 if (SE == ShadowExtension::None) { 4758 uint64_t ArgAllocSize = DL.getTypeAllocSize(T); 4759 assert(ArgAllocSize <= ArgSize); 4760 GapSize = ArgSize - ArgAllocSize; 4761 } 4762 ShadowBase = getShadowAddrForVAArgument(IRB, GpOffset + GapSize); 4763 if (MS.TrackOrigins) 4764 OriginBase = getOriginPtrForVAArgument(IRB, GpOffset + GapSize); 4765 } 4766 GpOffset += ArgSize; 4767 } else { 4768 GpOffset = kParamTLSSize; 4769 } 4770 break; 4771 } 4772 case ArgKind::FloatingPoint: { 4773 // Always keep track of FpOffset, but store shadow only for varargs. 4774 uint64_t ArgSize = 8; 4775 if (FpOffset + ArgSize <= kParamTLSSize) { 4776 if (!IsFixed) { 4777 // PoP says: "A short floating-point datum requires only the 4778 // left-most 32 bit positions of a floating-point register". 4779 // Therefore, in contrast to AK_GeneralPurpose and AK_Memory, 4780 // don't extend shadow and don't mind the gap. 4781 ShadowBase = getShadowAddrForVAArgument(IRB, FpOffset); 4782 if (MS.TrackOrigins) 4783 OriginBase = getOriginPtrForVAArgument(IRB, FpOffset); 4784 } 4785 FpOffset += ArgSize; 4786 } else { 4787 FpOffset = kParamTLSSize; 4788 } 4789 break; 4790 } 4791 case ArgKind::Vector: { 4792 // Keep track of VrIndex. No need to store shadow, since vector varargs 4793 // go through AK_Memory. 4794 assert(IsFixed); 4795 VrIndex++; 4796 break; 4797 } 4798 case ArgKind::Memory: { 4799 // Keep track of OverflowOffset and store shadow only for varargs. 4800 // Ignore fixed args, since we need to copy only the vararg portion of 4801 // the overflow area shadow. 4802 if (!IsFixed) { 4803 uint64_t ArgAllocSize = DL.getTypeAllocSize(T); 4804 uint64_t ArgSize = alignTo(ArgAllocSize, 8); 4805 if (OverflowOffset + ArgSize <= kParamTLSSize) { 4806 SE = getShadowExtension(CB, ArgNo); 4807 uint64_t GapSize = 4808 SE == ShadowExtension::None ? ArgSize - ArgAllocSize : 0; 4809 ShadowBase = 4810 getShadowAddrForVAArgument(IRB, OverflowOffset + GapSize); 4811 if (MS.TrackOrigins) 4812 OriginBase = 4813 getOriginPtrForVAArgument(IRB, OverflowOffset + GapSize); 4814 OverflowOffset += ArgSize; 4815 } else { 4816 OverflowOffset = kParamTLSSize; 4817 } 4818 } 4819 break; 4820 } 4821 case ArgKind::Indirect: 4822 llvm_unreachable("Indirect must be converted to GeneralPurpose"); 4823 } 4824 if (ShadowBase == nullptr) 4825 continue; 4826 Value *Shadow = MSV.getShadow(A); 4827 if (SE != ShadowExtension::None) 4828 Shadow = MSV.CreateShadowCast(IRB, Shadow, IRB.getInt64Ty(), 4829 /*Signed*/ SE == ShadowExtension::Sign); 4830 ShadowBase = IRB.CreateIntToPtr( 4831 ShadowBase, PointerType::get(Shadow->getType(), 0), "_msarg_va_s"); 4832 IRB.CreateStore(Shadow, ShadowBase); 4833 if (MS.TrackOrigins) { 4834 Value *Origin = MSV.getOrigin(A); 4835 unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType()); 4836 MSV.paintOrigin(IRB, Origin, OriginBase, StoreSize, 4837 kMinOriginAlignment); 4838 } 4839 } 4840 Constant *OverflowSize = ConstantInt::get( 4841 IRB.getInt64Ty(), OverflowOffset - SystemZOverflowOffset); 4842 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS); 4843 } 4844 4845 Value *getShadowAddrForVAArgument(IRBuilder<> &IRB, unsigned ArgOffset) { 4846 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy); 4847 return IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); 4848 } 4849 4850 Value *getOriginPtrForVAArgument(IRBuilder<> &IRB, int ArgOffset) { 4851 Value *Base = IRB.CreatePointerCast(MS.VAArgOriginTLS, MS.IntptrTy); 4852 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); 4853 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0), 4854 "_msarg_va_o"); 4855 } 4856 4857 void unpoisonVAListTagForInst(IntrinsicInst &I) { 4858 IRBuilder<> IRB(&I); 4859 Value *VAListTag = I.getArgOperand(0); 4860 Value *ShadowPtr, *OriginPtr; 4861 const Align Alignment = Align(8); 4862 std::tie(ShadowPtr, OriginPtr) = 4863 MSV.getShadowOriginPtr(VAListTag, IRB, IRB.getInt8Ty(), Alignment, 4864 /*isStore*/ true); 4865 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), 4866 SystemZVAListTagSize, Alignment, false); 4867 } 4868 4869 void visitVAStartInst(VAStartInst &I) override { 4870 VAStartInstrumentationList.push_back(&I); 4871 unpoisonVAListTagForInst(I); 4872 } 4873 4874 void visitVACopyInst(VACopyInst &I) override { unpoisonVAListTagForInst(I); } 4875 4876 void copyRegSaveArea(IRBuilder<> &IRB, Value *VAListTag) { 4877 Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C); 4878 Value *RegSaveAreaPtrPtr = IRB.CreateIntToPtr( 4879 IRB.CreateAdd( 4880 IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), 4881 ConstantInt::get(MS.IntptrTy, SystemZRegSaveAreaPtrOffset)), 4882 PointerType::get(RegSaveAreaPtrTy, 0)); 4883 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr); 4884 Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr; 4885 const Align Alignment = Align(8); 4886 std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) = 4887 MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(), Alignment, 4888 /*isStore*/ true); 4889 // TODO(iii): copy only fragments filled by visitCallBase() 4890 IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment, 4891 SystemZRegSaveAreaSize); 4892 if (MS.TrackOrigins) 4893 IRB.CreateMemCpy(RegSaveAreaOriginPtr, Alignment, VAArgTLSOriginCopy, 4894 Alignment, SystemZRegSaveAreaSize); 4895 } 4896 4897 void copyOverflowArea(IRBuilder<> &IRB, Value *VAListTag) { 4898 Type *OverflowArgAreaPtrTy = Type::getInt64PtrTy(*MS.C); 4899 Value *OverflowArgAreaPtrPtr = IRB.CreateIntToPtr( 4900 IRB.CreateAdd( 4901 IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), 4902 ConstantInt::get(MS.IntptrTy, SystemZOverflowArgAreaPtrOffset)), 4903 PointerType::get(OverflowArgAreaPtrTy, 0)); 4904 Value *OverflowArgAreaPtr = 4905 IRB.CreateLoad(OverflowArgAreaPtrTy, OverflowArgAreaPtrPtr); 4906 Value *OverflowArgAreaShadowPtr, *OverflowArgAreaOriginPtr; 4907 const Align Alignment = Align(8); 4908 std::tie(OverflowArgAreaShadowPtr, OverflowArgAreaOriginPtr) = 4909 MSV.getShadowOriginPtr(OverflowArgAreaPtr, IRB, IRB.getInt8Ty(), 4910 Alignment, /*isStore*/ true); 4911 Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy, 4912 SystemZOverflowOffset); 4913 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, Alignment, SrcPtr, Alignment, 4914 VAArgOverflowSize); 4915 if (MS.TrackOrigins) { 4916 SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSOriginCopy, 4917 SystemZOverflowOffset); 4918 IRB.CreateMemCpy(OverflowArgAreaOriginPtr, Alignment, SrcPtr, Alignment, 4919 VAArgOverflowSize); 4920 } 4921 } 4922 4923 void finalizeInstrumentation() override { 4924 assert(!VAArgOverflowSize && !VAArgTLSCopy && 4925 "finalizeInstrumentation called twice"); 4926 if (!VAStartInstrumentationList.empty()) { 4927 // If there is a va_start in this function, make a backup copy of 4928 // va_arg_tls somewhere in the function entry block. 4929 IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI()); 4930 VAArgOverflowSize = 4931 IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS); 4932 Value *CopySize = 4933 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, SystemZOverflowOffset), 4934 VAArgOverflowSize); 4935 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize); 4936 IRB.CreateMemCpy(VAArgTLSCopy, Align(8), MS.VAArgTLS, Align(8), CopySize); 4937 if (MS.TrackOrigins) { 4938 VAArgTLSOriginCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize); 4939 IRB.CreateMemCpy(VAArgTLSOriginCopy, Align(8), MS.VAArgOriginTLS, 4940 Align(8), CopySize); 4941 } 4942 } 4943 4944 // Instrument va_start. 4945 // Copy va_list shadow from the backup copy of the TLS contents. 4946 for (size_t VaStartNo = 0, VaStartNum = VAStartInstrumentationList.size(); 4947 VaStartNo < VaStartNum; VaStartNo++) { 4948 CallInst *OrigInst = VAStartInstrumentationList[VaStartNo]; 4949 IRBuilder<> IRB(OrigInst->getNextNode()); 4950 Value *VAListTag = OrigInst->getArgOperand(0); 4951 copyRegSaveArea(IRB, VAListTag); 4952 copyOverflowArea(IRB, VAListTag); 4953 } 4954 } 4955 }; 4956 4957 /// A no-op implementation of VarArgHelper. 4958 struct VarArgNoOpHelper : public VarArgHelper { 4959 VarArgNoOpHelper(Function &F, MemorySanitizer &MS, 4960 MemorySanitizerVisitor &MSV) {} 4961 4962 void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override {} 4963 4964 void visitVAStartInst(VAStartInst &I) override {} 4965 4966 void visitVACopyInst(VACopyInst &I) override {} 4967 4968 void finalizeInstrumentation() override {} 4969 }; 4970 4971 } // end anonymous namespace 4972 4973 static VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan, 4974 MemorySanitizerVisitor &Visitor) { 4975 // VarArg handling is only implemented on AMD64. False positives are possible 4976 // on other platforms. 4977 Triple TargetTriple(Func.getParent()->getTargetTriple()); 4978 if (TargetTriple.getArch() == Triple::x86_64) 4979 return new VarArgAMD64Helper(Func, Msan, Visitor); 4980 else if (TargetTriple.isMIPS64()) 4981 return new VarArgMIPS64Helper(Func, Msan, Visitor); 4982 else if (TargetTriple.getArch() == Triple::aarch64) 4983 return new VarArgAArch64Helper(Func, Msan, Visitor); 4984 else if (TargetTriple.getArch() == Triple::ppc64 || 4985 TargetTriple.getArch() == Triple::ppc64le) 4986 return new VarArgPowerPC64Helper(Func, Msan, Visitor); 4987 else if (TargetTriple.getArch() == Triple::systemz) 4988 return new VarArgSystemZHelper(Func, Msan, Visitor); 4989 else 4990 return new VarArgNoOpHelper(Func, Msan, Visitor); 4991 } 4992 4993 bool MemorySanitizer::sanitizeFunction(Function &F, TargetLibraryInfo &TLI) { 4994 if (!CompileKernel && F.getName() == kMsanModuleCtorName) 4995 return false; 4996 4997 MemorySanitizerVisitor Visitor(F, *this, TLI); 4998 4999 // Clear out readonly/readnone attributes. 5000 AttrBuilder B; 5001 B.addAttribute(Attribute::ReadOnly) 5002 .addAttribute(Attribute::ReadNone) 5003 .addAttribute(Attribute::WriteOnly) 5004 .addAttribute(Attribute::ArgMemOnly) 5005 .addAttribute(Attribute::Speculatable); 5006 F.removeAttributes(AttributeList::FunctionIndex, B); 5007 5008 return Visitor.runOnFunction(); 5009 } 5010