1 //===-- MemorySanitizer.cpp - detector of uninitialized reads -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file is a part of MemorySanitizer, a detector of uninitialized
13 /// Status: early prototype.
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.
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).
39 /// The default value of shadow is 0, which means "clean" (not poisoned).
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 //===----------------------------------------------------------------------===//
48 #define DEBUG_TYPE "msan"
50 #include "BlackList.h"
51 #include "llvm/DataLayout.h"
52 #include "llvm/Function.h"
53 #include "llvm/InlineAsm.h"
54 #include "llvm/IntrinsicInst.h"
55 #include "llvm/IRBuilder.h"
56 #include "llvm/LLVMContext.h"
57 #include "llvm/MDBuilder.h"
58 #include "llvm/Module.h"
59 #include "llvm/Type.h"
60 #include "llvm/ADT/DepthFirstIterator.h"
61 #include "llvm/ADT/SmallString.h"
62 #include "llvm/ADT/SmallVector.h"
63 #include "llvm/ADT/ValueMap.h"
64 #include "llvm/Transforms/Instrumentation.h"
65 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
66 #include "llvm/Transforms/Utils/ModuleUtils.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/Debug.h"
70 #include "llvm/Support/InstVisitor.h"
71 #include "llvm/Support/raw_ostream.h"
72 #include "llvm/Transforms/Instrumentation.h"
73 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
74 #include "llvm/Transforms/Utils/ModuleUtils.h"
78 static const uint64_t kShadowMask32 = 1ULL << 31;
79 static const uint64_t kShadowMask64 = 1ULL << 46;
80 static const uint64_t kOriginOffset32 = 1ULL << 30;
81 static const uint64_t kOriginOffset64 = 1ULL << 45;
83 // This is an important flag that makes the reports much more
84 // informative at the cost of greater slowdown. Not fully implemented
86 // FIXME: this should be a top-level clang flag, e.g.
87 // -fmemory-sanitizer-full.
88 static cl::opt<bool> ClTrackOrigins("msan-track-origins",
89 cl::desc("Track origins (allocation sites) of poisoned memory"),
90 cl::Hidden, cl::init(false));
91 static cl::opt<bool> ClKeepGoing("msan-keep-going",
92 cl::desc("keep going after reporting a UMR"),
93 cl::Hidden, cl::init(false));
94 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
95 cl::desc("poison uninitialized stack variables"),
96 cl::Hidden, cl::init(true));
97 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
98 cl::desc("poison uninitialized stack variables with a call"),
99 cl::Hidden, cl::init(false));
100 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
101 cl::desc("poison uninitialized stack variables with the given patter"),
102 cl::Hidden, cl::init(0xff));
104 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
105 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
106 cl::Hidden, cl::init(true));
108 // This flag controls whether we check the shadow of the address
109 // operand of load or store. Such bugs are very rare, since load from
110 // a garbage address typically results in SEGV, but still happen
111 // (e.g. only lower bits of address are garbage, or the access happens
112 // early at program startup where malloc-ed memory is more likely to
113 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
114 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
115 cl::desc("report accesses through a pointer which has poisoned shadow"),
116 cl::Hidden, cl::init(true));
118 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
119 cl::desc("print out instructions with default strict semantics"),
120 cl::Hidden, cl::init(false));
122 static cl::opt<std::string> ClBlackListFile("msan-blacklist",
123 cl::desc("File containing the list of functions where MemorySanitizer "
124 "should not report bugs"), cl::Hidden);
128 /// \brief An instrumentation pass implementing detection of uninitialized
131 /// MemorySanitizer: instrument the code in module to find
132 /// uninitialized reads.
133 class MemorySanitizer : public FunctionPass {
135 MemorySanitizer() : FunctionPass(ID), TD(0) { }
136 const char *getPassName() const { return "MemorySanitizer"; }
137 bool runOnFunction(Function &F);
138 bool doInitialization(Module &M);
139 static char ID; // Pass identification, replacement for typeid.
146 /// \brief Thread-local shadow storage for function parameters.
147 GlobalVariable *ParamTLS;
148 /// \brief Thread-local origin storage for function parameters.
149 GlobalVariable *ParamOriginTLS;
150 /// \brief Thread-local shadow storage for function return value.
151 GlobalVariable *RetvalTLS;
152 /// \brief Thread-local origin storage for function return value.
153 GlobalVariable *RetvalOriginTLS;
154 /// \brief Thread-local shadow storage for in-register va_arg function
155 /// parameters (x86_64-specific).
156 GlobalVariable *VAArgTLS;
157 /// \brief Thread-local shadow storage for va_arg overflow area
158 /// (x86_64-specific).
159 GlobalVariable *VAArgOverflowSizeTLS;
160 /// \brief Thread-local space used to pass origin value to the UMR reporting
162 GlobalVariable *OriginTLS;
164 /// \brief The run-time callback to print a warning.
166 /// \brief Run-time helper that copies origin info for a memory range.
167 Value *MsanCopyOriginFn;
168 /// \brief Run-time helper that generates a new origin value for a stack
170 Value *MsanSetAllocaOriginFn;
171 /// \brief Run-time helper that poisons stack on function entry.
172 Value *MsanPoisonStackFn;
173 /// \brief MSan runtime replacements for memmove, memcpy and memset.
174 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
176 /// \brief Address mask used in application-to-shadow address calculation.
177 /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
179 /// \brief Offset of the origin shadow from the "normal" shadow.
180 /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
181 uint64_t OriginOffset;
182 /// \brief Branch weights for error reporting.
183 MDNode *ColdCallWeights;
184 /// \brief The blacklist.
185 OwningPtr<BlackList> BL;
186 /// \brief An empty volatile inline asm that prevents callback merge.
189 friend struct MemorySanitizerVisitor;
190 friend struct VarArgAMD64Helper;
194 char MemorySanitizer::ID = 0;
195 INITIALIZE_PASS(MemorySanitizer, "msan",
196 "MemorySanitizer: detects uninitialized reads.",
199 FunctionPass *llvm::createMemorySanitizerPass() {
200 return new MemorySanitizer();
203 /// \brief Create a non-const global initialized with the given string.
205 /// Creates a writable global for Str so that we can pass it to the
206 /// run-time lib. Runtime uses first 4 bytes of the string to store the
207 /// frame ID, so the string needs to be mutable.
208 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
210 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
211 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
212 GlobalValue::PrivateLinkage, StrConst, "");
215 /// \brief Module-level initialization.
217 /// Obtains pointers to the required runtime library functions, and
218 /// inserts a call to __msan_init to the module's constructor list.
219 bool MemorySanitizer::doInitialization(Module &M) {
220 TD = getAnalysisIfAvailable<DataLayout>();
223 BL.reset(new BlackList(ClBlackListFile));
224 C = &(M.getContext());
225 unsigned PtrSize = TD->getPointerSizeInBits(/* AddressSpace */0);
228 ShadowMask = kShadowMask64;
229 OriginOffset = kOriginOffset64;
232 ShadowMask = kShadowMask32;
233 OriginOffset = kOriginOffset32;
236 report_fatal_error("unsupported pointer size");
241 IntptrTy = IRB.getIntPtrTy(TD);
242 OriginTy = IRB.getInt32Ty();
244 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
246 // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
247 appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
248 "__msan_init", IRB.getVoidTy(), NULL)), 0);
250 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::LinkOnceODRLinkage,
251 IRB.getInt32(ClTrackOrigins), "__msan_track_origins");
253 // Create the callback.
254 // FIXME: this function should have "Cold" calling conv,
255 // which is not yet implemented.
256 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
257 : "__msan_warning_noreturn";
258 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL);
260 MsanCopyOriginFn = M.getOrInsertFunction(
261 "__msan_copy_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(),
262 IRB.getInt8PtrTy(), IntptrTy, NULL);
263 MsanSetAllocaOriginFn = M.getOrInsertFunction(
264 "__msan_set_alloca_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
265 IRB.getInt8PtrTy(), NULL);
266 MsanPoisonStackFn = M.getOrInsertFunction(
267 "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL);
268 MemmoveFn = M.getOrInsertFunction(
269 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
271 MemcpyFn = M.getOrInsertFunction(
272 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
274 MemsetFn = M.getOrInsertFunction(
275 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
279 RetvalTLS = new GlobalVariable(
280 M, ArrayType::get(IRB.getInt64Ty(), 8), false,
281 GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0,
282 GlobalVariable::GeneralDynamicTLSModel);
283 RetvalOriginTLS = new GlobalVariable(
284 M, OriginTy, false, GlobalVariable::ExternalLinkage, 0,
285 "__msan_retval_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
287 ParamTLS = new GlobalVariable(
288 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
289 GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0,
290 GlobalVariable::GeneralDynamicTLSModel);
291 ParamOriginTLS = new GlobalVariable(
292 M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage,
293 0, "__msan_param_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
295 VAArgTLS = new GlobalVariable(
296 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
297 GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0,
298 GlobalVariable::GeneralDynamicTLSModel);
299 VAArgOverflowSizeTLS = new GlobalVariable(
300 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0,
301 "__msan_va_arg_overflow_size_tls", 0,
302 GlobalVariable::GeneralDynamicTLSModel);
303 OriginTLS = new GlobalVariable(
304 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0,
305 "__msan_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
307 // We insert an empty inline asm after __msan_report* to avoid callback merge.
308 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
309 StringRef(""), StringRef(""),
310 /*hasSideEffects=*/true);
316 /// \brief A helper class that handles instrumentation of VarArg
317 /// functions on a particular platform.
319 /// Implementations are expected to insert the instrumentation
320 /// necessary to propagate argument shadow through VarArg function
321 /// calls. Visit* methods are called during an InstVisitor pass over
322 /// the function, and should avoid creating new basic blocks. A new
323 /// instance of this class is created for each instrumented function.
324 struct VarArgHelper {
325 /// \brief Visit a CallSite.
326 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
328 /// \brief Visit a va_start call.
329 virtual void visitVAStartInst(VAStartInst &I) = 0;
331 /// \brief Visit a va_copy call.
332 virtual void visitVACopyInst(VACopyInst &I) = 0;
334 /// \brief Finalize function instrumentation.
336 /// This method is called after visiting all interesting (see above)
337 /// instructions in a function.
338 virtual void finalizeInstrumentation() = 0;
340 virtual ~VarArgHelper() {}
343 struct MemorySanitizerVisitor;
346 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
347 MemorySanitizerVisitor &Visitor);
349 /// This class does all the work for a given function. Store and Load
350 /// instructions store and load corresponding shadow and origin
351 /// values. Most instructions propagate shadow from arguments to their
352 /// return values. Certain instructions (most importantly, BranchInst)
353 /// test their argument shadow and print reports (with a runtime call) if it's
355 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
358 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
359 ValueMap<Value*, Value*> ShadowMap, OriginMap;
361 OwningPtr<VarArgHelper> VAHelper;
363 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
364 // See a comment in visitCallSite for more details.
365 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
366 static const unsigned AMD64FpEndOffset = 176;
368 struct ShadowOriginAndInsertPoint {
371 Instruction *OrigIns;
372 ShadowOriginAndInsertPoint(Instruction *S, Instruction *O, Instruction *I)
373 : Shadow(S), Origin(O), OrigIns(I) { }
374 ShadowOriginAndInsertPoint() : Shadow(0), Origin(0), OrigIns(0) { }
376 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
378 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
379 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
380 InsertChecks = !MS.BL->isIn(F);
381 DEBUG(if (!InsertChecks)
382 dbgs() << "MemorySanitizer is not inserting checks into '"
383 << F.getName() << "'\n");
386 void materializeChecks() {
387 for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) {
388 Instruction *Shadow = InstrumentationList[i].Shadow;
389 Instruction *OrigIns = InstrumentationList[i].OrigIns;
390 IRBuilder<> IRB(OrigIns);
391 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
392 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
393 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
394 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
395 getCleanShadow(ConvertedShadow), "_mscmp");
396 Instruction *CheckTerm =
397 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp),
398 /* Unreachable */ !ClKeepGoing,
401 IRB.SetInsertPoint(CheckTerm);
402 if (ClTrackOrigins) {
403 Instruction *Origin = InstrumentationList[i].Origin;
404 IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0),
407 CallInst *Call = IRB.CreateCall(MS.WarningFn);
408 Call->setDebugLoc(OrigIns->getDebugLoc());
409 IRB.CreateCall(MS.EmptyAsm);
410 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
412 DEBUG(dbgs() << "DONE:\n" << F);
415 /// \brief Add MemorySanitizer instrumentation to a function.
416 bool runOnFunction() {
417 if (!MS.TD) return false;
418 // Iterate all BBs in depth-first order and create shadow instructions
419 // for all instructions (where applicable).
420 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
421 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
422 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
423 BasicBlock *BB = *DI;
427 // Finalize PHI nodes.
428 for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) {
429 PHINode *PN = ShadowPHINodes[i];
430 PHINode *PNS = cast<PHINode>(getShadow(PN));
431 PHINode *PNO = ClTrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0;
432 size_t NumValues = PN->getNumIncomingValues();
433 for (size_t v = 0; v < NumValues; v++) {
434 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
436 PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
440 VAHelper->finalizeInstrumentation();
447 /// \brief Compute the shadow type that corresponds to a given Value.
448 Type *getShadowTy(Value *V) {
449 return getShadowTy(V->getType());
452 /// \brief Compute the shadow type that corresponds to a given Type.
453 Type *getShadowTy(Type *OrigTy) {
454 if (!OrigTy->isSized()) {
457 // For integer type, shadow is the same as the original type.
458 // This may return weird-sized types like i1.
459 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
461 if (VectorType *VT = dyn_cast<VectorType>(OrigTy))
462 return VectorType::getInteger(VT);
463 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
464 SmallVector<Type*, 4> Elements;
465 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
466 Elements.push_back(getShadowTy(ST->getElementType(i)));
467 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
468 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
471 uint32_t TypeSize = MS.TD->getTypeStoreSizeInBits(OrigTy);
472 return IntegerType::get(*MS.C, TypeSize);
475 /// \brief Flatten a vector type.
476 Type *getShadowTyNoVec(Type *ty) {
477 if (VectorType *vt = dyn_cast<VectorType>(ty))
478 return IntegerType::get(*MS.C, vt->getBitWidth());
482 /// \brief Convert a shadow value to it's flattened variant.
483 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
484 Type *Ty = V->getType();
485 Type *NoVecTy = getShadowTyNoVec(Ty);
486 if (Ty == NoVecTy) return V;
487 return IRB.CreateBitCast(V, NoVecTy);
490 /// \brief Compute the shadow address that corresponds to a given application
493 /// Shadow = Addr & ~ShadowMask.
494 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
497 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
498 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
499 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
502 /// \brief Compute the origin address that corresponds to a given application
505 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
506 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
508 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
509 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
511 IRB.CreateAdd(ShadowLong,
512 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
514 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
515 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
518 /// \brief Compute the shadow address for a given function argument.
520 /// Shadow = ParamTLS+ArgOffset.
521 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
523 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
524 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
525 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
529 /// \brief Compute the origin address for a given function argument.
530 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
532 if (!ClTrackOrigins) return 0;
533 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
534 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
535 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
539 /// \brief Compute the shadow address for a retval.
540 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
541 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
542 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
546 /// \brief Compute the origin address for a retval.
547 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
548 // We keep a single origin for the entire retval. Might be too optimistic.
549 return MS.RetvalOriginTLS;
552 /// \brief Set SV to be the shadow value for V.
553 void setShadow(Value *V, Value *SV) {
554 assert(!ShadowMap.count(V) && "Values may only have one shadow");
558 /// \brief Set Origin to be the origin value for V.
559 void setOrigin(Value *V, Value *Origin) {
560 if (!ClTrackOrigins) return;
561 assert(!OriginMap.count(V) && "Values may only have one origin");
562 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
563 OriginMap[V] = Origin;
566 /// \brief Create a clean shadow value for a given value.
568 /// Clean shadow (all zeroes) means all bits of the value are defined
570 Value *getCleanShadow(Value *V) {
571 Type *ShadowTy = getShadowTy(V);
574 return Constant::getNullValue(ShadowTy);
577 /// \brief Create a dirty shadow of a given shadow type.
578 Constant *getPoisonedShadow(Type *ShadowTy) {
580 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
581 return Constant::getAllOnesValue(ShadowTy);
582 StructType *ST = cast<StructType>(ShadowTy);
583 SmallVector<Constant *, 4> Vals;
584 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
585 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
586 return ConstantStruct::get(ST, Vals);
589 /// \brief Create a clean (zero) origin.
590 Value *getCleanOrigin() {
591 return Constant::getNullValue(MS.OriginTy);
594 /// \brief Get the shadow value for a given Value.
596 /// This function either returns the value set earlier with setShadow,
597 /// or extracts if from ParamTLS (for function arguments).
598 Value *getShadow(Value *V) {
599 if (Instruction *I = dyn_cast<Instruction>(V)) {
600 // For instructions the shadow is already stored in the map.
601 Value *Shadow = ShadowMap[V];
603 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
604 assert(Shadow && "No shadow for a value");
608 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
609 Value *AllOnes = getPoisonedShadow(getShadowTy(V));
610 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
613 if (Argument *A = dyn_cast<Argument>(V)) {
614 // For arguments we compute the shadow on demand and store it in the map.
615 Value **ShadowPtr = &ShadowMap[V];
618 Function *F = A->getParent();
619 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
620 unsigned ArgOffset = 0;
621 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
623 if (!AI->getType()->isSized()) {
624 DEBUG(dbgs() << "Arg is not sized\n");
627 unsigned Size = AI->hasByValAttr()
628 ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
629 : MS.TD->getTypeAllocSize(AI->getType());
631 Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
632 if (AI->hasByValAttr()) {
633 // ByVal pointer itself has clean shadow. We copy the actual
634 // argument shadow to the underlying memory.
635 Value *Cpy = EntryIRB.CreateMemCpy(
636 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
637 Base, Size, AI->getParamAlignment());
638 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
639 *ShadowPtr = getCleanShadow(V);
641 *ShadowPtr = EntryIRB.CreateLoad(Base);
643 DEBUG(dbgs() << " ARG: " << *AI << " ==> " <<
644 **ShadowPtr << "\n");
645 if (ClTrackOrigins) {
646 Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
647 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
650 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
652 assert(*ShadowPtr && "Could not find shadow for an argument");
655 // For everything else the shadow is zero.
656 return getCleanShadow(V);
659 /// \brief Get the shadow for i-th argument of the instruction I.
660 Value *getShadow(Instruction *I, int i) {
661 return getShadow(I->getOperand(i));
664 /// \brief Get the origin for a value.
665 Value *getOrigin(Value *V) {
666 if (!ClTrackOrigins) return 0;
667 if (isa<Instruction>(V) || isa<Argument>(V)) {
668 Value *Origin = OriginMap[V];
670 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
671 Origin = getCleanOrigin();
675 return getCleanOrigin();
678 /// \brief Get the origin for i-th argument of the instruction I.
679 Value *getOrigin(Instruction *I, int i) {
680 return getOrigin(I->getOperand(i));
683 /// \brief Remember the place where a shadow check should be inserted.
685 /// This location will be later instrumented with a check that will print a
686 /// UMR warning in runtime if the value is not fully defined.
687 void insertCheck(Value *Val, Instruction *OrigIns) {
689 if (!InsertChecks) return;
690 Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
692 Type *ShadowTy = Shadow->getType();
693 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
694 "Can only insert checks for integer and vector shadow types");
695 Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
696 InstrumentationList.push_back(
697 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
700 //------------------- Visitors.
702 /// \brief Instrument LoadInst
704 /// Loads the corresponding shadow and (optionally) origin.
705 /// Optionally, checks that the load address is fully defined.
706 void visitLoadInst(LoadInst &I) {
707 Type *LoadTy = I.getType();
708 assert(LoadTy->isSized() && "Load type must have size");
710 Type *ShadowTy = getShadowTy(&I);
711 Value *Addr = I.getPointerOperand();
712 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
713 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
715 if (ClCheckAccessAddress)
716 insertCheck(I.getPointerOperand(), &I);
719 setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), I.getAlignment()));
722 /// \brief Instrument StoreInst
724 /// Stores the corresponding shadow and (optionally) origin.
725 /// Optionally, checks that the store address is fully defined.
726 /// Volatile stores check that the value being stored is fully defined.
727 void visitStoreInst(StoreInst &I) {
729 Value *Val = I.getValueOperand();
730 Value *Addr = I.getPointerOperand();
731 Value *Shadow = getShadow(Val);
732 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
734 StoreInst *NewSI = IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment());
735 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
736 // If the store is volatile, add a check.
738 insertCheck(Val, &I);
739 if (ClCheckAccessAddress)
740 insertCheck(Addr, &I);
743 IRB.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRB), I.getAlignment());
747 void visitSExtInst(SExtInst &I) {
749 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
750 setOrigin(&I, getOrigin(&I, 0));
753 void visitZExtInst(ZExtInst &I) {
755 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
756 setOrigin(&I, getOrigin(&I, 0));
759 void visitTruncInst(TruncInst &I) {
761 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
762 setOrigin(&I, getOrigin(&I, 0));
765 void visitBitCastInst(BitCastInst &I) {
767 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
768 setOrigin(&I, getOrigin(&I, 0));
771 void visitPtrToIntInst(PtrToIntInst &I) {
773 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
774 "_msprop_ptrtoint"));
775 setOrigin(&I, getOrigin(&I, 0));
778 void visitIntToPtrInst(IntToPtrInst &I) {
780 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
781 "_msprop_inttoptr"));
782 setOrigin(&I, getOrigin(&I, 0));
785 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
786 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
787 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
788 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
789 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
790 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
792 /// \brief Propagate shadow for bitwise AND.
794 /// This code is exact, i.e. if, for example, a bit in the left argument
795 /// is defined and 0, then neither the value not definedness of the
796 /// corresponding bit in B don't affect the resulting shadow.
797 void visitAnd(BinaryOperator &I) {
799 // "And" of 0 and a poisoned value results in unpoisoned value.
800 // 1&1 => 1; 0&1 => 0; p&1 => p;
801 // 1&0 => 0; 0&0 => 0; p&0 => 0;
802 // 1&p => p; 0&p => 0; p&p => p;
803 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
804 Value *S1 = getShadow(&I, 0);
805 Value *S2 = getShadow(&I, 1);
806 Value *V1 = I.getOperand(0);
807 Value *V2 = I.getOperand(1);
808 if (V1->getType() != S1->getType()) {
809 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
810 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
812 Value *S1S2 = IRB.CreateAnd(S1, S2);
813 Value *V1S2 = IRB.CreateAnd(V1, S2);
814 Value *S1V2 = IRB.CreateAnd(S1, V2);
815 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
816 setOriginForNaryOp(I);
819 void visitOr(BinaryOperator &I) {
821 // "Or" of 1 and a poisoned value results in unpoisoned value.
822 // 1|1 => 1; 0|1 => 1; p|1 => 1;
823 // 1|0 => 1; 0|0 => 0; p|0 => p;
824 // 1|p => 1; 0|p => p; p|p => p;
825 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
826 Value *S1 = getShadow(&I, 0);
827 Value *S2 = getShadow(&I, 1);
828 Value *V1 = IRB.CreateNot(I.getOperand(0));
829 Value *V2 = IRB.CreateNot(I.getOperand(1));
830 if (V1->getType() != S1->getType()) {
831 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
832 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
834 Value *S1S2 = IRB.CreateAnd(S1, S2);
835 Value *V1S2 = IRB.CreateAnd(V1, S2);
836 Value *S1V2 = IRB.CreateAnd(S1, V2);
837 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
838 setOriginForNaryOp(I);
841 /// \brief Propagate origin for an instruction.
843 /// This is a general case of origin propagation. For an Nary operation,
844 /// is set to the origin of an argument that is not entirely initialized.
845 /// It does not matter which one is picked if all arguments are initialized.
846 void setOriginForNaryOp(Instruction &I) {
847 if (!ClTrackOrigins) return;
849 Value *Origin = getOrigin(&I, 0);
850 for (unsigned Op = 1, n = I.getNumOperands(); Op < n; ++Op) {
851 Value *S = convertToShadowTyNoVec(getShadow(&I, Op - 1), IRB);
852 Origin = IRB.CreateSelect(IRB.CreateICmpNE(S, getCleanShadow(S)),
853 Origin, getOrigin(&I, Op));
855 setOrigin(&I, Origin);
858 /// \brief Propagate shadow for a binary operation.
860 /// Shadow = Shadow0 | Shadow1, all 3 must have the same type.
861 /// Bitwise OR is selected as an operation that will never lose even a bit of
863 void handleShadowOrBinary(Instruction &I) {
865 Value *Shadow0 = getShadow(&I, 0);
866 Value *Shadow1 = getShadow(&I, 1);
867 setShadow(&I, IRB.CreateOr(Shadow0, Shadow1, "_msprop"));
868 setOriginForNaryOp(I);
871 /// \brief Propagate shadow for arbitrary operation.
873 /// This is a general case of shadow propagation, used in all cases where we
874 /// don't know and/or care about what the operation actually does.
875 /// It converts all input shadow values to a common type (extending or
876 /// truncating as necessary), and bitwise OR's them.
878 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
879 /// fully initialized), and less prone to false positives.
880 // FIXME: is the casting actually correct?
881 // FIXME: merge this with handleShadowOrBinary.
882 void handleShadowOr(Instruction &I) {
884 Value *Shadow = getShadow(&I, 0);
885 for (unsigned Op = 1, n = I.getNumOperands(); Op < n; ++Op)
886 Shadow = IRB.CreateOr(
887 Shadow, IRB.CreateIntCast(getShadow(&I, Op), Shadow->getType(), false),
889 Shadow = IRB.CreateIntCast(Shadow, getShadowTy(&I), false);
890 setShadow(&I, Shadow);
891 setOriginForNaryOp(I);
894 void visitFAdd(BinaryOperator &I) { handleShadowOrBinary(I); }
895 void visitFSub(BinaryOperator &I) { handleShadowOrBinary(I); }
896 void visitFMul(BinaryOperator &I) { handleShadowOrBinary(I); }
897 void visitAdd(BinaryOperator &I) { handleShadowOrBinary(I); }
898 void visitSub(BinaryOperator &I) { handleShadowOrBinary(I); }
899 void visitXor(BinaryOperator &I) { handleShadowOrBinary(I); }
900 void visitMul(BinaryOperator &I) { handleShadowOrBinary(I); }
902 void handleDiv(Instruction &I) {
904 // Strict on the second argument.
905 insertCheck(I.getOperand(1), &I);
906 setShadow(&I, getShadow(&I, 0));
907 setOrigin(&I, getOrigin(&I, 0));
910 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
911 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
912 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
913 void visitURem(BinaryOperator &I) { handleDiv(I); }
914 void visitSRem(BinaryOperator &I) { handleDiv(I); }
915 void visitFRem(BinaryOperator &I) { handleDiv(I); }
917 /// \brief Instrument == and != comparisons.
919 /// Sometimes the comparison result is known even if some of the bits of the
920 /// arguments are not.
921 void handleEqualityComparison(ICmpInst &I) {
923 Value *A = I.getOperand(0);
924 Value *B = I.getOperand(1);
925 Value *Sa = getShadow(A);
926 Value *Sb = getShadow(B);
927 if (A->getType()->isPointerTy())
928 A = IRB.CreatePointerCast(A, MS.IntptrTy);
929 if (B->getType()->isPointerTy())
930 B = IRB.CreatePointerCast(B, MS.IntptrTy);
931 // A == B <==> (C = A^B) == 0
932 // A != B <==> (C = A^B) != 0
934 Value *C = IRB.CreateXor(A, B);
935 Value *Sc = IRB.CreateOr(Sa, Sb);
936 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
937 // Result is defined if one of the following is true
938 // * there is a defined 1 bit in C
939 // * C is fully defined
940 // Si = !(C & ~Sc) && Sc
941 Value *Zero = Constant::getNullValue(Sc->getType());
942 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
944 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
946 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
947 Si->setName("_msprop_icmp");
949 setOriginForNaryOp(I);
952 /// \brief Instrument signed relational comparisons.
954 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
955 /// propagating the highest bit of the shadow. Everything else is delegated
956 /// to handleShadowOr().
957 void handleSignedRelationalComparison(ICmpInst &I) {
958 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
959 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
961 CmpInst::Predicate pre = I.getPredicate();
962 if (constOp0 && constOp0->isNullValue() &&
963 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
964 op = I.getOperand(1);
965 } else if (constOp1 && constOp1->isNullValue() &&
966 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
967 op = I.getOperand(0);
972 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
973 setShadow(&I, Shadow);
974 setOrigin(&I, getOrigin(op));
980 void visitICmpInst(ICmpInst &I) {
981 if (ClHandleICmp && I.isEquality())
982 handleEqualityComparison(I);
983 else if (ClHandleICmp && I.isSigned() && I.isRelational())
984 handleSignedRelationalComparison(I);
989 void visitFCmpInst(FCmpInst &I) {
993 void handleShift(BinaryOperator &I) {
995 // If any of the S2 bits are poisoned, the whole thing is poisoned.
996 // Otherwise perform the same shift on S1.
997 Value *S1 = getShadow(&I, 0);
998 Value *S2 = getShadow(&I, 1);
999 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1001 Value *V2 = I.getOperand(1);
1002 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1003 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1004 setOriginForNaryOp(I);
1007 void visitShl(BinaryOperator &I) { handleShift(I); }
1008 void visitAShr(BinaryOperator &I) { handleShift(I); }
1009 void visitLShr(BinaryOperator &I) { handleShift(I); }
1011 /// \brief Instrument llvm.memmove
1013 /// At this point we don't know if llvm.memmove will be inlined or not.
1014 /// If we don't instrument it and it gets inlined,
1015 /// our interceptor will not kick in and we will lose the memmove.
1016 /// If we instrument the call here, but it does not get inlined,
1017 /// we will memove the shadow twice: which is bad in case
1018 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1020 /// Similar situation exists for memcpy and memset.
1021 void visitMemMoveInst(MemMoveInst &I) {
1022 IRBuilder<> IRB(&I);
1025 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1026 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1027 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1028 I.eraseFromParent();
1031 // Similar to memmove: avoid copying shadow twice.
1032 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1033 // FIXME: consider doing manual inline for small constant sizes and proper
1035 void visitMemCpyInst(MemCpyInst &I) {
1036 IRBuilder<> IRB(&I);
1039 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1040 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1041 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1042 I.eraseFromParent();
1046 void visitMemSetInst(MemSetInst &I) {
1047 IRBuilder<> IRB(&I);
1050 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1051 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1052 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1053 I.eraseFromParent();
1056 void visitVAStartInst(VAStartInst &I) {
1057 VAHelper->visitVAStartInst(I);
1060 void visitVACopyInst(VACopyInst &I) {
1061 VAHelper->visitVACopyInst(I);
1064 void visitCallSite(CallSite CS) {
1065 Instruction &I = *CS.getInstruction();
1066 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1068 // Allow only tail calls with the same types, otherwise
1069 // we may have a false positive: shadow for a non-void RetVal
1070 // will get propagated to a void RetVal.
1071 CallInst *Call = cast<CallInst>(&I);
1072 if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1073 Call->setTailCall(false);
1074 if (isa<IntrinsicInst>(&I)) {
1075 // All intrinsics we care about are handled in corresponding visit*
1076 // methods. Add checks for the arguments, mark retval as clean.
1077 visitInstruction(I);
1081 IRBuilder<> IRB(&I);
1082 unsigned ArgOffset = 0;
1083 DEBUG(dbgs() << " CallSite: " << I << "\n");
1084 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1085 ArgIt != End; ++ArgIt) {
1087 unsigned i = ArgIt - CS.arg_begin();
1088 if (!A->getType()->isSized()) {
1089 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1094 // Compute the Shadow for arg even if it is ByVal, because
1095 // in that case getShadow() will copy the actual arg shadow to
1096 // __msan_param_tls.
1097 Value *ArgShadow = getShadow(A);
1098 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1099 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
1100 " Shadow: " << *ArgShadow << "\n");
1101 if (CS.paramHasAttr(i + 1, Attributes::ByVal)) {
1102 assert(A->getType()->isPointerTy() &&
1103 "ByVal argument is not a pointer!");
1104 Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1105 unsigned Alignment = CS.getParamAlignment(i + 1);
1106 Store = IRB.CreateMemCpy(ArgShadowBase,
1107 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1110 Size = MS.TD->getTypeAllocSize(A->getType());
1111 Store = IRB.CreateStore(ArgShadow, ArgShadowBase);
1114 IRB.CreateStore(getOrigin(A),
1115 getOriginPtrForArgument(A, IRB, ArgOffset));
1116 assert(Size != 0 && Store != 0);
1117 DEBUG(dbgs() << " Param:" << *Store << "\n");
1118 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1120 DEBUG(dbgs() << " done with call args\n");
1123 cast<FunctionType>(CS.getCalledValue()->getType()-> getContainedType(0));
1124 if (FT->isVarArg()) {
1125 VAHelper->visitCallSite(CS, IRB);
1128 // Now, get the shadow for the RetVal.
1129 if (!I.getType()->isSized()) return;
1130 IRBuilder<> IRBBefore(&I);
1131 // Untill we have full dynamic coverage, make sure the retval shadow is 0.
1132 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
1133 IRBBefore.CreateStore(getCleanShadow(&I), Base);
1134 Instruction *NextInsn = 0;
1136 NextInsn = I.getNextNode();
1138 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1139 if (!NormalDest->getSinglePredecessor()) {
1140 // FIXME: this case is tricky, so we are just conservative here.
1141 // Perhaps we need to split the edge between this BB and NormalDest,
1142 // but a naive attempt to use SplitEdge leads to a crash.
1143 setShadow(&I, getCleanShadow(&I));
1144 setOrigin(&I, getCleanOrigin());
1147 NextInsn = NormalDest->getFirstInsertionPt();
1149 "Could not find insertion point for retval shadow load");
1151 IRBuilder<> IRBAfter(NextInsn);
1152 setShadow(&I, IRBAfter.CreateLoad(getShadowPtrForRetval(&I, IRBAfter),
1155 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1158 void visitReturnInst(ReturnInst &I) {
1159 IRBuilder<> IRB(&I);
1160 if (Value *RetVal = I.getReturnValue()) {
1161 // Set the shadow for the RetVal.
1162 Value *Shadow = getShadow(RetVal);
1163 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
1164 DEBUG(dbgs() << "Return: " << *Shadow << "\n" << *ShadowPtr << "\n");
1165 IRB.CreateStore(Shadow, ShadowPtr);
1167 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
1171 void visitPHINode(PHINode &I) {
1172 IRBuilder<> IRB(&I);
1173 ShadowPHINodes.push_back(&I);
1174 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
1177 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
1181 void visitAllocaInst(AllocaInst &I) {
1182 setShadow(&I, getCleanShadow(&I));
1183 if (!ClPoisonStack) return;
1184 IRBuilder<> IRB(I.getNextNode());
1185 uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
1186 if (ClPoisonStackWithCall) {
1187 IRB.CreateCall2(MS.MsanPoisonStackFn,
1188 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1189 ConstantInt::get(MS.IntptrTy, Size));
1191 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
1192 IRB.CreateMemSet(ShadowBase, IRB.getInt8(ClPoisonStackPattern),
1193 Size, I.getAlignment());
1196 if (ClTrackOrigins) {
1197 setOrigin(&I, getCleanOrigin());
1198 SmallString<2048> StackDescriptionStorage;
1199 raw_svector_ostream StackDescription(StackDescriptionStorage);
1200 // We create a string with a description of the stack allocation and
1201 // pass it into __msan_set_alloca_origin.
1202 // It will be printed by the run-time if stack-originated UMR is found.
1203 // The first 4 bytes of the string are set to '----' and will be replaced
1204 // by __msan_va_arg_overflow_size_tls at the first call.
1205 StackDescription << "----" << I.getName() << "@" << F.getName();
1207 createPrivateNonConstGlobalForString(*F.getParent(),
1208 StackDescription.str());
1209 IRB.CreateCall3(MS.MsanSetAllocaOriginFn,
1210 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1211 ConstantInt::get(MS.IntptrTy, Size),
1212 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()));
1216 void visitSelectInst(SelectInst& I) {
1217 IRBuilder<> IRB(&I);
1218 setShadow(&I, IRB.CreateSelect(I.getCondition(),
1219 getShadow(I.getTrueValue()), getShadow(I.getFalseValue()),
1222 setOrigin(&I, IRB.CreateSelect(I.getCondition(),
1223 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue())));
1226 void visitLandingPadInst(LandingPadInst &I) {
1228 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
1229 setShadow(&I, getCleanShadow(&I));
1230 setOrigin(&I, getCleanOrigin());
1233 void visitGetElementPtrInst(GetElementPtrInst &I) {
1237 void visitExtractValueInst(ExtractValueInst &I) {
1238 IRBuilder<> IRB(&I);
1239 Value *Agg = I.getAggregateOperand();
1240 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
1241 Value *AggShadow = getShadow(Agg);
1242 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1243 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
1244 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
1245 setShadow(&I, ResShadow);
1246 setOrigin(&I, getCleanOrigin());
1249 void visitInsertValueInst(InsertValueInst &I) {
1250 IRBuilder<> IRB(&I);
1251 DEBUG(dbgs() << "InsertValue: " << I << "\n");
1252 Value *AggShadow = getShadow(I.getAggregateOperand());
1253 Value *InsShadow = getShadow(I.getInsertedValueOperand());
1254 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1255 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
1256 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
1257 DEBUG(dbgs() << " Res: " << *Res << "\n");
1259 setOrigin(&I, getCleanOrigin());
1262 void dumpInst(Instruction &I) {
1263 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1264 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
1266 errs() << "ZZZ " << I.getOpcodeName() << "\n";
1268 errs() << "QQQ " << I << "\n";
1271 void visitResumeInst(ResumeInst &I) {
1272 DEBUG(dbgs() << "Resume: " << I << "\n");
1273 // Nothing to do here.
1276 void visitInstruction(Instruction &I) {
1277 // Everything else: stop propagating and check for poisoned shadow.
1278 if (ClDumpStrictInstructions)
1280 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
1281 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
1282 insertCheck(I.getOperand(i), &I);
1283 setShadow(&I, getCleanShadow(&I));
1284 setOrigin(&I, getCleanOrigin());
1288 /// \brief AMD64-specific implementation of VarArgHelper.
1289 struct VarArgAMD64Helper : public VarArgHelper {
1290 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
1291 // See a comment in visitCallSite for more details.
1292 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
1293 static const unsigned AMD64FpEndOffset = 176;
1296 MemorySanitizer &MS;
1297 MemorySanitizerVisitor &MSV;
1298 Value *VAArgTLSCopy;
1299 Value *VAArgOverflowSize;
1301 SmallVector<CallInst*, 16> VAStartInstrumentationList;
1303 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
1304 MemorySanitizerVisitor &MSV)
1305 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
1307 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
1309 ArgKind classifyArgument(Value* arg) {
1310 // A very rough approximation of X86_64 argument classification rules.
1311 Type *T = arg->getType();
1312 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
1313 return AK_FloatingPoint;
1314 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
1315 return AK_GeneralPurpose;
1316 if (T->isPointerTy())
1317 return AK_GeneralPurpose;
1321 // For VarArg functions, store the argument shadow in an ABI-specific format
1322 // that corresponds to va_list layout.
1323 // We do this because Clang lowers va_arg in the frontend, and this pass
1324 // only sees the low level code that deals with va_list internals.
1325 // A much easier alternative (provided that Clang emits va_arg instructions)
1326 // would have been to associate each live instance of va_list with a copy of
1327 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
1329 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
1330 unsigned GpOffset = 0;
1331 unsigned FpOffset = AMD64GpEndOffset;
1332 unsigned OverflowOffset = AMD64FpEndOffset;
1333 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1334 ArgIt != End; ++ArgIt) {
1336 ArgKind AK = classifyArgument(A);
1337 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
1339 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
1343 case AK_GeneralPurpose:
1344 Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
1347 case AK_FloatingPoint:
1348 Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
1352 uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
1353 Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
1354 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
1356 IRB.CreateStore(MSV.getShadow(A), Base);
1358 Constant *OverflowSize =
1359 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
1360 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
1363 /// \brief Compute the shadow address for a given va_arg.
1364 Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
1366 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
1367 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1368 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
1372 void visitVAStartInst(VAStartInst &I) {
1373 IRBuilder<> IRB(&I);
1374 VAStartInstrumentationList.push_back(&I);
1375 Value *VAListTag = I.getArgOperand(0);
1376 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1378 // Unpoison the whole __va_list_tag.
1379 // FIXME: magic ABI constants.
1380 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1381 /* size */24, /* alignment */16, false);
1384 void visitVACopyInst(VACopyInst &I) {
1385 IRBuilder<> IRB(&I);
1386 Value *VAListTag = I.getArgOperand(0);
1387 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1389 // Unpoison the whole __va_list_tag.
1390 // FIXME: magic ABI constants.
1391 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1392 /* size */ 24, /* alignment */ 16, false);
1395 void finalizeInstrumentation() {
1396 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
1397 "finalizeInstrumentation called twice");
1398 if (!VAStartInstrumentationList.empty()) {
1399 // If there is a va_start in this function, make a backup copy of
1400 // va_arg_tls somewhere in the function entry block.
1401 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1402 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
1404 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
1406 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
1407 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
1410 // Instrument va_start.
1411 // Copy va_list shadow from the backup copy of the TLS contents.
1412 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
1413 CallInst *OrigInst = VAStartInstrumentationList[i];
1414 IRBuilder<> IRB(OrigInst->getNextNode());
1415 Value *VAListTag = OrigInst->getArgOperand(0);
1417 Value *RegSaveAreaPtrPtr =
1419 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1420 ConstantInt::get(MS.IntptrTy, 16)),
1421 Type::getInt64PtrTy(*MS.C));
1422 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
1423 Value *RegSaveAreaShadowPtr =
1424 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
1425 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
1426 AMD64FpEndOffset, 16);
1428 Value *OverflowArgAreaPtrPtr =
1430 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1431 ConstantInt::get(MS.IntptrTy, 8)),
1432 Type::getInt64PtrTy(*MS.C));
1433 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
1434 Value *OverflowArgAreaShadowPtr =
1435 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
1437 getShadowPtrForVAArgument(VAArgTLSCopy, IRB, AMD64FpEndOffset);
1438 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
1443 VarArgHelper* CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
1444 MemorySanitizerVisitor &Visitor) {
1445 return new VarArgAMD64Helper(Func, Msan, Visitor);
1450 bool MemorySanitizer::runOnFunction(Function &F) {
1451 MemorySanitizerVisitor Visitor(F, *this);
1453 // Clear out readonly/readnone attributes.
1455 B.addAttribute(Attributes::ReadOnly)
1456 .addAttribute(Attributes::ReadNone);
1457 F.removeAttribute(AttrListPtr::FunctionIndex,
1458 Attributes::get(F.getContext(), B));
1460 return Visitor.runOnFunction();