Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1 | //===-- MemorySanitizer.cpp - detector of uninitialized reads -------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | /// \file |
| 10 | /// This file is a part of MemorySanitizer, a detector of uninitialized |
| 11 | /// reads. |
| 12 | /// |
| 13 | /// Status: early prototype. |
| 14 | /// |
| 15 | /// The algorithm of the tool is similar to Memcheck |
| 16 | /// (http://goo.gl/QKbem). We associate a few shadow bits with every |
| 17 | /// byte of the application memory, poison the shadow of the malloc-ed |
| 18 | /// or alloca-ed memory, load the shadow bits on every memory read, |
| 19 | /// propagate the shadow bits through some of the arithmetic |
| 20 | /// instruction (including MOV), store the shadow bits on every memory |
| 21 | /// write, report a bug on some other instructions (e.g. JMP) if the |
| 22 | /// associated shadow is poisoned. |
| 23 | /// |
| 24 | /// But there are differences too. The first and the major one: |
| 25 | /// compiler instrumentation instead of binary instrumentation. This |
| 26 | /// gives us much better register allocation, possible compiler |
| 27 | /// optimizations and a fast start-up. But this brings the major issue |
| 28 | /// as well: msan needs to see all program events, including system |
| 29 | /// calls and reads/writes in system libraries, so we either need to |
| 30 | /// compile *everything* with msan or use a binary translation |
| 31 | /// component (e.g. DynamoRIO) to instrument pre-built libraries. |
| 32 | /// Another difference from Memcheck is that we use 8 shadow bits per |
| 33 | /// byte of application memory and use a direct shadow mapping. This |
| 34 | /// greatly simplifies the instrumentation code and avoids races on |
| 35 | /// shadow updates (Memcheck is single-threaded so races are not a |
| 36 | /// concern there. Memcheck uses 2 shadow bits per byte with a slow |
| 37 | /// path storage that uses 8 bits per byte). |
| 38 | /// |
| 39 | /// The default value of shadow is 0, which means "clean" (not poisoned). |
| 40 | /// |
| 41 | /// Every module initializer should call __msan_init to ensure that the |
| 42 | /// shadow memory is ready. On error, __msan_warning is called. Since |
| 43 | /// parameters and return values may be passed via registers, we have a |
| 44 | /// specialized thread-local shadow for return values |
| 45 | /// (__msan_retval_tls) and parameters (__msan_param_tls). |
| 46 | //===----------------------------------------------------------------------===// |
| 47 | |
| 48 | #define DEBUG_TYPE "msan" |
| 49 | |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 50 | #include "llvm/Transforms/Instrumentation.h" |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 51 | #include "BlackList.h" |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 52 | #include "llvm/ADT/DepthFirstIterator.h" |
| 53 | #include "llvm/ADT/SmallString.h" |
| 54 | #include "llvm/ADT/SmallVector.h" |
| 55 | #include "llvm/ADT/ValueMap.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 56 | #include "llvm/DataLayout.h" |
| 57 | #include "llvm/Function.h" |
| 58 | #include "llvm/IRBuilder.h" |
| 59 | #include "llvm/InlineAsm.h" |
| 60 | #include "llvm/InstVisitor.h" |
| 61 | #include "llvm/IntrinsicInst.h" |
| 62 | #include "llvm/LLVMContext.h" |
| 63 | #include "llvm/MDBuilder.h" |
| 64 | #include "llvm/Module.h" |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 65 | #include "llvm/Support/CommandLine.h" |
| 66 | #include "llvm/Support/Compiler.h" |
| 67 | #include "llvm/Support/Debug.h" |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 68 | #include "llvm/Support/raw_ostream.h" |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 69 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 70 | #include "llvm/Transforms/Utils/ModuleUtils.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 71 | #include "llvm/Type.h" |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 72 | |
| 73 | using namespace llvm; |
| 74 | |
| 75 | static const uint64_t kShadowMask32 = 1ULL << 31; |
| 76 | static const uint64_t kShadowMask64 = 1ULL << 46; |
| 77 | static const uint64_t kOriginOffset32 = 1ULL << 30; |
| 78 | static const uint64_t kOriginOffset64 = 1ULL << 45; |
Evgeniy Stepanov | d2bd319 | 2012-12-11 12:34:09 +0000 | [diff] [blame] | 79 | static const uint64_t kShadowTLSAlignment = 8; |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 80 | |
| 81 | // This is an important flag that makes the reports much more |
| 82 | // informative at the cost of greater slowdown. Not fully implemented |
| 83 | // yet. |
| 84 | // FIXME: this should be a top-level clang flag, e.g. |
| 85 | // -fmemory-sanitizer-full. |
| 86 | static cl::opt<bool> ClTrackOrigins("msan-track-origins", |
| 87 | cl::desc("Track origins (allocation sites) of poisoned memory"), |
| 88 | cl::Hidden, cl::init(false)); |
| 89 | static cl::opt<bool> ClKeepGoing("msan-keep-going", |
| 90 | cl::desc("keep going after reporting a UMR"), |
| 91 | cl::Hidden, cl::init(false)); |
| 92 | static cl::opt<bool> ClPoisonStack("msan-poison-stack", |
| 93 | cl::desc("poison uninitialized stack variables"), |
| 94 | cl::Hidden, cl::init(true)); |
| 95 | static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call", |
| 96 | cl::desc("poison uninitialized stack variables with a call"), |
| 97 | cl::Hidden, cl::init(false)); |
| 98 | static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern", |
| 99 | cl::desc("poison uninitialized stack variables with the given patter"), |
| 100 | cl::Hidden, cl::init(0xff)); |
| 101 | |
| 102 | static cl::opt<bool> ClHandleICmp("msan-handle-icmp", |
| 103 | cl::desc("propagate shadow through ICmpEQ and ICmpNE"), |
| 104 | cl::Hidden, cl::init(true)); |
| 105 | |
Evgeniy Stepanov | 4f220d9 | 2012-12-06 11:41:03 +0000 | [diff] [blame] | 106 | static cl::opt<bool> ClStoreCleanOrigin("msan-store-clean-origin", |
| 107 | cl::desc("store origin for clean (fully initialized) values"), |
| 108 | cl::Hidden, cl::init(false)); |
| 109 | |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 110 | // This flag controls whether we check the shadow of the address |
| 111 | // operand of load or store. Such bugs are very rare, since load from |
| 112 | // a garbage address typically results in SEGV, but still happen |
| 113 | // (e.g. only lower bits of address are garbage, or the access happens |
| 114 | // early at program startup where malloc-ed memory is more likely to |
| 115 | // be zeroed. As of 2012-08-28 this flag adds 20% slowdown. |
| 116 | static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address", |
| 117 | cl::desc("report accesses through a pointer which has poisoned shadow"), |
| 118 | cl::Hidden, cl::init(true)); |
| 119 | |
| 120 | static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions", |
| 121 | cl::desc("print out instructions with default strict semantics"), |
| 122 | cl::Hidden, cl::init(false)); |
| 123 | |
| 124 | static cl::opt<std::string> ClBlackListFile("msan-blacklist", |
| 125 | cl::desc("File containing the list of functions where MemorySanitizer " |
| 126 | "should not report bugs"), cl::Hidden); |
| 127 | |
| 128 | namespace { |
| 129 | |
| 130 | /// \brief An instrumentation pass implementing detection of uninitialized |
| 131 | /// reads. |
| 132 | /// |
| 133 | /// MemorySanitizer: instrument the code in module to find |
| 134 | /// uninitialized reads. |
| 135 | class MemorySanitizer : public FunctionPass { |
| 136 | public: |
Evgeniy Stepanov | 94b257d | 2012-12-05 13:14:33 +0000 | [diff] [blame] | 137 | MemorySanitizer() : FunctionPass(ID), TD(0), WarningFn(0) { } |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 138 | const char *getPassName() const { return "MemorySanitizer"; } |
| 139 | bool runOnFunction(Function &F); |
| 140 | bool doInitialization(Module &M); |
| 141 | static char ID; // Pass identification, replacement for typeid. |
| 142 | |
| 143 | private: |
Evgeniy Stepanov | 94b257d | 2012-12-05 13:14:33 +0000 | [diff] [blame] | 144 | void initializeCallbacks(Module &M); |
| 145 | |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 146 | DataLayout *TD; |
| 147 | LLVMContext *C; |
| 148 | Type *IntptrTy; |
| 149 | Type *OriginTy; |
| 150 | /// \brief Thread-local shadow storage for function parameters. |
| 151 | GlobalVariable *ParamTLS; |
| 152 | /// \brief Thread-local origin storage for function parameters. |
| 153 | GlobalVariable *ParamOriginTLS; |
| 154 | /// \brief Thread-local shadow storage for function return value. |
| 155 | GlobalVariable *RetvalTLS; |
| 156 | /// \brief Thread-local origin storage for function return value. |
| 157 | GlobalVariable *RetvalOriginTLS; |
| 158 | /// \brief Thread-local shadow storage for in-register va_arg function |
| 159 | /// parameters (x86_64-specific). |
| 160 | GlobalVariable *VAArgTLS; |
| 161 | /// \brief Thread-local shadow storage for va_arg overflow area |
| 162 | /// (x86_64-specific). |
| 163 | GlobalVariable *VAArgOverflowSizeTLS; |
| 164 | /// \brief Thread-local space used to pass origin value to the UMR reporting |
| 165 | /// function. |
| 166 | GlobalVariable *OriginTLS; |
| 167 | |
| 168 | /// \brief The run-time callback to print a warning. |
| 169 | Value *WarningFn; |
| 170 | /// \brief Run-time helper that copies origin info for a memory range. |
| 171 | Value *MsanCopyOriginFn; |
| 172 | /// \brief Run-time helper that generates a new origin value for a stack |
| 173 | /// allocation. |
| 174 | Value *MsanSetAllocaOriginFn; |
| 175 | /// \brief Run-time helper that poisons stack on function entry. |
| 176 | Value *MsanPoisonStackFn; |
Evgeniy Stepanov | 62b5db9 | 2012-11-29 12:49:04 +0000 | [diff] [blame] | 177 | /// \brief MSan runtime replacements for memmove, memcpy and memset. |
| 178 | Value *MemmoveFn, *MemcpyFn, *MemsetFn; |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 179 | |
| 180 | /// \brief Address mask used in application-to-shadow address calculation. |
| 181 | /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask. |
| 182 | uint64_t ShadowMask; |
| 183 | /// \brief Offset of the origin shadow from the "normal" shadow. |
| 184 | /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL |
| 185 | uint64_t OriginOffset; |
| 186 | /// \brief Branch weights for error reporting. |
| 187 | MDNode *ColdCallWeights; |
Evgeniy Stepanov | 4f220d9 | 2012-12-06 11:41:03 +0000 | [diff] [blame] | 188 | /// \brief Branch weights for origin store. |
| 189 | MDNode *OriginStoreWeights; |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 190 | /// \brief The blacklist. |
| 191 | OwningPtr<BlackList> BL; |
Evgeniy Stepanov | 1d2da65 | 2012-11-29 12:30:18 +0000 | [diff] [blame] | 192 | /// \brief An empty volatile inline asm that prevents callback merge. |
| 193 | InlineAsm *EmptyAsm; |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 194 | |
Evgeniy Stepanov | da0072b | 2012-11-29 13:12:03 +0000 | [diff] [blame] | 195 | friend struct MemorySanitizerVisitor; |
| 196 | friend struct VarArgAMD64Helper; |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 197 | }; |
| 198 | } // namespace |
| 199 | |
| 200 | char MemorySanitizer::ID = 0; |
| 201 | INITIALIZE_PASS(MemorySanitizer, "msan", |
| 202 | "MemorySanitizer: detects uninitialized reads.", |
| 203 | false, false) |
| 204 | |
| 205 | FunctionPass *llvm::createMemorySanitizerPass() { |
| 206 | return new MemorySanitizer(); |
| 207 | } |
| 208 | |
| 209 | /// \brief Create a non-const global initialized with the given string. |
| 210 | /// |
| 211 | /// Creates a writable global for Str so that we can pass it to the |
| 212 | /// run-time lib. Runtime uses first 4 bytes of the string to store the |
| 213 | /// frame ID, so the string needs to be mutable. |
| 214 | static GlobalVariable *createPrivateNonConstGlobalForString(Module &M, |
| 215 | StringRef Str) { |
| 216 | Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str); |
| 217 | return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false, |
| 218 | GlobalValue::PrivateLinkage, StrConst, ""); |
| 219 | } |
| 220 | |
Evgeniy Stepanov | 94b257d | 2012-12-05 13:14:33 +0000 | [diff] [blame] | 221 | |
| 222 | /// \brief Insert extern declaration of runtime-provided functions and globals. |
| 223 | void MemorySanitizer::initializeCallbacks(Module &M) { |
| 224 | // Only do this once. |
| 225 | if (WarningFn) |
| 226 | return; |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 227 | |
| 228 | IRBuilder<> IRB(*C); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 229 | // Create the callback. |
| 230 | // FIXME: this function should have "Cold" calling conv, |
| 231 | // which is not yet implemented. |
| 232 | StringRef WarningFnName = ClKeepGoing ? "__msan_warning" |
| 233 | : "__msan_warning_noreturn"; |
| 234 | WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL); |
| 235 | |
| 236 | MsanCopyOriginFn = M.getOrInsertFunction( |
| 237 | "__msan_copy_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(), |
| 238 | IRB.getInt8PtrTy(), IntptrTy, NULL); |
| 239 | MsanSetAllocaOriginFn = M.getOrInsertFunction( |
| 240 | "__msan_set_alloca_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, |
| 241 | IRB.getInt8PtrTy(), NULL); |
| 242 | MsanPoisonStackFn = M.getOrInsertFunction( |
| 243 | "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL); |
| 244 | MemmoveFn = M.getOrInsertFunction( |
Evgeniy Stepanov | 62b5db9 | 2012-11-29 12:49:04 +0000 | [diff] [blame] | 245 | "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), |
| 246 | IntptrTy, NULL); |
| 247 | MemcpyFn = M.getOrInsertFunction( |
| 248 | "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), |
| 249 | IntptrTy, NULL); |
| 250 | MemsetFn = M.getOrInsertFunction( |
| 251 | "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(), |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 252 | IntptrTy, NULL); |
| 253 | |
| 254 | // Create globals. |
| 255 | RetvalTLS = new GlobalVariable( |
| 256 | M, ArrayType::get(IRB.getInt64Ty(), 8), false, |
| 257 | GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0, |
| 258 | GlobalVariable::GeneralDynamicTLSModel); |
| 259 | RetvalOriginTLS = new GlobalVariable( |
| 260 | M, OriginTy, false, GlobalVariable::ExternalLinkage, 0, |
| 261 | "__msan_retval_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel); |
| 262 | |
| 263 | ParamTLS = new GlobalVariable( |
| 264 | M, ArrayType::get(IRB.getInt64Ty(), 1000), false, |
| 265 | GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0, |
| 266 | GlobalVariable::GeneralDynamicTLSModel); |
| 267 | ParamOriginTLS = new GlobalVariable( |
| 268 | M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage, |
| 269 | 0, "__msan_param_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel); |
| 270 | |
| 271 | VAArgTLS = new GlobalVariable( |
| 272 | M, ArrayType::get(IRB.getInt64Ty(), 1000), false, |
| 273 | GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0, |
| 274 | GlobalVariable::GeneralDynamicTLSModel); |
| 275 | VAArgOverflowSizeTLS = new GlobalVariable( |
| 276 | M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0, |
| 277 | "__msan_va_arg_overflow_size_tls", 0, |
| 278 | GlobalVariable::GeneralDynamicTLSModel); |
| 279 | OriginTLS = new GlobalVariable( |
| 280 | M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0, |
| 281 | "__msan_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel); |
Evgeniy Stepanov | 1d2da65 | 2012-11-29 12:30:18 +0000 | [diff] [blame] | 282 | |
| 283 | // We insert an empty inline asm after __msan_report* to avoid callback merge. |
| 284 | EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false), |
| 285 | StringRef(""), StringRef(""), |
| 286 | /*hasSideEffects=*/true); |
Evgeniy Stepanov | 94b257d | 2012-12-05 13:14:33 +0000 | [diff] [blame] | 287 | } |
| 288 | |
| 289 | /// \brief Module-level initialization. |
| 290 | /// |
| 291 | /// inserts a call to __msan_init to the module's constructor list. |
| 292 | bool MemorySanitizer::doInitialization(Module &M) { |
| 293 | TD = getAnalysisIfAvailable<DataLayout>(); |
| 294 | if (!TD) |
| 295 | return false; |
| 296 | BL.reset(new BlackList(ClBlackListFile)); |
| 297 | C = &(M.getContext()); |
| 298 | unsigned PtrSize = TD->getPointerSizeInBits(/* AddressSpace */0); |
| 299 | switch (PtrSize) { |
| 300 | case 64: |
| 301 | ShadowMask = kShadowMask64; |
| 302 | OriginOffset = kOriginOffset64; |
| 303 | break; |
| 304 | case 32: |
| 305 | ShadowMask = kShadowMask32; |
| 306 | OriginOffset = kOriginOffset32; |
| 307 | break; |
| 308 | default: |
| 309 | report_fatal_error("unsupported pointer size"); |
| 310 | break; |
| 311 | } |
| 312 | |
| 313 | IRBuilder<> IRB(*C); |
| 314 | IntptrTy = IRB.getIntPtrTy(TD); |
| 315 | OriginTy = IRB.getInt32Ty(); |
| 316 | |
| 317 | ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000); |
Evgeniy Stepanov | 4f220d9 | 2012-12-06 11:41:03 +0000 | [diff] [blame] | 318 | OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000); |
Evgeniy Stepanov | 94b257d | 2012-12-05 13:14:33 +0000 | [diff] [blame] | 319 | |
| 320 | // Insert a call to __msan_init/__msan_track_origins into the module's CTORs. |
| 321 | appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction( |
| 322 | "__msan_init", IRB.getVoidTy(), NULL)), 0); |
| 323 | |
| 324 | new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage, |
| 325 | IRB.getInt32(ClTrackOrigins), "__msan_track_origins"); |
| 326 | |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 327 | return true; |
| 328 | } |
| 329 | |
| 330 | namespace { |
| 331 | |
| 332 | /// \brief A helper class that handles instrumentation of VarArg |
| 333 | /// functions on a particular platform. |
| 334 | /// |
| 335 | /// Implementations are expected to insert the instrumentation |
| 336 | /// necessary to propagate argument shadow through VarArg function |
| 337 | /// calls. Visit* methods are called during an InstVisitor pass over |
| 338 | /// the function, and should avoid creating new basic blocks. A new |
| 339 | /// instance of this class is created for each instrumented function. |
| 340 | struct VarArgHelper { |
| 341 | /// \brief Visit a CallSite. |
| 342 | virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0; |
| 343 | |
| 344 | /// \brief Visit a va_start call. |
| 345 | virtual void visitVAStartInst(VAStartInst &I) = 0; |
| 346 | |
| 347 | /// \brief Visit a va_copy call. |
| 348 | virtual void visitVACopyInst(VACopyInst &I) = 0; |
| 349 | |
| 350 | /// \brief Finalize function instrumentation. |
| 351 | /// |
| 352 | /// This method is called after visiting all interesting (see above) |
| 353 | /// instructions in a function. |
| 354 | virtual void finalizeInstrumentation() = 0; |
Evgeniy Stepanov | da0072b | 2012-11-29 13:12:03 +0000 | [diff] [blame] | 355 | |
| 356 | virtual ~VarArgHelper() {} |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 357 | }; |
| 358 | |
| 359 | struct MemorySanitizerVisitor; |
| 360 | |
| 361 | VarArgHelper* |
| 362 | CreateVarArgHelper(Function &Func, MemorySanitizer &Msan, |
| 363 | MemorySanitizerVisitor &Visitor); |
| 364 | |
| 365 | /// This class does all the work for a given function. Store and Load |
| 366 | /// instructions store and load corresponding shadow and origin |
| 367 | /// values. Most instructions propagate shadow from arguments to their |
| 368 | /// return values. Certain instructions (most importantly, BranchInst) |
| 369 | /// test their argument shadow and print reports (with a runtime call) if it's |
| 370 | /// non-zero. |
| 371 | struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> { |
| 372 | Function &F; |
| 373 | MemorySanitizer &MS; |
| 374 | SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes; |
| 375 | ValueMap<Value*, Value*> ShadowMap, OriginMap; |
| 376 | bool InsertChecks; |
| 377 | OwningPtr<VarArgHelper> VAHelper; |
| 378 | |
| 379 | // An unfortunate workaround for asymmetric lowering of va_arg stuff. |
| 380 | // See a comment in visitCallSite for more details. |
| 381 | static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7 |
| 382 | static const unsigned AMD64FpEndOffset = 176; |
| 383 | |
| 384 | struct ShadowOriginAndInsertPoint { |
| 385 | Instruction *Shadow; |
| 386 | Instruction *Origin; |
| 387 | Instruction *OrigIns; |
| 388 | ShadowOriginAndInsertPoint(Instruction *S, Instruction *O, Instruction *I) |
| 389 | : Shadow(S), Origin(O), OrigIns(I) { } |
| 390 | ShadowOriginAndInsertPoint() : Shadow(0), Origin(0), OrigIns(0) { } |
| 391 | }; |
| 392 | SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList; |
Evgeniy Stepanov | 4f220d9 | 2012-12-06 11:41:03 +0000 | [diff] [blame] | 393 | SmallVector<Instruction*, 16> StoreList; |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 394 | |
| 395 | MemorySanitizerVisitor(Function &F, MemorySanitizer &MS) |
| 396 | : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) { |
| 397 | InsertChecks = !MS.BL->isIn(F); |
| 398 | DEBUG(if (!InsertChecks) |
| 399 | dbgs() << "MemorySanitizer is not inserting checks into '" |
| 400 | << F.getName() << "'\n"); |
| 401 | } |
| 402 | |
Evgeniy Stepanov | 4f220d9 | 2012-12-06 11:41:03 +0000 | [diff] [blame] | 403 | void materializeStores() { |
| 404 | for (size_t i = 0, n = StoreList.size(); i < n; i++) { |
| 405 | StoreInst& I = *dyn_cast<StoreInst>(StoreList[i]); |
| 406 | |
| 407 | IRBuilder<> IRB(&I); |
| 408 | Value *Val = I.getValueOperand(); |
| 409 | Value *Addr = I.getPointerOperand(); |
| 410 | Value *Shadow = getShadow(Val); |
| 411 | Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB); |
| 412 | |
| 413 | StoreInst *NewSI = IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment()); |
| 414 | DEBUG(dbgs() << " STORE: " << *NewSI << "\n"); |
NAKAMURA Takumi | e0b1b46 | 2012-12-06 13:38:00 +0000 | [diff] [blame] | 415 | (void)NewSI; |
Evgeniy Stepanov | 4f220d9 | 2012-12-06 11:41:03 +0000 | [diff] [blame] | 416 | // If the store is volatile, add a check. |
| 417 | if (I.isVolatile()) |
| 418 | insertCheck(Val, &I); |
| 419 | if (ClCheckAccessAddress) |
| 420 | insertCheck(Addr, &I); |
| 421 | |
| 422 | if (ClTrackOrigins) { |
| 423 | if (ClStoreCleanOrigin || isa<StructType>(Shadow->getType())) { |
Evgeniy Stepanov | 49175b2 | 2012-12-14 13:43:11 +0000 | [diff] [blame^] | 424 | IRB.CreateStore(getOrigin(Val), getOriginPtr(Addr, IRB)); |
Evgeniy Stepanov | 4f220d9 | 2012-12-06 11:41:03 +0000 | [diff] [blame] | 425 | } else { |
| 426 | Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB); |
| 427 | |
| 428 | Constant *Cst = dyn_cast_or_null<Constant>(ConvertedShadow); |
| 429 | // TODO(eugenis): handle non-zero constant shadow by inserting an |
| 430 | // unconditional check (can not simply fail compilation as this could |
| 431 | // be in the dead code). |
| 432 | if (Cst) |
| 433 | continue; |
| 434 | |
| 435 | Value *Cmp = IRB.CreateICmpNE(ConvertedShadow, |
| 436 | getCleanShadow(ConvertedShadow), "_mscmp"); |
| 437 | Instruction *CheckTerm = |
Evgeniy Stepanov | 49175b2 | 2012-12-14 13:43:11 +0000 | [diff] [blame^] | 438 | SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false, |
| 439 | MS.OriginStoreWeights); |
| 440 | IRBuilder<> IRBNew(CheckTerm); |
| 441 | IRBNew.CreateStore(getOrigin(Val), getOriginPtr(Addr, IRBNew)); |
Evgeniy Stepanov | 4f220d9 | 2012-12-06 11:41:03 +0000 | [diff] [blame] | 442 | } |
| 443 | } |
| 444 | } |
| 445 | } |
| 446 | |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 447 | void materializeChecks() { |
| 448 | for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) { |
| 449 | Instruction *Shadow = InstrumentationList[i].Shadow; |
| 450 | Instruction *OrigIns = InstrumentationList[i].OrigIns; |
| 451 | IRBuilder<> IRB(OrigIns); |
| 452 | DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n"); |
| 453 | Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB); |
| 454 | DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n"); |
| 455 | Value *Cmp = IRB.CreateICmpNE(ConvertedShadow, |
| 456 | getCleanShadow(ConvertedShadow), "_mscmp"); |
| 457 | Instruction *CheckTerm = |
| 458 | SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), |
| 459 | /* Unreachable */ !ClKeepGoing, |
| 460 | MS.ColdCallWeights); |
| 461 | |
| 462 | IRB.SetInsertPoint(CheckTerm); |
| 463 | if (ClTrackOrigins) { |
| 464 | Instruction *Origin = InstrumentationList[i].Origin; |
| 465 | IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0), |
| 466 | MS.OriginTLS); |
| 467 | } |
| 468 | CallInst *Call = IRB.CreateCall(MS.WarningFn); |
| 469 | Call->setDebugLoc(OrigIns->getDebugLoc()); |
Evgeniy Stepanov | 1d2da65 | 2012-11-29 12:30:18 +0000 | [diff] [blame] | 470 | IRB.CreateCall(MS.EmptyAsm); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 471 | DEBUG(dbgs() << " CHECK: " << *Cmp << "\n"); |
| 472 | } |
| 473 | DEBUG(dbgs() << "DONE:\n" << F); |
| 474 | } |
| 475 | |
| 476 | /// \brief Add MemorySanitizer instrumentation to a function. |
| 477 | bool runOnFunction() { |
Evgeniy Stepanov | 94b257d | 2012-12-05 13:14:33 +0000 | [diff] [blame] | 478 | MS.initializeCallbacks(*F.getParent()); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 479 | if (!MS.TD) return false; |
| 480 | // Iterate all BBs in depth-first order and create shadow instructions |
| 481 | // for all instructions (where applicable). |
| 482 | // For PHI nodes we create dummy shadow PHIs which will be finalized later. |
| 483 | for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()), |
| 484 | DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) { |
| 485 | BasicBlock *BB = *DI; |
| 486 | visit(*BB); |
| 487 | } |
| 488 | |
| 489 | // Finalize PHI nodes. |
| 490 | for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) { |
| 491 | PHINode *PN = ShadowPHINodes[i]; |
| 492 | PHINode *PNS = cast<PHINode>(getShadow(PN)); |
| 493 | PHINode *PNO = ClTrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0; |
| 494 | size_t NumValues = PN->getNumIncomingValues(); |
| 495 | for (size_t v = 0; v < NumValues; v++) { |
| 496 | PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v)); |
| 497 | if (PNO) |
| 498 | PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v)); |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | VAHelper->finalizeInstrumentation(); |
| 503 | |
Evgeniy Stepanov | 4f220d9 | 2012-12-06 11:41:03 +0000 | [diff] [blame] | 504 | // Delayed instrumentation of StoreInst. |
Evgeniy Stepanov | 47ac9ba | 2012-12-06 11:58:59 +0000 | [diff] [blame] | 505 | // This may add new checks to be inserted later. |
Evgeniy Stepanov | 4f220d9 | 2012-12-06 11:41:03 +0000 | [diff] [blame] | 506 | materializeStores(); |
| 507 | |
| 508 | // Insert shadow value checks. |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 509 | materializeChecks(); |
| 510 | |
| 511 | return true; |
| 512 | } |
| 513 | |
| 514 | /// \brief Compute the shadow type that corresponds to a given Value. |
| 515 | Type *getShadowTy(Value *V) { |
| 516 | return getShadowTy(V->getType()); |
| 517 | } |
| 518 | |
| 519 | /// \brief Compute the shadow type that corresponds to a given Type. |
| 520 | Type *getShadowTy(Type *OrigTy) { |
| 521 | if (!OrigTy->isSized()) { |
| 522 | return 0; |
| 523 | } |
| 524 | // For integer type, shadow is the same as the original type. |
| 525 | // This may return weird-sized types like i1. |
| 526 | if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy)) |
| 527 | return IT; |
| 528 | if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) |
| 529 | return VectorType::getInteger(VT); |
| 530 | if (StructType *ST = dyn_cast<StructType>(OrigTy)) { |
| 531 | SmallVector<Type*, 4> Elements; |
| 532 | for (unsigned i = 0, n = ST->getNumElements(); i < n; i++) |
| 533 | Elements.push_back(getShadowTy(ST->getElementType(i))); |
| 534 | StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked()); |
| 535 | DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n"); |
| 536 | return Res; |
| 537 | } |
| 538 | uint32_t TypeSize = MS.TD->getTypeStoreSizeInBits(OrigTy); |
| 539 | return IntegerType::get(*MS.C, TypeSize); |
| 540 | } |
| 541 | |
| 542 | /// \brief Flatten a vector type. |
| 543 | Type *getShadowTyNoVec(Type *ty) { |
| 544 | if (VectorType *vt = dyn_cast<VectorType>(ty)) |
| 545 | return IntegerType::get(*MS.C, vt->getBitWidth()); |
| 546 | return ty; |
| 547 | } |
| 548 | |
| 549 | /// \brief Convert a shadow value to it's flattened variant. |
| 550 | Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) { |
| 551 | Type *Ty = V->getType(); |
| 552 | Type *NoVecTy = getShadowTyNoVec(Ty); |
| 553 | if (Ty == NoVecTy) return V; |
| 554 | return IRB.CreateBitCast(V, NoVecTy); |
| 555 | } |
| 556 | |
| 557 | /// \brief Compute the shadow address that corresponds to a given application |
| 558 | /// address. |
| 559 | /// |
| 560 | /// Shadow = Addr & ~ShadowMask. |
| 561 | Value *getShadowPtr(Value *Addr, Type *ShadowTy, |
| 562 | IRBuilder<> &IRB) { |
| 563 | Value *ShadowLong = |
| 564 | IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy), |
| 565 | ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask)); |
| 566 | return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0)); |
| 567 | } |
| 568 | |
| 569 | /// \brief Compute the origin address that corresponds to a given application |
| 570 | /// address. |
| 571 | /// |
| 572 | /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 573 | Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) { |
| 574 | Value *ShadowLong = |
| 575 | IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy), |
Evgeniy Stepanov | 62ba611 | 2012-11-29 13:43:05 +0000 | [diff] [blame] | 576 | ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask)); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 577 | Value *Add = |
| 578 | IRB.CreateAdd(ShadowLong, |
| 579 | ConstantInt::get(MS.IntptrTy, MS.OriginOffset)); |
Evgeniy Stepanov | 62ba611 | 2012-11-29 13:43:05 +0000 | [diff] [blame] | 580 | Value *SecondAnd = |
| 581 | IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL)); |
| 582 | return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0)); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 583 | } |
| 584 | |
| 585 | /// \brief Compute the shadow address for a given function argument. |
| 586 | /// |
| 587 | /// Shadow = ParamTLS+ArgOffset. |
| 588 | Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB, |
| 589 | int ArgOffset) { |
| 590 | Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy); |
| 591 | Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); |
| 592 | return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0), |
| 593 | "_msarg"); |
| 594 | } |
| 595 | |
| 596 | /// \brief Compute the origin address for a given function argument. |
| 597 | Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB, |
| 598 | int ArgOffset) { |
| 599 | if (!ClTrackOrigins) return 0; |
| 600 | Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy); |
| 601 | Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); |
| 602 | return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0), |
| 603 | "_msarg_o"); |
| 604 | } |
| 605 | |
| 606 | /// \brief Compute the shadow address for a retval. |
| 607 | Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) { |
| 608 | Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy); |
| 609 | return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0), |
| 610 | "_msret"); |
| 611 | } |
| 612 | |
| 613 | /// \brief Compute the origin address for a retval. |
| 614 | Value *getOriginPtrForRetval(IRBuilder<> &IRB) { |
| 615 | // We keep a single origin for the entire retval. Might be too optimistic. |
| 616 | return MS.RetvalOriginTLS; |
| 617 | } |
| 618 | |
| 619 | /// \brief Set SV to be the shadow value for V. |
| 620 | void setShadow(Value *V, Value *SV) { |
| 621 | assert(!ShadowMap.count(V) && "Values may only have one shadow"); |
| 622 | ShadowMap[V] = SV; |
| 623 | } |
| 624 | |
| 625 | /// \brief Set Origin to be the origin value for V. |
| 626 | void setOrigin(Value *V, Value *Origin) { |
| 627 | if (!ClTrackOrigins) return; |
| 628 | assert(!OriginMap.count(V) && "Values may only have one origin"); |
| 629 | DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n"); |
| 630 | OriginMap[V] = Origin; |
| 631 | } |
| 632 | |
| 633 | /// \brief Create a clean shadow value for a given value. |
| 634 | /// |
| 635 | /// Clean shadow (all zeroes) means all bits of the value are defined |
| 636 | /// (initialized). |
| 637 | Value *getCleanShadow(Value *V) { |
| 638 | Type *ShadowTy = getShadowTy(V); |
| 639 | if (!ShadowTy) |
| 640 | return 0; |
| 641 | return Constant::getNullValue(ShadowTy); |
| 642 | } |
| 643 | |
| 644 | /// \brief Create a dirty shadow of a given shadow type. |
| 645 | Constant *getPoisonedShadow(Type *ShadowTy) { |
| 646 | assert(ShadowTy); |
| 647 | if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) |
| 648 | return Constant::getAllOnesValue(ShadowTy); |
| 649 | StructType *ST = cast<StructType>(ShadowTy); |
| 650 | SmallVector<Constant *, 4> Vals; |
| 651 | for (unsigned i = 0, n = ST->getNumElements(); i < n; i++) |
| 652 | Vals.push_back(getPoisonedShadow(ST->getElementType(i))); |
| 653 | return ConstantStruct::get(ST, Vals); |
| 654 | } |
| 655 | |
| 656 | /// \brief Create a clean (zero) origin. |
| 657 | Value *getCleanOrigin() { |
| 658 | return Constant::getNullValue(MS.OriginTy); |
| 659 | } |
| 660 | |
| 661 | /// \brief Get the shadow value for a given Value. |
| 662 | /// |
| 663 | /// This function either returns the value set earlier with setShadow, |
| 664 | /// or extracts if from ParamTLS (for function arguments). |
| 665 | Value *getShadow(Value *V) { |
| 666 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
| 667 | // For instructions the shadow is already stored in the map. |
| 668 | Value *Shadow = ShadowMap[V]; |
| 669 | if (!Shadow) { |
| 670 | DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent())); |
Matt Beaumont-Gay | c76536f | 2012-11-29 18:15:49 +0000 | [diff] [blame] | 671 | (void)I; |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 672 | assert(Shadow && "No shadow for a value"); |
| 673 | } |
| 674 | return Shadow; |
| 675 | } |
| 676 | if (UndefValue *U = dyn_cast<UndefValue>(V)) { |
| 677 | Value *AllOnes = getPoisonedShadow(getShadowTy(V)); |
| 678 | DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n"); |
Matt Beaumont-Gay | c76536f | 2012-11-29 18:15:49 +0000 | [diff] [blame] | 679 | (void)U; |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 680 | return AllOnes; |
| 681 | } |
| 682 | if (Argument *A = dyn_cast<Argument>(V)) { |
| 683 | // For arguments we compute the shadow on demand and store it in the map. |
| 684 | Value **ShadowPtr = &ShadowMap[V]; |
| 685 | if (*ShadowPtr) |
| 686 | return *ShadowPtr; |
| 687 | Function *F = A->getParent(); |
| 688 | IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI()); |
| 689 | unsigned ArgOffset = 0; |
| 690 | for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end(); |
| 691 | AI != AE; ++AI) { |
| 692 | if (!AI->getType()->isSized()) { |
| 693 | DEBUG(dbgs() << "Arg is not sized\n"); |
| 694 | continue; |
| 695 | } |
| 696 | unsigned Size = AI->hasByValAttr() |
| 697 | ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType()) |
| 698 | : MS.TD->getTypeAllocSize(AI->getType()); |
| 699 | if (A == AI) { |
| 700 | Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset); |
| 701 | if (AI->hasByValAttr()) { |
| 702 | // ByVal pointer itself has clean shadow. We copy the actual |
| 703 | // argument shadow to the underlying memory. |
| 704 | Value *Cpy = EntryIRB.CreateMemCpy( |
| 705 | getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), |
| 706 | Base, Size, AI->getParamAlignment()); |
| 707 | DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n"); |
Matt Beaumont-Gay | c76536f | 2012-11-29 18:15:49 +0000 | [diff] [blame] | 708 | (void)Cpy; |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 709 | *ShadowPtr = getCleanShadow(V); |
| 710 | } else { |
| 711 | *ShadowPtr = EntryIRB.CreateLoad(Base); |
| 712 | } |
| 713 | DEBUG(dbgs() << " ARG: " << *AI << " ==> " << |
| 714 | **ShadowPtr << "\n"); |
| 715 | if (ClTrackOrigins) { |
| 716 | Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset); |
| 717 | setOrigin(A, EntryIRB.CreateLoad(OriginPtr)); |
| 718 | } |
| 719 | } |
| 720 | ArgOffset += DataLayout::RoundUpAlignment(Size, 8); |
| 721 | } |
| 722 | assert(*ShadowPtr && "Could not find shadow for an argument"); |
| 723 | return *ShadowPtr; |
| 724 | } |
| 725 | // For everything else the shadow is zero. |
| 726 | return getCleanShadow(V); |
| 727 | } |
| 728 | |
| 729 | /// \brief Get the shadow for i-th argument of the instruction I. |
| 730 | Value *getShadow(Instruction *I, int i) { |
| 731 | return getShadow(I->getOperand(i)); |
| 732 | } |
| 733 | |
| 734 | /// \brief Get the origin for a value. |
| 735 | Value *getOrigin(Value *V) { |
| 736 | if (!ClTrackOrigins) return 0; |
| 737 | if (isa<Instruction>(V) || isa<Argument>(V)) { |
| 738 | Value *Origin = OriginMap[V]; |
| 739 | if (!Origin) { |
| 740 | DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n"); |
| 741 | Origin = getCleanOrigin(); |
| 742 | } |
| 743 | return Origin; |
| 744 | } |
| 745 | return getCleanOrigin(); |
| 746 | } |
| 747 | |
| 748 | /// \brief Get the origin for i-th argument of the instruction I. |
| 749 | Value *getOrigin(Instruction *I, int i) { |
| 750 | return getOrigin(I->getOperand(i)); |
| 751 | } |
| 752 | |
| 753 | /// \brief Remember the place where a shadow check should be inserted. |
| 754 | /// |
| 755 | /// This location will be later instrumented with a check that will print a |
| 756 | /// UMR warning in runtime if the value is not fully defined. |
| 757 | void insertCheck(Value *Val, Instruction *OrigIns) { |
| 758 | assert(Val); |
| 759 | if (!InsertChecks) return; |
| 760 | Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val)); |
| 761 | if (!Shadow) return; |
Matt Beaumont-Gay | c76536f | 2012-11-29 18:15:49 +0000 | [diff] [blame] | 762 | #ifndef NDEBUG |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 763 | Type *ShadowTy = Shadow->getType(); |
| 764 | assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) && |
| 765 | "Can only insert checks for integer and vector shadow types"); |
Matt Beaumont-Gay | c76536f | 2012-11-29 18:15:49 +0000 | [diff] [blame] | 766 | #endif |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 767 | Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val)); |
| 768 | InstrumentationList.push_back( |
| 769 | ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns)); |
| 770 | } |
| 771 | |
| 772 | //------------------- Visitors. |
| 773 | |
| 774 | /// \brief Instrument LoadInst |
| 775 | /// |
| 776 | /// Loads the corresponding shadow and (optionally) origin. |
| 777 | /// Optionally, checks that the load address is fully defined. |
| 778 | void visitLoadInst(LoadInst &I) { |
Matt Beaumont-Gay | c76536f | 2012-11-29 18:15:49 +0000 | [diff] [blame] | 779 | assert(I.getType()->isSized() && "Load type must have size"); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 780 | IRBuilder<> IRB(&I); |
| 781 | Type *ShadowTy = getShadowTy(&I); |
| 782 | Value *Addr = I.getPointerOperand(); |
| 783 | Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB); |
Evgeniy Stepanov | eeb8b7c | 2012-11-29 14:05:53 +0000 | [diff] [blame] | 784 | setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld")); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 785 | |
| 786 | if (ClCheckAccessAddress) |
| 787 | insertCheck(I.getPointerOperand(), &I); |
| 788 | |
| 789 | if (ClTrackOrigins) |
Evgeniy Stepanov | 49175b2 | 2012-12-14 13:43:11 +0000 | [diff] [blame^] | 790 | setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB))); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 791 | } |
| 792 | |
| 793 | /// \brief Instrument StoreInst |
| 794 | /// |
| 795 | /// Stores the corresponding shadow and (optionally) origin. |
| 796 | /// Optionally, checks that the store address is fully defined. |
| 797 | /// Volatile stores check that the value being stored is fully defined. |
| 798 | void visitStoreInst(StoreInst &I) { |
Evgeniy Stepanov | 4f220d9 | 2012-12-06 11:41:03 +0000 | [diff] [blame] | 799 | StoreList.push_back(&I); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 800 | } |
| 801 | |
Evgeniy Stepanov | 30484fc | 2012-11-29 15:22:06 +0000 | [diff] [blame] | 802 | // Vector manipulation. |
| 803 | void visitExtractElementInst(ExtractElementInst &I) { |
| 804 | insertCheck(I.getOperand(1), &I); |
| 805 | IRBuilder<> IRB(&I); |
| 806 | setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1), |
| 807 | "_msprop")); |
| 808 | setOrigin(&I, getOrigin(&I, 0)); |
| 809 | } |
| 810 | |
| 811 | void visitInsertElementInst(InsertElementInst &I) { |
| 812 | insertCheck(I.getOperand(2), &I); |
| 813 | IRBuilder<> IRB(&I); |
| 814 | setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1), |
| 815 | I.getOperand(2), "_msprop")); |
| 816 | setOriginForNaryOp(I); |
| 817 | } |
| 818 | |
| 819 | void visitShuffleVectorInst(ShuffleVectorInst &I) { |
| 820 | insertCheck(I.getOperand(2), &I); |
| 821 | IRBuilder<> IRB(&I); |
| 822 | setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1), |
| 823 | I.getOperand(2), "_msprop")); |
| 824 | setOriginForNaryOp(I); |
| 825 | } |
| 826 | |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 827 | // Casts. |
| 828 | void visitSExtInst(SExtInst &I) { |
| 829 | IRBuilder<> IRB(&I); |
| 830 | setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop")); |
| 831 | setOrigin(&I, getOrigin(&I, 0)); |
| 832 | } |
| 833 | |
| 834 | void visitZExtInst(ZExtInst &I) { |
| 835 | IRBuilder<> IRB(&I); |
| 836 | setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop")); |
| 837 | setOrigin(&I, getOrigin(&I, 0)); |
| 838 | } |
| 839 | |
| 840 | void visitTruncInst(TruncInst &I) { |
| 841 | IRBuilder<> IRB(&I); |
| 842 | setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop")); |
| 843 | setOrigin(&I, getOrigin(&I, 0)); |
| 844 | } |
| 845 | |
| 846 | void visitBitCastInst(BitCastInst &I) { |
| 847 | IRBuilder<> IRB(&I); |
| 848 | setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I))); |
| 849 | setOrigin(&I, getOrigin(&I, 0)); |
| 850 | } |
| 851 | |
| 852 | void visitPtrToIntInst(PtrToIntInst &I) { |
| 853 | IRBuilder<> IRB(&I); |
| 854 | setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false, |
| 855 | "_msprop_ptrtoint")); |
| 856 | setOrigin(&I, getOrigin(&I, 0)); |
| 857 | } |
| 858 | |
| 859 | void visitIntToPtrInst(IntToPtrInst &I) { |
| 860 | IRBuilder<> IRB(&I); |
| 861 | setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false, |
| 862 | "_msprop_inttoptr")); |
| 863 | setOrigin(&I, getOrigin(&I, 0)); |
| 864 | } |
| 865 | |
| 866 | void visitFPToSIInst(CastInst& I) { handleShadowOr(I); } |
| 867 | void visitFPToUIInst(CastInst& I) { handleShadowOr(I); } |
| 868 | void visitSIToFPInst(CastInst& I) { handleShadowOr(I); } |
| 869 | void visitUIToFPInst(CastInst& I) { handleShadowOr(I); } |
| 870 | void visitFPExtInst(CastInst& I) { handleShadowOr(I); } |
| 871 | void visitFPTruncInst(CastInst& I) { handleShadowOr(I); } |
| 872 | |
| 873 | /// \brief Propagate shadow for bitwise AND. |
| 874 | /// |
| 875 | /// This code is exact, i.e. if, for example, a bit in the left argument |
| 876 | /// is defined and 0, then neither the value not definedness of the |
| 877 | /// corresponding bit in B don't affect the resulting shadow. |
| 878 | void visitAnd(BinaryOperator &I) { |
| 879 | IRBuilder<> IRB(&I); |
| 880 | // "And" of 0 and a poisoned value results in unpoisoned value. |
| 881 | // 1&1 => 1; 0&1 => 0; p&1 => p; |
| 882 | // 1&0 => 0; 0&0 => 0; p&0 => 0; |
| 883 | // 1&p => p; 0&p => 0; p&p => p; |
| 884 | // S = (S1 & S2) | (V1 & S2) | (S1 & V2) |
| 885 | Value *S1 = getShadow(&I, 0); |
| 886 | Value *S2 = getShadow(&I, 1); |
| 887 | Value *V1 = I.getOperand(0); |
| 888 | Value *V2 = I.getOperand(1); |
| 889 | if (V1->getType() != S1->getType()) { |
| 890 | V1 = IRB.CreateIntCast(V1, S1->getType(), false); |
| 891 | V2 = IRB.CreateIntCast(V2, S2->getType(), false); |
| 892 | } |
| 893 | Value *S1S2 = IRB.CreateAnd(S1, S2); |
| 894 | Value *V1S2 = IRB.CreateAnd(V1, S2); |
| 895 | Value *S1V2 = IRB.CreateAnd(S1, V2); |
| 896 | setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2))); |
| 897 | setOriginForNaryOp(I); |
| 898 | } |
| 899 | |
| 900 | void visitOr(BinaryOperator &I) { |
| 901 | IRBuilder<> IRB(&I); |
| 902 | // "Or" of 1 and a poisoned value results in unpoisoned value. |
| 903 | // 1|1 => 1; 0|1 => 1; p|1 => 1; |
| 904 | // 1|0 => 1; 0|0 => 0; p|0 => p; |
| 905 | // 1|p => 1; 0|p => p; p|p => p; |
| 906 | // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2) |
| 907 | Value *S1 = getShadow(&I, 0); |
| 908 | Value *S2 = getShadow(&I, 1); |
| 909 | Value *V1 = IRB.CreateNot(I.getOperand(0)); |
| 910 | Value *V2 = IRB.CreateNot(I.getOperand(1)); |
| 911 | if (V1->getType() != S1->getType()) { |
| 912 | V1 = IRB.CreateIntCast(V1, S1->getType(), false); |
| 913 | V2 = IRB.CreateIntCast(V2, S2->getType(), false); |
| 914 | } |
| 915 | Value *S1S2 = IRB.CreateAnd(S1, S2); |
| 916 | Value *V1S2 = IRB.CreateAnd(V1, S2); |
| 917 | Value *S1V2 = IRB.CreateAnd(S1, V2); |
| 918 | setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2))); |
| 919 | setOriginForNaryOp(I); |
| 920 | } |
| 921 | |
Evgeniy Stepanov | f18e3af | 2012-12-14 12:54:18 +0000 | [diff] [blame] | 922 | /// \brief Default propagation of shadow and/or origin. |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 923 | /// |
Evgeniy Stepanov | f18e3af | 2012-12-14 12:54:18 +0000 | [diff] [blame] | 924 | /// This class implements the general case of shadow propagation, used in all |
| 925 | /// cases where we don't know and/or don't care about what the operation |
| 926 | /// actually does. It converts all input shadow values to a common type |
| 927 | /// (extending or truncating as necessary), and bitwise OR's them. |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 928 | /// |
| 929 | /// This is much cheaper than inserting checks (i.e. requiring inputs to be |
| 930 | /// fully initialized), and less prone to false positives. |
Evgeniy Stepanov | f18e3af | 2012-12-14 12:54:18 +0000 | [diff] [blame] | 931 | /// |
| 932 | /// This class also implements the general case of origin propagation. For a |
| 933 | /// Nary operation, result origin is set to the origin of an argument that is |
| 934 | /// not entirely initialized. If there is more than one such arguments, the |
| 935 | /// rightmost of them is picked. It does not matter which one is picked if all |
| 936 | /// arguments are initialized. |
| 937 | template <bool CombineShadow> |
| 938 | class Combiner { |
| 939 | Value *Shadow; |
| 940 | Value *Origin; |
| 941 | IRBuilder<> &IRB; |
| 942 | MemorySanitizerVisitor *MSV; |
| 943 | public: |
| 944 | Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) : |
| 945 | Shadow(0), Origin(0), IRB(IRB), MSV(MSV) {} |
| 946 | |
| 947 | /// \brief Add a pair of shadow and origin values to the mix. |
| 948 | Combiner &Add(Value *OpShadow, Value *OpOrigin) { |
| 949 | if (CombineShadow) { |
| 950 | assert(OpShadow); |
| 951 | if (!Shadow) |
| 952 | Shadow = OpShadow; |
| 953 | else { |
| 954 | OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType()); |
| 955 | Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop"); |
| 956 | } |
| 957 | } |
| 958 | |
| 959 | if (ClTrackOrigins) { |
| 960 | assert(OpOrigin); |
| 961 | if (!Origin) { |
| 962 | Origin = OpOrigin; |
| 963 | } else { |
| 964 | Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB); |
| 965 | Value *Cond = IRB.CreateICmpNE(FlatShadow, |
| 966 | MSV->getCleanShadow(FlatShadow)); |
| 967 | Origin = IRB.CreateSelect(Cond, OpOrigin, Origin); |
| 968 | } |
| 969 | } |
| 970 | return *this; |
| 971 | } |
| 972 | |
| 973 | /// \brief Add an application value to the mix. |
| 974 | Combiner &Add(Value *V) { |
| 975 | Value *OpShadow = MSV->getShadow(V); |
| 976 | Value *OpOrigin = ClTrackOrigins ? MSV->getOrigin(V) : 0; |
| 977 | return Add(OpShadow, OpOrigin); |
| 978 | } |
| 979 | |
| 980 | /// \brief Set the current combined values as the given instruction's shadow |
| 981 | /// and origin. |
| 982 | void Done(Instruction *I) { |
| 983 | if (CombineShadow) { |
| 984 | assert(Shadow); |
| 985 | Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I)); |
| 986 | MSV->setShadow(I, Shadow); |
| 987 | } |
| 988 | if (ClTrackOrigins) { |
| 989 | assert(Origin); |
| 990 | MSV->setOrigin(I, Origin); |
| 991 | } |
| 992 | } |
| 993 | }; |
| 994 | |
| 995 | typedef Combiner<true> ShadowAndOriginCombiner; |
| 996 | typedef Combiner<false> OriginCombiner; |
| 997 | |
| 998 | /// \brief Propagate origin for arbitrary operation. |
| 999 | void setOriginForNaryOp(Instruction &I) { |
| 1000 | if (!ClTrackOrigins) return; |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1001 | IRBuilder<> IRB(&I); |
Evgeniy Stepanov | f18e3af | 2012-12-14 12:54:18 +0000 | [diff] [blame] | 1002 | OriginCombiner OC(this, IRB); |
| 1003 | for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI) |
| 1004 | OC.Add(OI->get()); |
| 1005 | OC.Done(&I); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1006 | } |
| 1007 | |
Evgeniy Stepanov | f18e3af | 2012-12-14 12:54:18 +0000 | [diff] [blame] | 1008 | size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) { |
| 1009 | return Ty->isVectorTy() ? |
| 1010 | Ty->getVectorNumElements() * Ty->getScalarSizeInBits() : |
| 1011 | Ty->getPrimitiveSizeInBits(); |
| 1012 | } |
| 1013 | |
| 1014 | /// \brief Cast between two shadow types, extending or truncating as |
| 1015 | /// necessary. |
| 1016 | Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy) { |
| 1017 | Type *srcTy = V->getType(); |
| 1018 | if (dstTy->isIntegerTy() && srcTy->isIntegerTy()) |
| 1019 | return IRB.CreateIntCast(V, dstTy, false); |
| 1020 | if (dstTy->isVectorTy() && srcTy->isVectorTy() && |
| 1021 | dstTy->getVectorNumElements() == srcTy->getVectorNumElements()) |
| 1022 | return IRB.CreateIntCast(V, dstTy, false); |
| 1023 | size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy); |
| 1024 | size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy); |
| 1025 | Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits)); |
| 1026 | Value *V2 = |
| 1027 | IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), false); |
| 1028 | return IRB.CreateBitCast(V2, dstTy); |
| 1029 | // TODO: handle struct types. |
| 1030 | } |
| 1031 | |
| 1032 | /// \brief Propagate shadow for arbitrary operation. |
| 1033 | void handleShadowOr(Instruction &I) { |
| 1034 | IRBuilder<> IRB(&I); |
| 1035 | ShadowAndOriginCombiner SC(this, IRB); |
| 1036 | for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI) |
| 1037 | SC.Add(OI->get()); |
| 1038 | SC.Done(&I); |
| 1039 | } |
| 1040 | |
| 1041 | void visitFAdd(BinaryOperator &I) { handleShadowOr(I); } |
| 1042 | void visitFSub(BinaryOperator &I) { handleShadowOr(I); } |
| 1043 | void visitFMul(BinaryOperator &I) { handleShadowOr(I); } |
| 1044 | void visitAdd(BinaryOperator &I) { handleShadowOr(I); } |
| 1045 | void visitSub(BinaryOperator &I) { handleShadowOr(I); } |
| 1046 | void visitXor(BinaryOperator &I) { handleShadowOr(I); } |
| 1047 | void visitMul(BinaryOperator &I) { handleShadowOr(I); } |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1048 | |
| 1049 | void handleDiv(Instruction &I) { |
| 1050 | IRBuilder<> IRB(&I); |
| 1051 | // Strict on the second argument. |
| 1052 | insertCheck(I.getOperand(1), &I); |
| 1053 | setShadow(&I, getShadow(&I, 0)); |
| 1054 | setOrigin(&I, getOrigin(&I, 0)); |
| 1055 | } |
| 1056 | |
| 1057 | void visitUDiv(BinaryOperator &I) { handleDiv(I); } |
| 1058 | void visitSDiv(BinaryOperator &I) { handleDiv(I); } |
| 1059 | void visitFDiv(BinaryOperator &I) { handleDiv(I); } |
| 1060 | void visitURem(BinaryOperator &I) { handleDiv(I); } |
| 1061 | void visitSRem(BinaryOperator &I) { handleDiv(I); } |
| 1062 | void visitFRem(BinaryOperator &I) { handleDiv(I); } |
| 1063 | |
| 1064 | /// \brief Instrument == and != comparisons. |
| 1065 | /// |
| 1066 | /// Sometimes the comparison result is known even if some of the bits of the |
| 1067 | /// arguments are not. |
| 1068 | void handleEqualityComparison(ICmpInst &I) { |
| 1069 | IRBuilder<> IRB(&I); |
| 1070 | Value *A = I.getOperand(0); |
| 1071 | Value *B = I.getOperand(1); |
| 1072 | Value *Sa = getShadow(A); |
| 1073 | Value *Sb = getShadow(B); |
| 1074 | if (A->getType()->isPointerTy()) |
| 1075 | A = IRB.CreatePointerCast(A, MS.IntptrTy); |
| 1076 | if (B->getType()->isPointerTy()) |
| 1077 | B = IRB.CreatePointerCast(B, MS.IntptrTy); |
| 1078 | // A == B <==> (C = A^B) == 0 |
| 1079 | // A != B <==> (C = A^B) != 0 |
| 1080 | // Sc = Sa | Sb |
| 1081 | Value *C = IRB.CreateXor(A, B); |
| 1082 | Value *Sc = IRB.CreateOr(Sa, Sb); |
| 1083 | // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now) |
| 1084 | // Result is defined if one of the following is true |
| 1085 | // * there is a defined 1 bit in C |
| 1086 | // * C is fully defined |
| 1087 | // Si = !(C & ~Sc) && Sc |
| 1088 | Value *Zero = Constant::getNullValue(Sc->getType()); |
| 1089 | Value *MinusOne = Constant::getAllOnesValue(Sc->getType()); |
| 1090 | Value *Si = |
| 1091 | IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero), |
| 1092 | IRB.CreateICmpEQ( |
| 1093 | IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero)); |
| 1094 | Si->setName("_msprop_icmp"); |
| 1095 | setShadow(&I, Si); |
| 1096 | setOriginForNaryOp(I); |
| 1097 | } |
| 1098 | |
Evgeniy Stepanov | 857d9d2 | 2012-11-29 14:25:47 +0000 | [diff] [blame] | 1099 | /// \brief Instrument signed relational comparisons. |
| 1100 | /// |
| 1101 | /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by |
| 1102 | /// propagating the highest bit of the shadow. Everything else is delegated |
| 1103 | /// to handleShadowOr(). |
| 1104 | void handleSignedRelationalComparison(ICmpInst &I) { |
| 1105 | Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0)); |
| 1106 | Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1)); |
| 1107 | Value* op = NULL; |
| 1108 | CmpInst::Predicate pre = I.getPredicate(); |
| 1109 | if (constOp0 && constOp0->isNullValue() && |
| 1110 | (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) { |
| 1111 | op = I.getOperand(1); |
| 1112 | } else if (constOp1 && constOp1->isNullValue() && |
| 1113 | (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) { |
| 1114 | op = I.getOperand(0); |
| 1115 | } |
| 1116 | if (op) { |
| 1117 | IRBuilder<> IRB(&I); |
| 1118 | Value* Shadow = |
| 1119 | IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt"); |
| 1120 | setShadow(&I, Shadow); |
| 1121 | setOrigin(&I, getOrigin(op)); |
| 1122 | } else { |
| 1123 | handleShadowOr(I); |
| 1124 | } |
| 1125 | } |
| 1126 | |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1127 | void visitICmpInst(ICmpInst &I) { |
| 1128 | if (ClHandleICmp && I.isEquality()) |
| 1129 | handleEqualityComparison(I); |
Evgeniy Stepanov | 857d9d2 | 2012-11-29 14:25:47 +0000 | [diff] [blame] | 1130 | else if (ClHandleICmp && I.isSigned() && I.isRelational()) |
| 1131 | handleSignedRelationalComparison(I); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1132 | else |
| 1133 | handleShadowOr(I); |
| 1134 | } |
| 1135 | |
| 1136 | void visitFCmpInst(FCmpInst &I) { |
| 1137 | handleShadowOr(I); |
| 1138 | } |
| 1139 | |
| 1140 | void handleShift(BinaryOperator &I) { |
| 1141 | IRBuilder<> IRB(&I); |
| 1142 | // If any of the S2 bits are poisoned, the whole thing is poisoned. |
| 1143 | // Otherwise perform the same shift on S1. |
| 1144 | Value *S1 = getShadow(&I, 0); |
| 1145 | Value *S2 = getShadow(&I, 1); |
| 1146 | Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)), |
| 1147 | S2->getType()); |
| 1148 | Value *V2 = I.getOperand(1); |
| 1149 | Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2); |
| 1150 | setShadow(&I, IRB.CreateOr(Shift, S2Conv)); |
| 1151 | setOriginForNaryOp(I); |
| 1152 | } |
| 1153 | |
| 1154 | void visitShl(BinaryOperator &I) { handleShift(I); } |
| 1155 | void visitAShr(BinaryOperator &I) { handleShift(I); } |
| 1156 | void visitLShr(BinaryOperator &I) { handleShift(I); } |
| 1157 | |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1158 | /// \brief Instrument llvm.memmove |
| 1159 | /// |
| 1160 | /// At this point we don't know if llvm.memmove will be inlined or not. |
| 1161 | /// If we don't instrument it and it gets inlined, |
| 1162 | /// our interceptor will not kick in and we will lose the memmove. |
| 1163 | /// If we instrument the call here, but it does not get inlined, |
| 1164 | /// we will memove the shadow twice: which is bad in case |
| 1165 | /// of overlapping regions. So, we simply lower the intrinsic to a call. |
| 1166 | /// |
Evgeniy Stepanov | 62b5db9 | 2012-11-29 12:49:04 +0000 | [diff] [blame] | 1167 | /// Similar situation exists for memcpy and memset. |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1168 | void visitMemMoveInst(MemMoveInst &I) { |
| 1169 | IRBuilder<> IRB(&I); |
| 1170 | IRB.CreateCall3( |
| 1171 | MS.MemmoveFn, |
| 1172 | IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()), |
| 1173 | IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()), |
| 1174 | IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)); |
| 1175 | I.eraseFromParent(); |
| 1176 | } |
| 1177 | |
Evgeniy Stepanov | 62b5db9 | 2012-11-29 12:49:04 +0000 | [diff] [blame] | 1178 | // Similar to memmove: avoid copying shadow twice. |
| 1179 | // This is somewhat unfortunate as it may slowdown small constant memcpys. |
| 1180 | // FIXME: consider doing manual inline for small constant sizes and proper |
| 1181 | // alignment. |
| 1182 | void visitMemCpyInst(MemCpyInst &I) { |
| 1183 | IRBuilder<> IRB(&I); |
| 1184 | IRB.CreateCall3( |
| 1185 | MS.MemcpyFn, |
| 1186 | IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()), |
| 1187 | IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()), |
| 1188 | IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)); |
| 1189 | I.eraseFromParent(); |
| 1190 | } |
| 1191 | |
| 1192 | // Same as memcpy. |
| 1193 | void visitMemSetInst(MemSetInst &I) { |
| 1194 | IRBuilder<> IRB(&I); |
| 1195 | IRB.CreateCall3( |
| 1196 | MS.MemsetFn, |
| 1197 | IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()), |
| 1198 | IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false), |
| 1199 | IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)); |
| 1200 | I.eraseFromParent(); |
| 1201 | } |
| 1202 | |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1203 | void visitVAStartInst(VAStartInst &I) { |
| 1204 | VAHelper->visitVAStartInst(I); |
| 1205 | } |
| 1206 | |
| 1207 | void visitVACopyInst(VACopyInst &I) { |
| 1208 | VAHelper->visitVACopyInst(I); |
| 1209 | } |
| 1210 | |
Evgeniy Stepanov | 8b51bab | 2012-12-05 14:39:55 +0000 | [diff] [blame] | 1211 | void handleBswap(IntrinsicInst &I) { |
| 1212 | IRBuilder<> IRB(&I); |
| 1213 | Value *Op = I.getArgOperand(0); |
| 1214 | Type *OpType = Op->getType(); |
| 1215 | Function *BswapFunc = Intrinsic::getDeclaration( |
| 1216 | F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1)); |
| 1217 | setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op))); |
| 1218 | setOrigin(&I, getOrigin(Op)); |
| 1219 | } |
| 1220 | |
| 1221 | void visitIntrinsicInst(IntrinsicInst &I) { |
| 1222 | switch (I.getIntrinsicID()) { |
| 1223 | case llvm::Intrinsic::bswap: |
| 1224 | handleBswap(I); break; |
| 1225 | default: |
| 1226 | visitInstruction(I); break; |
| 1227 | } |
| 1228 | } |
| 1229 | |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1230 | void visitCallSite(CallSite CS) { |
| 1231 | Instruction &I = *CS.getInstruction(); |
| 1232 | assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite"); |
| 1233 | if (CS.isCall()) { |
Evgeniy Stepanov | 7ad7e83 | 2012-11-29 14:32:03 +0000 | [diff] [blame] | 1234 | CallInst *Call = cast<CallInst>(&I); |
| 1235 | |
| 1236 | // For inline asm, do the usual thing: check argument shadow and mark all |
| 1237 | // outputs as clean. Note that any side effects of the inline asm that are |
| 1238 | // not immediately visible in its constraints are not handled. |
| 1239 | if (Call->isInlineAsm()) { |
| 1240 | visitInstruction(I); |
| 1241 | return; |
| 1242 | } |
| 1243 | |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1244 | // Allow only tail calls with the same types, otherwise |
| 1245 | // we may have a false positive: shadow for a non-void RetVal |
| 1246 | // will get propagated to a void RetVal. |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1247 | if (Call->isTailCall() && Call->getType() != Call->getParent()->getType()) |
| 1248 | Call->setTailCall(false); |
Evgeniy Stepanov | 8b51bab | 2012-12-05 14:39:55 +0000 | [diff] [blame] | 1249 | |
| 1250 | assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere"); |
Evgeniy Stepanov | 383b61e | 2012-12-07 09:08:32 +0000 | [diff] [blame] | 1251 | |
| 1252 | // We are going to insert code that relies on the fact that the callee |
| 1253 | // will become a non-readonly function after it is instrumented by us. To |
| 1254 | // prevent this code from being optimized out, mark that function |
| 1255 | // non-readonly in advance. |
| 1256 | if (Function *Func = Call->getCalledFunction()) { |
| 1257 | // Clear out readonly/readnone attributes. |
| 1258 | AttrBuilder B; |
| 1259 | B.addAttribute(Attributes::ReadOnly) |
| 1260 | .addAttribute(Attributes::ReadNone); |
Bill Wendling | e94d843 | 2012-12-07 23:16:57 +0000 | [diff] [blame] | 1261 | Func->removeAttribute(AttributeSet::FunctionIndex, |
Evgeniy Stepanov | 383b61e | 2012-12-07 09:08:32 +0000 | [diff] [blame] | 1262 | Attributes::get(Func->getContext(), B)); |
| 1263 | } |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1264 | } |
| 1265 | IRBuilder<> IRB(&I); |
| 1266 | unsigned ArgOffset = 0; |
| 1267 | DEBUG(dbgs() << " CallSite: " << I << "\n"); |
| 1268 | for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end(); |
| 1269 | ArgIt != End; ++ArgIt) { |
| 1270 | Value *A = *ArgIt; |
| 1271 | unsigned i = ArgIt - CS.arg_begin(); |
| 1272 | if (!A->getType()->isSized()) { |
| 1273 | DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n"); |
| 1274 | continue; |
| 1275 | } |
| 1276 | unsigned Size = 0; |
| 1277 | Value *Store = 0; |
| 1278 | // Compute the Shadow for arg even if it is ByVal, because |
| 1279 | // in that case getShadow() will copy the actual arg shadow to |
| 1280 | // __msan_param_tls. |
| 1281 | Value *ArgShadow = getShadow(A); |
| 1282 | Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset); |
| 1283 | DEBUG(dbgs() << " Arg#" << i << ": " << *A << |
| 1284 | " Shadow: " << *ArgShadow << "\n"); |
| 1285 | if (CS.paramHasAttr(i + 1, Attributes::ByVal)) { |
| 1286 | assert(A->getType()->isPointerTy() && |
| 1287 | "ByVal argument is not a pointer!"); |
| 1288 | Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType()); |
| 1289 | unsigned Alignment = CS.getParamAlignment(i + 1); |
| 1290 | Store = IRB.CreateMemCpy(ArgShadowBase, |
| 1291 | getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB), |
| 1292 | Size, Alignment); |
| 1293 | } else { |
| 1294 | Size = MS.TD->getTypeAllocSize(A->getType()); |
Evgeniy Stepanov | d2bd319 | 2012-12-11 12:34:09 +0000 | [diff] [blame] | 1295 | Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase, |
| 1296 | kShadowTLSAlignment); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1297 | } |
| 1298 | if (ClTrackOrigins) |
Evgeniy Stepanov | 49175b2 | 2012-12-14 13:43:11 +0000 | [diff] [blame^] | 1299 | IRB.CreateStore(getOrigin(A), |
| 1300 | getOriginPtrForArgument(A, IRB, ArgOffset)); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1301 | assert(Size != 0 && Store != 0); |
| 1302 | DEBUG(dbgs() << " Param:" << *Store << "\n"); |
| 1303 | ArgOffset += DataLayout::RoundUpAlignment(Size, 8); |
| 1304 | } |
| 1305 | DEBUG(dbgs() << " done with call args\n"); |
| 1306 | |
| 1307 | FunctionType *FT = |
| 1308 | cast<FunctionType>(CS.getCalledValue()->getType()-> getContainedType(0)); |
| 1309 | if (FT->isVarArg()) { |
| 1310 | VAHelper->visitCallSite(CS, IRB); |
| 1311 | } |
| 1312 | |
| 1313 | // Now, get the shadow for the RetVal. |
| 1314 | if (!I.getType()->isSized()) return; |
| 1315 | IRBuilder<> IRBBefore(&I); |
| 1316 | // Untill we have full dynamic coverage, make sure the retval shadow is 0. |
| 1317 | Value *Base = getShadowPtrForRetval(&I, IRBBefore); |
Evgeniy Stepanov | d2bd319 | 2012-12-11 12:34:09 +0000 | [diff] [blame] | 1318 | IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1319 | Instruction *NextInsn = 0; |
| 1320 | if (CS.isCall()) { |
| 1321 | NextInsn = I.getNextNode(); |
| 1322 | } else { |
| 1323 | BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest(); |
| 1324 | if (!NormalDest->getSinglePredecessor()) { |
| 1325 | // FIXME: this case is tricky, so we are just conservative here. |
| 1326 | // Perhaps we need to split the edge between this BB and NormalDest, |
| 1327 | // but a naive attempt to use SplitEdge leads to a crash. |
| 1328 | setShadow(&I, getCleanShadow(&I)); |
| 1329 | setOrigin(&I, getCleanOrigin()); |
| 1330 | return; |
| 1331 | } |
| 1332 | NextInsn = NormalDest->getFirstInsertionPt(); |
| 1333 | assert(NextInsn && |
| 1334 | "Could not find insertion point for retval shadow load"); |
| 1335 | } |
| 1336 | IRBuilder<> IRBAfter(NextInsn); |
Evgeniy Stepanov | d2bd319 | 2012-12-11 12:34:09 +0000 | [diff] [blame] | 1337 | Value *RetvalShadow = |
| 1338 | IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter), |
| 1339 | kShadowTLSAlignment, "_msret"); |
| 1340 | setShadow(&I, RetvalShadow); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1341 | if (ClTrackOrigins) |
| 1342 | setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter))); |
| 1343 | } |
| 1344 | |
| 1345 | void visitReturnInst(ReturnInst &I) { |
| 1346 | IRBuilder<> IRB(&I); |
| 1347 | if (Value *RetVal = I.getReturnValue()) { |
| 1348 | // Set the shadow for the RetVal. |
| 1349 | Value *Shadow = getShadow(RetVal); |
| 1350 | Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB); |
| 1351 | DEBUG(dbgs() << "Return: " << *Shadow << "\n" << *ShadowPtr << "\n"); |
Evgeniy Stepanov | d2bd319 | 2012-12-11 12:34:09 +0000 | [diff] [blame] | 1352 | IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1353 | if (ClTrackOrigins) |
| 1354 | IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB)); |
| 1355 | } |
| 1356 | } |
| 1357 | |
| 1358 | void visitPHINode(PHINode &I) { |
| 1359 | IRBuilder<> IRB(&I); |
| 1360 | ShadowPHINodes.push_back(&I); |
| 1361 | setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(), |
| 1362 | "_msphi_s")); |
| 1363 | if (ClTrackOrigins) |
| 1364 | setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(), |
| 1365 | "_msphi_o")); |
| 1366 | } |
| 1367 | |
| 1368 | void visitAllocaInst(AllocaInst &I) { |
| 1369 | setShadow(&I, getCleanShadow(&I)); |
| 1370 | if (!ClPoisonStack) return; |
| 1371 | IRBuilder<> IRB(I.getNextNode()); |
| 1372 | uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType()); |
| 1373 | if (ClPoisonStackWithCall) { |
| 1374 | IRB.CreateCall2(MS.MsanPoisonStackFn, |
| 1375 | IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), |
| 1376 | ConstantInt::get(MS.IntptrTy, Size)); |
| 1377 | } else { |
| 1378 | Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB); |
| 1379 | IRB.CreateMemSet(ShadowBase, IRB.getInt8(ClPoisonStackPattern), |
| 1380 | Size, I.getAlignment()); |
| 1381 | } |
| 1382 | |
| 1383 | if (ClTrackOrigins) { |
| 1384 | setOrigin(&I, getCleanOrigin()); |
| 1385 | SmallString<2048> StackDescriptionStorage; |
| 1386 | raw_svector_ostream StackDescription(StackDescriptionStorage); |
| 1387 | // We create a string with a description of the stack allocation and |
| 1388 | // pass it into __msan_set_alloca_origin. |
| 1389 | // It will be printed by the run-time if stack-originated UMR is found. |
| 1390 | // The first 4 bytes of the string are set to '----' and will be replaced |
| 1391 | // by __msan_va_arg_overflow_size_tls at the first call. |
| 1392 | StackDescription << "----" << I.getName() << "@" << F.getName(); |
| 1393 | Value *Descr = |
| 1394 | createPrivateNonConstGlobalForString(*F.getParent(), |
| 1395 | StackDescription.str()); |
| 1396 | IRB.CreateCall3(MS.MsanSetAllocaOriginFn, |
| 1397 | IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), |
| 1398 | ConstantInt::get(MS.IntptrTy, Size), |
| 1399 | IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy())); |
| 1400 | } |
| 1401 | } |
| 1402 | |
| 1403 | void visitSelectInst(SelectInst& I) { |
| 1404 | IRBuilder<> IRB(&I); |
| 1405 | setShadow(&I, IRB.CreateSelect(I.getCondition(), |
| 1406 | getShadow(I.getTrueValue()), getShadow(I.getFalseValue()), |
| 1407 | "_msprop")); |
| 1408 | if (ClTrackOrigins) |
| 1409 | setOrigin(&I, IRB.CreateSelect(I.getCondition(), |
| 1410 | getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue()))); |
| 1411 | } |
| 1412 | |
| 1413 | void visitLandingPadInst(LandingPadInst &I) { |
| 1414 | // Do nothing. |
| 1415 | // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1 |
| 1416 | setShadow(&I, getCleanShadow(&I)); |
| 1417 | setOrigin(&I, getCleanOrigin()); |
| 1418 | } |
| 1419 | |
| 1420 | void visitGetElementPtrInst(GetElementPtrInst &I) { |
| 1421 | handleShadowOr(I); |
| 1422 | } |
| 1423 | |
| 1424 | void visitExtractValueInst(ExtractValueInst &I) { |
| 1425 | IRBuilder<> IRB(&I); |
| 1426 | Value *Agg = I.getAggregateOperand(); |
| 1427 | DEBUG(dbgs() << "ExtractValue: " << I << "\n"); |
| 1428 | Value *AggShadow = getShadow(Agg); |
| 1429 | DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n"); |
| 1430 | Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices()); |
| 1431 | DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n"); |
| 1432 | setShadow(&I, ResShadow); |
| 1433 | setOrigin(&I, getCleanOrigin()); |
| 1434 | } |
| 1435 | |
| 1436 | void visitInsertValueInst(InsertValueInst &I) { |
| 1437 | IRBuilder<> IRB(&I); |
| 1438 | DEBUG(dbgs() << "InsertValue: " << I << "\n"); |
| 1439 | Value *AggShadow = getShadow(I.getAggregateOperand()); |
| 1440 | Value *InsShadow = getShadow(I.getInsertedValueOperand()); |
| 1441 | DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n"); |
| 1442 | DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n"); |
| 1443 | Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices()); |
| 1444 | DEBUG(dbgs() << " Res: " << *Res << "\n"); |
| 1445 | setShadow(&I, Res); |
| 1446 | setOrigin(&I, getCleanOrigin()); |
| 1447 | } |
| 1448 | |
| 1449 | void dumpInst(Instruction &I) { |
| 1450 | if (CallInst *CI = dyn_cast<CallInst>(&I)) { |
| 1451 | errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n"; |
| 1452 | } else { |
| 1453 | errs() << "ZZZ " << I.getOpcodeName() << "\n"; |
| 1454 | } |
| 1455 | errs() << "QQQ " << I << "\n"; |
| 1456 | } |
| 1457 | |
| 1458 | void visitResumeInst(ResumeInst &I) { |
| 1459 | DEBUG(dbgs() << "Resume: " << I << "\n"); |
| 1460 | // Nothing to do here. |
| 1461 | } |
| 1462 | |
| 1463 | void visitInstruction(Instruction &I) { |
| 1464 | // Everything else: stop propagating and check for poisoned shadow. |
| 1465 | if (ClDumpStrictInstructions) |
| 1466 | dumpInst(I); |
| 1467 | DEBUG(dbgs() << "DEFAULT: " << I << "\n"); |
| 1468 | for (size_t i = 0, n = I.getNumOperands(); i < n; i++) |
| 1469 | insertCheck(I.getOperand(i), &I); |
| 1470 | setShadow(&I, getCleanShadow(&I)); |
| 1471 | setOrigin(&I, getCleanOrigin()); |
| 1472 | } |
| 1473 | }; |
| 1474 | |
| 1475 | /// \brief AMD64-specific implementation of VarArgHelper. |
| 1476 | struct VarArgAMD64Helper : public VarArgHelper { |
| 1477 | // An unfortunate workaround for asymmetric lowering of va_arg stuff. |
| 1478 | // See a comment in visitCallSite for more details. |
| 1479 | static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7 |
| 1480 | static const unsigned AMD64FpEndOffset = 176; |
| 1481 | |
| 1482 | Function &F; |
| 1483 | MemorySanitizer &MS; |
| 1484 | MemorySanitizerVisitor &MSV; |
| 1485 | Value *VAArgTLSCopy; |
| 1486 | Value *VAArgOverflowSize; |
| 1487 | |
| 1488 | SmallVector<CallInst*, 16> VAStartInstrumentationList; |
| 1489 | |
| 1490 | VarArgAMD64Helper(Function &F, MemorySanitizer &MS, |
| 1491 | MemorySanitizerVisitor &MSV) |
| 1492 | : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { } |
| 1493 | |
| 1494 | enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory }; |
| 1495 | |
| 1496 | ArgKind classifyArgument(Value* arg) { |
| 1497 | // A very rough approximation of X86_64 argument classification rules. |
| 1498 | Type *T = arg->getType(); |
| 1499 | if (T->isFPOrFPVectorTy() || T->isX86_MMXTy()) |
| 1500 | return AK_FloatingPoint; |
| 1501 | if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64) |
| 1502 | return AK_GeneralPurpose; |
| 1503 | if (T->isPointerTy()) |
| 1504 | return AK_GeneralPurpose; |
| 1505 | return AK_Memory; |
| 1506 | } |
| 1507 | |
| 1508 | // For VarArg functions, store the argument shadow in an ABI-specific format |
| 1509 | // that corresponds to va_list layout. |
| 1510 | // We do this because Clang lowers va_arg in the frontend, and this pass |
| 1511 | // only sees the low level code that deals with va_list internals. |
| 1512 | // A much easier alternative (provided that Clang emits va_arg instructions) |
| 1513 | // would have been to associate each live instance of va_list with a copy of |
| 1514 | // MSanParamTLS, and extract shadow on va_arg() call in the argument list |
| 1515 | // order. |
| 1516 | void visitCallSite(CallSite &CS, IRBuilder<> &IRB) { |
| 1517 | unsigned GpOffset = 0; |
| 1518 | unsigned FpOffset = AMD64GpEndOffset; |
| 1519 | unsigned OverflowOffset = AMD64FpEndOffset; |
| 1520 | for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end(); |
| 1521 | ArgIt != End; ++ArgIt) { |
| 1522 | Value *A = *ArgIt; |
| 1523 | ArgKind AK = classifyArgument(A); |
| 1524 | if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset) |
| 1525 | AK = AK_Memory; |
| 1526 | if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset) |
| 1527 | AK = AK_Memory; |
| 1528 | Value *Base; |
| 1529 | switch (AK) { |
| 1530 | case AK_GeneralPurpose: |
| 1531 | Base = getShadowPtrForVAArgument(A, IRB, GpOffset); |
| 1532 | GpOffset += 8; |
| 1533 | break; |
| 1534 | case AK_FloatingPoint: |
| 1535 | Base = getShadowPtrForVAArgument(A, IRB, FpOffset); |
| 1536 | FpOffset += 16; |
| 1537 | break; |
| 1538 | case AK_Memory: |
| 1539 | uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType()); |
| 1540 | Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset); |
| 1541 | OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8); |
| 1542 | } |
Evgeniy Stepanov | d2bd319 | 2012-12-11 12:34:09 +0000 | [diff] [blame] | 1543 | IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment); |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1544 | } |
| 1545 | Constant *OverflowSize = |
| 1546 | ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset); |
| 1547 | IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS); |
| 1548 | } |
| 1549 | |
| 1550 | /// \brief Compute the shadow address for a given va_arg. |
| 1551 | Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB, |
| 1552 | int ArgOffset) { |
| 1553 | Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy); |
| 1554 | Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); |
| 1555 | return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0), |
| 1556 | "_msarg"); |
| 1557 | } |
| 1558 | |
| 1559 | void visitVAStartInst(VAStartInst &I) { |
| 1560 | IRBuilder<> IRB(&I); |
| 1561 | VAStartInstrumentationList.push_back(&I); |
| 1562 | Value *VAListTag = I.getArgOperand(0); |
| 1563 | Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB); |
| 1564 | |
| 1565 | // Unpoison the whole __va_list_tag. |
| 1566 | // FIXME: magic ABI constants. |
| 1567 | IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), |
| 1568 | /* size */24, /* alignment */16, false); |
| 1569 | } |
| 1570 | |
| 1571 | void visitVACopyInst(VACopyInst &I) { |
| 1572 | IRBuilder<> IRB(&I); |
| 1573 | Value *VAListTag = I.getArgOperand(0); |
| 1574 | Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB); |
| 1575 | |
| 1576 | // Unpoison the whole __va_list_tag. |
| 1577 | // FIXME: magic ABI constants. |
| 1578 | IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), |
| 1579 | /* size */ 24, /* alignment */ 16, false); |
| 1580 | } |
| 1581 | |
| 1582 | void finalizeInstrumentation() { |
| 1583 | assert(!VAArgOverflowSize && !VAArgTLSCopy && |
| 1584 | "finalizeInstrumentation called twice"); |
| 1585 | if (!VAStartInstrumentationList.empty()) { |
| 1586 | // If there is a va_start in this function, make a backup copy of |
| 1587 | // va_arg_tls somewhere in the function entry block. |
| 1588 | IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI()); |
| 1589 | VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS); |
| 1590 | Value *CopySize = |
| 1591 | IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset), |
| 1592 | VAArgOverflowSize); |
| 1593 | VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize); |
| 1594 | IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8); |
| 1595 | } |
| 1596 | |
| 1597 | // Instrument va_start. |
| 1598 | // Copy va_list shadow from the backup copy of the TLS contents. |
| 1599 | for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) { |
| 1600 | CallInst *OrigInst = VAStartInstrumentationList[i]; |
| 1601 | IRBuilder<> IRB(OrigInst->getNextNode()); |
| 1602 | Value *VAListTag = OrigInst->getArgOperand(0); |
| 1603 | |
| 1604 | Value *RegSaveAreaPtrPtr = |
| 1605 | IRB.CreateIntToPtr( |
| 1606 | IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), |
| 1607 | ConstantInt::get(MS.IntptrTy, 16)), |
| 1608 | Type::getInt64PtrTy(*MS.C)); |
| 1609 | Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr); |
| 1610 | Value *RegSaveAreaShadowPtr = |
| 1611 | MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB); |
| 1612 | IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy, |
| 1613 | AMD64FpEndOffset, 16); |
| 1614 | |
| 1615 | Value *OverflowArgAreaPtrPtr = |
| 1616 | IRB.CreateIntToPtr( |
| 1617 | IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), |
| 1618 | ConstantInt::get(MS.IntptrTy, 8)), |
| 1619 | Type::getInt64PtrTy(*MS.C)); |
| 1620 | Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr); |
| 1621 | Value *OverflowArgAreaShadowPtr = |
| 1622 | MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB); |
| 1623 | Value *SrcPtr = |
| 1624 | getShadowPtrForVAArgument(VAArgTLSCopy, IRB, AMD64FpEndOffset); |
| 1625 | IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16); |
| 1626 | } |
| 1627 | } |
| 1628 | }; |
| 1629 | |
| 1630 | VarArgHelper* CreateVarArgHelper(Function &Func, MemorySanitizer &Msan, |
| 1631 | MemorySanitizerVisitor &Visitor) { |
| 1632 | return new VarArgAMD64Helper(Func, Msan, Visitor); |
| 1633 | } |
| 1634 | |
| 1635 | } // namespace |
| 1636 | |
| 1637 | bool MemorySanitizer::runOnFunction(Function &F) { |
| 1638 | MemorySanitizerVisitor Visitor(F, *this); |
| 1639 | |
| 1640 | // Clear out readonly/readnone attributes. |
| 1641 | AttrBuilder B; |
| 1642 | B.addAttribute(Attributes::ReadOnly) |
| 1643 | .addAttribute(Attributes::ReadNone); |
Bill Wendling | e94d843 | 2012-12-07 23:16:57 +0000 | [diff] [blame] | 1644 | F.removeAttribute(AttributeSet::FunctionIndex, |
Evgeniy Stepanov | d4bd7b7 | 2012-11-29 09:57:20 +0000 | [diff] [blame] | 1645 | Attributes::get(F.getContext(), B)); |
| 1646 | |
| 1647 | return Visitor.runOnFunction(); |
| 1648 | } |