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 "llvm/Transforms/Instrumentation.h"
51 #include "BlackList.h"
52 #include "llvm/ADT/DepthFirstIterator.h"
53 #include "llvm/ADT/SmallString.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/ValueMap.h"
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"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Compiler.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
70 #include "llvm/Transforms/Utils/ModuleUtils.h"
71 #include "llvm/Type.h"
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;
80 // This is an important flag that makes the reports much more
81 // informative at the cost of greater slowdown. Not fully implemented
83 // FIXME: this should be a top-level clang flag, e.g.
84 // -fmemory-sanitizer-full.
85 static cl::opt<bool> ClTrackOrigins("msan-track-origins",
86 cl::desc("Track origins (allocation sites) of poisoned memory"),
87 cl::Hidden, cl::init(false));
88 static cl::opt<bool> ClKeepGoing("msan-keep-going",
89 cl::desc("keep going after reporting a UMR"),
90 cl::Hidden, cl::init(false));
91 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
92 cl::desc("poison uninitialized stack variables"),
93 cl::Hidden, cl::init(true));
94 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
95 cl::desc("poison uninitialized stack variables with a call"),
96 cl::Hidden, cl::init(false));
97 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
98 cl::desc("poison uninitialized stack variables with the given patter"),
99 cl::Hidden, cl::init(0xff));
101 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
102 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
103 cl::Hidden, cl::init(true));
105 static cl::opt<bool> ClStoreCleanOrigin("msan-store-clean-origin",
106 cl::desc("store origin for clean (fully initialized) values"),
107 cl::Hidden, cl::init(false));
109 // This flag controls whether we check the shadow of the address
110 // operand of load or store. Such bugs are very rare, since load from
111 // a garbage address typically results in SEGV, but still happen
112 // (e.g. only lower bits of address are garbage, or the access happens
113 // early at program startup where malloc-ed memory is more likely to
114 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
115 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
116 cl::desc("report accesses through a pointer which has poisoned shadow"),
117 cl::Hidden, cl::init(true));
119 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
120 cl::desc("print out instructions with default strict semantics"),
121 cl::Hidden, cl::init(false));
123 static cl::opt<std::string> ClBlackListFile("msan-blacklist",
124 cl::desc("File containing the list of functions where MemorySanitizer "
125 "should not report bugs"), cl::Hidden);
129 /// \brief An instrumentation pass implementing detection of uninitialized
132 /// MemorySanitizer: instrument the code in module to find
133 /// uninitialized reads.
134 class MemorySanitizer : public FunctionPass {
136 MemorySanitizer() : FunctionPass(ID), TD(0), WarningFn(0) { }
137 const char *getPassName() const { return "MemorySanitizer"; }
138 bool runOnFunction(Function &F);
139 bool doInitialization(Module &M);
140 static char ID; // Pass identification, replacement for typeid.
143 void initializeCallbacks(Module &M);
149 /// \brief Thread-local shadow storage for function parameters.
150 GlobalVariable *ParamTLS;
151 /// \brief Thread-local origin storage for function parameters.
152 GlobalVariable *ParamOriginTLS;
153 /// \brief Thread-local shadow storage for function return value.
154 GlobalVariable *RetvalTLS;
155 /// \brief Thread-local origin storage for function return value.
156 GlobalVariable *RetvalOriginTLS;
157 /// \brief Thread-local shadow storage for in-register va_arg function
158 /// parameters (x86_64-specific).
159 GlobalVariable *VAArgTLS;
160 /// \brief Thread-local shadow storage for va_arg overflow area
161 /// (x86_64-specific).
162 GlobalVariable *VAArgOverflowSizeTLS;
163 /// \brief Thread-local space used to pass origin value to the UMR reporting
165 GlobalVariable *OriginTLS;
167 /// \brief The run-time callback to print a warning.
169 /// \brief Run-time helper that copies origin info for a memory range.
170 Value *MsanCopyOriginFn;
171 /// \brief Run-time helper that generates a new origin value for a stack
173 Value *MsanSetAllocaOriginFn;
174 /// \brief Run-time helper that poisons stack on function entry.
175 Value *MsanPoisonStackFn;
176 /// \brief MSan runtime replacements for memmove, memcpy and memset.
177 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
179 /// \brief Address mask used in application-to-shadow address calculation.
180 /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
182 /// \brief Offset of the origin shadow from the "normal" shadow.
183 /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
184 uint64_t OriginOffset;
185 /// \brief Branch weights for error reporting.
186 MDNode *ColdCallWeights;
187 /// \brief Branch weights for origin store.
188 MDNode *OriginStoreWeights;
189 /// \brief The blacklist.
190 OwningPtr<BlackList> BL;
191 /// \brief An empty volatile inline asm that prevents callback merge.
194 friend struct MemorySanitizerVisitor;
195 friend struct VarArgAMD64Helper;
199 char MemorySanitizer::ID = 0;
200 INITIALIZE_PASS(MemorySanitizer, "msan",
201 "MemorySanitizer: detects uninitialized reads.",
204 FunctionPass *llvm::createMemorySanitizerPass() {
205 return new MemorySanitizer();
208 /// \brief Create a non-const global initialized with the given string.
210 /// Creates a writable global for Str so that we can pass it to the
211 /// run-time lib. Runtime uses first 4 bytes of the string to store the
212 /// frame ID, so the string needs to be mutable.
213 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
215 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
216 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
217 GlobalValue::PrivateLinkage, StrConst, "");
221 /// \brief Insert extern declaration of runtime-provided functions and globals.
222 void MemorySanitizer::initializeCallbacks(Module &M) {
223 // Only do this once.
228 // Create the callback.
229 // FIXME: this function should have "Cold" calling conv,
230 // which is not yet implemented.
231 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
232 : "__msan_warning_noreturn";
233 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL);
235 MsanCopyOriginFn = M.getOrInsertFunction(
236 "__msan_copy_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(),
237 IRB.getInt8PtrTy(), IntptrTy, NULL);
238 MsanSetAllocaOriginFn = M.getOrInsertFunction(
239 "__msan_set_alloca_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
240 IRB.getInt8PtrTy(), NULL);
241 MsanPoisonStackFn = M.getOrInsertFunction(
242 "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL);
243 MemmoveFn = M.getOrInsertFunction(
244 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
246 MemcpyFn = M.getOrInsertFunction(
247 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
249 MemsetFn = M.getOrInsertFunction(
250 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
254 RetvalTLS = new GlobalVariable(
255 M, ArrayType::get(IRB.getInt64Ty(), 8), false,
256 GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0,
257 GlobalVariable::GeneralDynamicTLSModel);
258 RetvalOriginTLS = new GlobalVariable(
259 M, OriginTy, false, GlobalVariable::ExternalLinkage, 0,
260 "__msan_retval_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
262 ParamTLS = new GlobalVariable(
263 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
264 GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0,
265 GlobalVariable::GeneralDynamicTLSModel);
266 ParamOriginTLS = new GlobalVariable(
267 M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage,
268 0, "__msan_param_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
270 VAArgTLS = new GlobalVariable(
271 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
272 GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0,
273 GlobalVariable::GeneralDynamicTLSModel);
274 VAArgOverflowSizeTLS = new GlobalVariable(
275 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0,
276 "__msan_va_arg_overflow_size_tls", 0,
277 GlobalVariable::GeneralDynamicTLSModel);
278 OriginTLS = new GlobalVariable(
279 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0,
280 "__msan_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
282 // We insert an empty inline asm after __msan_report* to avoid callback merge.
283 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
284 StringRef(""), StringRef(""),
285 /*hasSideEffects=*/true);
288 /// \brief Module-level initialization.
290 /// inserts a call to __msan_init to the module's constructor list.
291 bool MemorySanitizer::doInitialization(Module &M) {
292 TD = getAnalysisIfAvailable<DataLayout>();
295 BL.reset(new BlackList(ClBlackListFile));
296 C = &(M.getContext());
297 unsigned PtrSize = TD->getPointerSizeInBits(/* AddressSpace */0);
300 ShadowMask = kShadowMask64;
301 OriginOffset = kOriginOffset64;
304 ShadowMask = kShadowMask32;
305 OriginOffset = kOriginOffset32;
308 report_fatal_error("unsupported pointer size");
313 IntptrTy = IRB.getIntPtrTy(TD);
314 OriginTy = IRB.getInt32Ty();
316 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
317 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
319 // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
320 appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
321 "__msan_init", IRB.getVoidTy(), NULL)), 0);
323 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
324 IRB.getInt32(ClTrackOrigins), "__msan_track_origins");
331 /// \brief A helper class that handles instrumentation of VarArg
332 /// functions on a particular platform.
334 /// Implementations are expected to insert the instrumentation
335 /// necessary to propagate argument shadow through VarArg function
336 /// calls. Visit* methods are called during an InstVisitor pass over
337 /// the function, and should avoid creating new basic blocks. A new
338 /// instance of this class is created for each instrumented function.
339 struct VarArgHelper {
340 /// \brief Visit a CallSite.
341 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
343 /// \brief Visit a va_start call.
344 virtual void visitVAStartInst(VAStartInst &I) = 0;
346 /// \brief Visit a va_copy call.
347 virtual void visitVACopyInst(VACopyInst &I) = 0;
349 /// \brief Finalize function instrumentation.
351 /// This method is called after visiting all interesting (see above)
352 /// instructions in a function.
353 virtual void finalizeInstrumentation() = 0;
355 virtual ~VarArgHelper() {}
358 struct MemorySanitizerVisitor;
361 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
362 MemorySanitizerVisitor &Visitor);
364 /// This class does all the work for a given function. Store and Load
365 /// instructions store and load corresponding shadow and origin
366 /// values. Most instructions propagate shadow from arguments to their
367 /// return values. Certain instructions (most importantly, BranchInst)
368 /// test their argument shadow and print reports (with a runtime call) if it's
370 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
373 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
374 ValueMap<Value*, Value*> ShadowMap, OriginMap;
376 OwningPtr<VarArgHelper> VAHelper;
378 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
379 // See a comment in visitCallSite for more details.
380 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
381 static const unsigned AMD64FpEndOffset = 176;
383 struct ShadowOriginAndInsertPoint {
386 Instruction *OrigIns;
387 ShadowOriginAndInsertPoint(Instruction *S, Instruction *O, Instruction *I)
388 : Shadow(S), Origin(O), OrigIns(I) { }
389 ShadowOriginAndInsertPoint() : Shadow(0), Origin(0), OrigIns(0) { }
391 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
392 SmallVector<Instruction*, 16> StoreList;
394 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
395 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
396 InsertChecks = !MS.BL->isIn(F);
397 DEBUG(if (!InsertChecks)
398 dbgs() << "MemorySanitizer is not inserting checks into '"
399 << F.getName() << "'\n");
402 void materializeStores() {
403 for (size_t i = 0, n = StoreList.size(); i < n; i++) {
404 StoreInst& I = *dyn_cast<StoreInst>(StoreList[i]);
407 Value *Val = I.getValueOperand();
408 Value *Addr = I.getPointerOperand();
409 Value *Shadow = getShadow(Val);
410 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
412 StoreInst *NewSI = IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment());
413 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
414 // If the store is volatile, add a check.
416 insertCheck(Val, &I);
417 if (ClCheckAccessAddress)
418 insertCheck(Addr, &I);
420 if (ClTrackOrigins) {
421 if (ClStoreCleanOrigin || isa<StructType>(Shadow->getType())) {
422 IRB.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRB), I.getAlignment());
424 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
426 Constant *Cst = dyn_cast_or_null<Constant>(ConvertedShadow);
427 // TODO(eugenis): handle non-zero constant shadow by inserting an
428 // unconditional check (can not simply fail compilation as this could
429 // be in the dead code).
433 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
434 getCleanShadow(ConvertedShadow), "_mscmp");
435 Instruction *CheckTerm =
436 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false, MS.OriginStoreWeights);
437 IRBuilder<> IRBNewBlock(CheckTerm);
438 IRBNewBlock.CreateAlignedStore(getOrigin(Val),
439 getOriginPtr(Addr, IRBNewBlock), I.getAlignment());
445 void materializeChecks() {
446 for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) {
447 Instruction *Shadow = InstrumentationList[i].Shadow;
448 Instruction *OrigIns = InstrumentationList[i].OrigIns;
449 IRBuilder<> IRB(OrigIns);
450 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
451 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
452 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
453 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
454 getCleanShadow(ConvertedShadow), "_mscmp");
455 Instruction *CheckTerm =
456 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp),
457 /* Unreachable */ !ClKeepGoing,
460 IRB.SetInsertPoint(CheckTerm);
461 if (ClTrackOrigins) {
462 Instruction *Origin = InstrumentationList[i].Origin;
463 IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0),
466 CallInst *Call = IRB.CreateCall(MS.WarningFn);
467 Call->setDebugLoc(OrigIns->getDebugLoc());
468 IRB.CreateCall(MS.EmptyAsm);
469 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
471 DEBUG(dbgs() << "DONE:\n" << F);
474 /// \brief Add MemorySanitizer instrumentation to a function.
475 bool runOnFunction() {
476 MS.initializeCallbacks(*F.getParent());
477 if (!MS.TD) return false;
478 // Iterate all BBs in depth-first order and create shadow instructions
479 // for all instructions (where applicable).
480 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
481 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
482 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
483 BasicBlock *BB = *DI;
487 // Finalize PHI nodes.
488 for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) {
489 PHINode *PN = ShadowPHINodes[i];
490 PHINode *PNS = cast<PHINode>(getShadow(PN));
491 PHINode *PNO = ClTrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0;
492 size_t NumValues = PN->getNumIncomingValues();
493 for (size_t v = 0; v < NumValues; v++) {
494 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
496 PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
500 VAHelper->finalizeInstrumentation();
502 // Delayed instrumentation of StoreInst.
503 // This make add new checks to inserted later.
506 // Insert shadow value checks.
512 /// \brief Compute the shadow type that corresponds to a given Value.
513 Type *getShadowTy(Value *V) {
514 return getShadowTy(V->getType());
517 /// \brief Compute the shadow type that corresponds to a given Type.
518 Type *getShadowTy(Type *OrigTy) {
519 if (!OrigTy->isSized()) {
522 // For integer type, shadow is the same as the original type.
523 // This may return weird-sized types like i1.
524 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
526 if (VectorType *VT = dyn_cast<VectorType>(OrigTy))
527 return VectorType::getInteger(VT);
528 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
529 SmallVector<Type*, 4> Elements;
530 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
531 Elements.push_back(getShadowTy(ST->getElementType(i)));
532 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
533 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
536 uint32_t TypeSize = MS.TD->getTypeStoreSizeInBits(OrigTy);
537 return IntegerType::get(*MS.C, TypeSize);
540 /// \brief Flatten a vector type.
541 Type *getShadowTyNoVec(Type *ty) {
542 if (VectorType *vt = dyn_cast<VectorType>(ty))
543 return IntegerType::get(*MS.C, vt->getBitWidth());
547 /// \brief Convert a shadow value to it's flattened variant.
548 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
549 Type *Ty = V->getType();
550 Type *NoVecTy = getShadowTyNoVec(Ty);
551 if (Ty == NoVecTy) return V;
552 return IRB.CreateBitCast(V, NoVecTy);
555 /// \brief Compute the shadow address that corresponds to a given application
558 /// Shadow = Addr & ~ShadowMask.
559 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
562 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
563 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
564 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
567 /// \brief Compute the origin address that corresponds to a given application
570 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
571 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
573 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
574 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
576 IRB.CreateAdd(ShadowLong,
577 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
579 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
580 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
583 /// \brief Compute the shadow address for a given function argument.
585 /// Shadow = ParamTLS+ArgOffset.
586 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
588 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
589 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
590 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
594 /// \brief Compute the origin address for a given function argument.
595 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
597 if (!ClTrackOrigins) return 0;
598 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
599 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
600 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
604 /// \brief Compute the shadow address for a retval.
605 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
606 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
607 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
611 /// \brief Compute the origin address for a retval.
612 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
613 // We keep a single origin for the entire retval. Might be too optimistic.
614 return MS.RetvalOriginTLS;
617 /// \brief Set SV to be the shadow value for V.
618 void setShadow(Value *V, Value *SV) {
619 assert(!ShadowMap.count(V) && "Values may only have one shadow");
623 /// \brief Set Origin to be the origin value for V.
624 void setOrigin(Value *V, Value *Origin) {
625 if (!ClTrackOrigins) return;
626 assert(!OriginMap.count(V) && "Values may only have one origin");
627 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
628 OriginMap[V] = Origin;
631 /// \brief Create a clean shadow value for a given value.
633 /// Clean shadow (all zeroes) means all bits of the value are defined
635 Value *getCleanShadow(Value *V) {
636 Type *ShadowTy = getShadowTy(V);
639 return Constant::getNullValue(ShadowTy);
642 /// \brief Create a dirty shadow of a given shadow type.
643 Constant *getPoisonedShadow(Type *ShadowTy) {
645 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
646 return Constant::getAllOnesValue(ShadowTy);
647 StructType *ST = cast<StructType>(ShadowTy);
648 SmallVector<Constant *, 4> Vals;
649 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
650 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
651 return ConstantStruct::get(ST, Vals);
654 /// \brief Create a clean (zero) origin.
655 Value *getCleanOrigin() {
656 return Constant::getNullValue(MS.OriginTy);
659 /// \brief Get the shadow value for a given Value.
661 /// This function either returns the value set earlier with setShadow,
662 /// or extracts if from ParamTLS (for function arguments).
663 Value *getShadow(Value *V) {
664 if (Instruction *I = dyn_cast<Instruction>(V)) {
665 // For instructions the shadow is already stored in the map.
666 Value *Shadow = ShadowMap[V];
668 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
670 assert(Shadow && "No shadow for a value");
674 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
675 Value *AllOnes = getPoisonedShadow(getShadowTy(V));
676 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
680 if (Argument *A = dyn_cast<Argument>(V)) {
681 // For arguments we compute the shadow on demand and store it in the map.
682 Value **ShadowPtr = &ShadowMap[V];
685 Function *F = A->getParent();
686 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
687 unsigned ArgOffset = 0;
688 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
690 if (!AI->getType()->isSized()) {
691 DEBUG(dbgs() << "Arg is not sized\n");
694 unsigned Size = AI->hasByValAttr()
695 ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
696 : MS.TD->getTypeAllocSize(AI->getType());
698 Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
699 if (AI->hasByValAttr()) {
700 // ByVal pointer itself has clean shadow. We copy the actual
701 // argument shadow to the underlying memory.
702 Value *Cpy = EntryIRB.CreateMemCpy(
703 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
704 Base, Size, AI->getParamAlignment());
705 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
707 *ShadowPtr = getCleanShadow(V);
709 *ShadowPtr = EntryIRB.CreateLoad(Base);
711 DEBUG(dbgs() << " ARG: " << *AI << " ==> " <<
712 **ShadowPtr << "\n");
713 if (ClTrackOrigins) {
714 Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
715 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
718 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
720 assert(*ShadowPtr && "Could not find shadow for an argument");
723 // For everything else the shadow is zero.
724 return getCleanShadow(V);
727 /// \brief Get the shadow for i-th argument of the instruction I.
728 Value *getShadow(Instruction *I, int i) {
729 return getShadow(I->getOperand(i));
732 /// \brief Get the origin for a value.
733 Value *getOrigin(Value *V) {
734 if (!ClTrackOrigins) return 0;
735 if (isa<Instruction>(V) || isa<Argument>(V)) {
736 Value *Origin = OriginMap[V];
738 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
739 Origin = getCleanOrigin();
743 return getCleanOrigin();
746 /// \brief Get the origin for i-th argument of the instruction I.
747 Value *getOrigin(Instruction *I, int i) {
748 return getOrigin(I->getOperand(i));
751 /// \brief Remember the place where a shadow check should be inserted.
753 /// This location will be later instrumented with a check that will print a
754 /// UMR warning in runtime if the value is not fully defined.
755 void insertCheck(Value *Val, Instruction *OrigIns) {
757 if (!InsertChecks) return;
758 Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
761 Type *ShadowTy = Shadow->getType();
762 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
763 "Can only insert checks for integer and vector shadow types");
765 Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
766 InstrumentationList.push_back(
767 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
770 //------------------- Visitors.
772 /// \brief Instrument LoadInst
774 /// Loads the corresponding shadow and (optionally) origin.
775 /// Optionally, checks that the load address is fully defined.
776 void visitLoadInst(LoadInst &I) {
777 assert(I.getType()->isSized() && "Load type must have size");
779 Type *ShadowTy = getShadowTy(&I);
780 Value *Addr = I.getPointerOperand();
781 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
782 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
784 if (ClCheckAccessAddress)
785 insertCheck(I.getPointerOperand(), &I);
788 setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), I.getAlignment()));
791 /// \brief Instrument StoreInst
793 /// Stores the corresponding shadow and (optionally) origin.
794 /// Optionally, checks that the store address is fully defined.
795 /// Volatile stores check that the value being stored is fully defined.
796 void visitStoreInst(StoreInst &I) {
797 StoreList.push_back(&I);
800 // Vector manipulation.
801 void visitExtractElementInst(ExtractElementInst &I) {
802 insertCheck(I.getOperand(1), &I);
804 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
806 setOrigin(&I, getOrigin(&I, 0));
809 void visitInsertElementInst(InsertElementInst &I) {
810 insertCheck(I.getOperand(2), &I);
812 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
813 I.getOperand(2), "_msprop"));
814 setOriginForNaryOp(I);
817 void visitShuffleVectorInst(ShuffleVectorInst &I) {
818 insertCheck(I.getOperand(2), &I);
820 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
821 I.getOperand(2), "_msprop"));
822 setOriginForNaryOp(I);
826 void visitSExtInst(SExtInst &I) {
828 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
829 setOrigin(&I, getOrigin(&I, 0));
832 void visitZExtInst(ZExtInst &I) {
834 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
835 setOrigin(&I, getOrigin(&I, 0));
838 void visitTruncInst(TruncInst &I) {
840 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
841 setOrigin(&I, getOrigin(&I, 0));
844 void visitBitCastInst(BitCastInst &I) {
846 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
847 setOrigin(&I, getOrigin(&I, 0));
850 void visitPtrToIntInst(PtrToIntInst &I) {
852 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
853 "_msprop_ptrtoint"));
854 setOrigin(&I, getOrigin(&I, 0));
857 void visitIntToPtrInst(IntToPtrInst &I) {
859 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
860 "_msprop_inttoptr"));
861 setOrigin(&I, getOrigin(&I, 0));
864 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
865 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
866 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
867 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
868 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
869 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
871 /// \brief Propagate shadow for bitwise AND.
873 /// This code is exact, i.e. if, for example, a bit in the left argument
874 /// is defined and 0, then neither the value not definedness of the
875 /// corresponding bit in B don't affect the resulting shadow.
876 void visitAnd(BinaryOperator &I) {
878 // "And" of 0 and a poisoned value results in unpoisoned value.
879 // 1&1 => 1; 0&1 => 0; p&1 => p;
880 // 1&0 => 0; 0&0 => 0; p&0 => 0;
881 // 1&p => p; 0&p => 0; p&p => p;
882 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
883 Value *S1 = getShadow(&I, 0);
884 Value *S2 = getShadow(&I, 1);
885 Value *V1 = I.getOperand(0);
886 Value *V2 = I.getOperand(1);
887 if (V1->getType() != S1->getType()) {
888 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
889 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
891 Value *S1S2 = IRB.CreateAnd(S1, S2);
892 Value *V1S2 = IRB.CreateAnd(V1, S2);
893 Value *S1V2 = IRB.CreateAnd(S1, V2);
894 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
895 setOriginForNaryOp(I);
898 void visitOr(BinaryOperator &I) {
900 // "Or" of 1 and a poisoned value results in unpoisoned value.
901 // 1|1 => 1; 0|1 => 1; p|1 => 1;
902 // 1|0 => 1; 0|0 => 0; p|0 => p;
903 // 1|p => 1; 0|p => p; p|p => p;
904 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
905 Value *S1 = getShadow(&I, 0);
906 Value *S2 = getShadow(&I, 1);
907 Value *V1 = IRB.CreateNot(I.getOperand(0));
908 Value *V2 = IRB.CreateNot(I.getOperand(1));
909 if (V1->getType() != S1->getType()) {
910 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
911 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
913 Value *S1S2 = IRB.CreateAnd(S1, S2);
914 Value *V1S2 = IRB.CreateAnd(V1, S2);
915 Value *S1V2 = IRB.CreateAnd(S1, V2);
916 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
917 setOriginForNaryOp(I);
920 /// \brief Propagate origin for an instruction.
922 /// This is a general case of origin propagation. For an Nary operation,
923 /// is set to the origin of an argument that is not entirely initialized.
924 /// If there is more than one such arguments, the rightmost of them is picked.
925 /// It does not matter which one is picked if all arguments are initialized.
926 void setOriginForNaryOp(Instruction &I) {
927 if (!ClTrackOrigins) return;
929 Value *Origin = getOrigin(&I, 0);
930 for (unsigned Op = 1, n = I.getNumOperands(); Op < n; ++Op) {
931 Value *S = convertToShadowTyNoVec(getShadow(&I, Op), IRB);
932 Origin = IRB.CreateSelect(IRB.CreateICmpNE(S, getCleanShadow(S)),
933 getOrigin(&I, Op), Origin);
935 setOrigin(&I, Origin);
938 /// \brief Propagate shadow for a binary operation.
940 /// Shadow = Shadow0 | Shadow1, all 3 must have the same type.
941 /// Bitwise OR is selected as an operation that will never lose even a bit of
943 void handleShadowOrBinary(Instruction &I) {
945 Value *Shadow0 = getShadow(&I, 0);
946 Value *Shadow1 = getShadow(&I, 1);
947 setShadow(&I, IRB.CreateOr(Shadow0, Shadow1, "_msprop"));
948 setOriginForNaryOp(I);
951 /// \brief Propagate shadow for arbitrary operation.
953 /// This is a general case of shadow propagation, used in all cases where we
954 /// don't know and/or care about what the operation actually does.
955 /// It converts all input shadow values to a common type (extending or
956 /// truncating as necessary), and bitwise OR's them.
958 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
959 /// fully initialized), and less prone to false positives.
960 // FIXME: is the casting actually correct?
961 // FIXME: merge this with handleShadowOrBinary.
962 void handleShadowOr(Instruction &I) {
964 Value *Shadow = getShadow(&I, 0);
965 for (unsigned Op = 1, n = I.getNumOperands(); Op < n; ++Op)
966 Shadow = IRB.CreateOr(
967 Shadow, IRB.CreateIntCast(getShadow(&I, Op), Shadow->getType(), false),
969 Shadow = IRB.CreateIntCast(Shadow, getShadowTy(&I), false);
970 setShadow(&I, Shadow);
971 setOriginForNaryOp(I);
974 void visitFAdd(BinaryOperator &I) { handleShadowOrBinary(I); }
975 void visitFSub(BinaryOperator &I) { handleShadowOrBinary(I); }
976 void visitFMul(BinaryOperator &I) { handleShadowOrBinary(I); }
977 void visitAdd(BinaryOperator &I) { handleShadowOrBinary(I); }
978 void visitSub(BinaryOperator &I) { handleShadowOrBinary(I); }
979 void visitXor(BinaryOperator &I) { handleShadowOrBinary(I); }
980 void visitMul(BinaryOperator &I) { handleShadowOrBinary(I); }
982 void handleDiv(Instruction &I) {
984 // Strict on the second argument.
985 insertCheck(I.getOperand(1), &I);
986 setShadow(&I, getShadow(&I, 0));
987 setOrigin(&I, getOrigin(&I, 0));
990 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
991 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
992 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
993 void visitURem(BinaryOperator &I) { handleDiv(I); }
994 void visitSRem(BinaryOperator &I) { handleDiv(I); }
995 void visitFRem(BinaryOperator &I) { handleDiv(I); }
997 /// \brief Instrument == and != comparisons.
999 /// Sometimes the comparison result is known even if some of the bits of the
1000 /// arguments are not.
1001 void handleEqualityComparison(ICmpInst &I) {
1002 IRBuilder<> IRB(&I);
1003 Value *A = I.getOperand(0);
1004 Value *B = I.getOperand(1);
1005 Value *Sa = getShadow(A);
1006 Value *Sb = getShadow(B);
1007 if (A->getType()->isPointerTy())
1008 A = IRB.CreatePointerCast(A, MS.IntptrTy);
1009 if (B->getType()->isPointerTy())
1010 B = IRB.CreatePointerCast(B, MS.IntptrTy);
1011 // A == B <==> (C = A^B) == 0
1012 // A != B <==> (C = A^B) != 0
1014 Value *C = IRB.CreateXor(A, B);
1015 Value *Sc = IRB.CreateOr(Sa, Sb);
1016 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1017 // Result is defined if one of the following is true
1018 // * there is a defined 1 bit in C
1019 // * C is fully defined
1020 // Si = !(C & ~Sc) && Sc
1021 Value *Zero = Constant::getNullValue(Sc->getType());
1022 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1024 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1026 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1027 Si->setName("_msprop_icmp");
1029 setOriginForNaryOp(I);
1032 /// \brief Instrument signed relational comparisons.
1034 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1035 /// propagating the highest bit of the shadow. Everything else is delegated
1036 /// to handleShadowOr().
1037 void handleSignedRelationalComparison(ICmpInst &I) {
1038 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1039 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1041 CmpInst::Predicate pre = I.getPredicate();
1042 if (constOp0 && constOp0->isNullValue() &&
1043 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1044 op = I.getOperand(1);
1045 } else if (constOp1 && constOp1->isNullValue() &&
1046 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1047 op = I.getOperand(0);
1050 IRBuilder<> IRB(&I);
1052 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1053 setShadow(&I, Shadow);
1054 setOrigin(&I, getOrigin(op));
1060 void visitICmpInst(ICmpInst &I) {
1061 if (ClHandleICmp && I.isEquality())
1062 handleEqualityComparison(I);
1063 else if (ClHandleICmp && I.isSigned() && I.isRelational())
1064 handleSignedRelationalComparison(I);
1069 void visitFCmpInst(FCmpInst &I) {
1073 void handleShift(BinaryOperator &I) {
1074 IRBuilder<> IRB(&I);
1075 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1076 // Otherwise perform the same shift on S1.
1077 Value *S1 = getShadow(&I, 0);
1078 Value *S2 = getShadow(&I, 1);
1079 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1081 Value *V2 = I.getOperand(1);
1082 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1083 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1084 setOriginForNaryOp(I);
1087 void visitShl(BinaryOperator &I) { handleShift(I); }
1088 void visitAShr(BinaryOperator &I) { handleShift(I); }
1089 void visitLShr(BinaryOperator &I) { handleShift(I); }
1091 /// \brief Instrument llvm.memmove
1093 /// At this point we don't know if llvm.memmove will be inlined or not.
1094 /// If we don't instrument it and it gets inlined,
1095 /// our interceptor will not kick in and we will lose the memmove.
1096 /// If we instrument the call here, but it does not get inlined,
1097 /// we will memove the shadow twice: which is bad in case
1098 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1100 /// Similar situation exists for memcpy and memset.
1101 void visitMemMoveInst(MemMoveInst &I) {
1102 IRBuilder<> IRB(&I);
1105 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1106 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1107 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1108 I.eraseFromParent();
1111 // Similar to memmove: avoid copying shadow twice.
1112 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1113 // FIXME: consider doing manual inline for small constant sizes and proper
1115 void visitMemCpyInst(MemCpyInst &I) {
1116 IRBuilder<> IRB(&I);
1119 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1120 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1121 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1122 I.eraseFromParent();
1126 void visitMemSetInst(MemSetInst &I) {
1127 IRBuilder<> IRB(&I);
1130 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1131 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1132 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1133 I.eraseFromParent();
1136 void visitVAStartInst(VAStartInst &I) {
1137 VAHelper->visitVAStartInst(I);
1140 void visitVACopyInst(VACopyInst &I) {
1141 VAHelper->visitVACopyInst(I);
1144 void handleBswap(IntrinsicInst &I) {
1145 IRBuilder<> IRB(&I);
1146 Value *Op = I.getArgOperand(0);
1147 Type *OpType = Op->getType();
1148 Function *BswapFunc = Intrinsic::getDeclaration(
1149 F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1));
1150 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1151 setOrigin(&I, getOrigin(Op));
1154 void visitIntrinsicInst(IntrinsicInst &I) {
1155 switch (I.getIntrinsicID()) {
1156 case llvm::Intrinsic::bswap:
1157 handleBswap(I); break;
1159 visitInstruction(I); break;
1163 void visitCallSite(CallSite CS) {
1164 Instruction &I = *CS.getInstruction();
1165 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1167 CallInst *Call = cast<CallInst>(&I);
1169 // For inline asm, do the usual thing: check argument shadow and mark all
1170 // outputs as clean. Note that any side effects of the inline asm that are
1171 // not immediately visible in its constraints are not handled.
1172 if (Call->isInlineAsm()) {
1173 visitInstruction(I);
1177 // Allow only tail calls with the same types, otherwise
1178 // we may have a false positive: shadow for a non-void RetVal
1179 // will get propagated to a void RetVal.
1180 if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1181 Call->setTailCall(false);
1183 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
1185 IRBuilder<> IRB(&I);
1186 unsigned ArgOffset = 0;
1187 DEBUG(dbgs() << " CallSite: " << I << "\n");
1188 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1189 ArgIt != End; ++ArgIt) {
1191 unsigned i = ArgIt - CS.arg_begin();
1192 if (!A->getType()->isSized()) {
1193 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1198 // Compute the Shadow for arg even if it is ByVal, because
1199 // in that case getShadow() will copy the actual arg shadow to
1200 // __msan_param_tls.
1201 Value *ArgShadow = getShadow(A);
1202 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1203 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
1204 " Shadow: " << *ArgShadow << "\n");
1205 if (CS.paramHasAttr(i + 1, Attributes::ByVal)) {
1206 assert(A->getType()->isPointerTy() &&
1207 "ByVal argument is not a pointer!");
1208 Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1209 unsigned Alignment = CS.getParamAlignment(i + 1);
1210 Store = IRB.CreateMemCpy(ArgShadowBase,
1211 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1214 Size = MS.TD->getTypeAllocSize(A->getType());
1215 Store = IRB.CreateStore(ArgShadow, ArgShadowBase);
1218 IRB.CreateStore(getOrigin(A),
1219 getOriginPtrForArgument(A, IRB, ArgOffset));
1220 assert(Size != 0 && Store != 0);
1221 DEBUG(dbgs() << " Param:" << *Store << "\n");
1222 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1224 DEBUG(dbgs() << " done with call args\n");
1227 cast<FunctionType>(CS.getCalledValue()->getType()-> getContainedType(0));
1228 if (FT->isVarArg()) {
1229 VAHelper->visitCallSite(CS, IRB);
1232 // Now, get the shadow for the RetVal.
1233 if (!I.getType()->isSized()) return;
1234 IRBuilder<> IRBBefore(&I);
1235 // Untill we have full dynamic coverage, make sure the retval shadow is 0.
1236 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
1237 IRBBefore.CreateStore(getCleanShadow(&I), Base);
1238 Instruction *NextInsn = 0;
1240 NextInsn = I.getNextNode();
1242 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1243 if (!NormalDest->getSinglePredecessor()) {
1244 // FIXME: this case is tricky, so we are just conservative here.
1245 // Perhaps we need to split the edge between this BB and NormalDest,
1246 // but a naive attempt to use SplitEdge leads to a crash.
1247 setShadow(&I, getCleanShadow(&I));
1248 setOrigin(&I, getCleanOrigin());
1251 NextInsn = NormalDest->getFirstInsertionPt();
1253 "Could not find insertion point for retval shadow load");
1255 IRBuilder<> IRBAfter(NextInsn);
1256 setShadow(&I, IRBAfter.CreateLoad(getShadowPtrForRetval(&I, IRBAfter),
1259 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1262 void visitReturnInst(ReturnInst &I) {
1263 IRBuilder<> IRB(&I);
1264 if (Value *RetVal = I.getReturnValue()) {
1265 // Set the shadow for the RetVal.
1266 Value *Shadow = getShadow(RetVal);
1267 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
1268 DEBUG(dbgs() << "Return: " << *Shadow << "\n" << *ShadowPtr << "\n");
1269 IRB.CreateStore(Shadow, ShadowPtr);
1271 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
1275 void visitPHINode(PHINode &I) {
1276 IRBuilder<> IRB(&I);
1277 ShadowPHINodes.push_back(&I);
1278 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
1281 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
1285 void visitAllocaInst(AllocaInst &I) {
1286 setShadow(&I, getCleanShadow(&I));
1287 if (!ClPoisonStack) return;
1288 IRBuilder<> IRB(I.getNextNode());
1289 uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
1290 if (ClPoisonStackWithCall) {
1291 IRB.CreateCall2(MS.MsanPoisonStackFn,
1292 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1293 ConstantInt::get(MS.IntptrTy, Size));
1295 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
1296 IRB.CreateMemSet(ShadowBase, IRB.getInt8(ClPoisonStackPattern),
1297 Size, I.getAlignment());
1300 if (ClTrackOrigins) {
1301 setOrigin(&I, getCleanOrigin());
1302 SmallString<2048> StackDescriptionStorage;
1303 raw_svector_ostream StackDescription(StackDescriptionStorage);
1304 // We create a string with a description of the stack allocation and
1305 // pass it into __msan_set_alloca_origin.
1306 // It will be printed by the run-time if stack-originated UMR is found.
1307 // The first 4 bytes of the string are set to '----' and will be replaced
1308 // by __msan_va_arg_overflow_size_tls at the first call.
1309 StackDescription << "----" << I.getName() << "@" << F.getName();
1311 createPrivateNonConstGlobalForString(*F.getParent(),
1312 StackDescription.str());
1313 IRB.CreateCall3(MS.MsanSetAllocaOriginFn,
1314 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1315 ConstantInt::get(MS.IntptrTy, Size),
1316 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()));
1320 void visitSelectInst(SelectInst& I) {
1321 IRBuilder<> IRB(&I);
1322 setShadow(&I, IRB.CreateSelect(I.getCondition(),
1323 getShadow(I.getTrueValue()), getShadow(I.getFalseValue()),
1326 setOrigin(&I, IRB.CreateSelect(I.getCondition(),
1327 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue())));
1330 void visitLandingPadInst(LandingPadInst &I) {
1332 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
1333 setShadow(&I, getCleanShadow(&I));
1334 setOrigin(&I, getCleanOrigin());
1337 void visitGetElementPtrInst(GetElementPtrInst &I) {
1341 void visitExtractValueInst(ExtractValueInst &I) {
1342 IRBuilder<> IRB(&I);
1343 Value *Agg = I.getAggregateOperand();
1344 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
1345 Value *AggShadow = getShadow(Agg);
1346 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1347 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
1348 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
1349 setShadow(&I, ResShadow);
1350 setOrigin(&I, getCleanOrigin());
1353 void visitInsertValueInst(InsertValueInst &I) {
1354 IRBuilder<> IRB(&I);
1355 DEBUG(dbgs() << "InsertValue: " << I << "\n");
1356 Value *AggShadow = getShadow(I.getAggregateOperand());
1357 Value *InsShadow = getShadow(I.getInsertedValueOperand());
1358 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1359 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
1360 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
1361 DEBUG(dbgs() << " Res: " << *Res << "\n");
1363 setOrigin(&I, getCleanOrigin());
1366 void dumpInst(Instruction &I) {
1367 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1368 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
1370 errs() << "ZZZ " << I.getOpcodeName() << "\n";
1372 errs() << "QQQ " << I << "\n";
1375 void visitResumeInst(ResumeInst &I) {
1376 DEBUG(dbgs() << "Resume: " << I << "\n");
1377 // Nothing to do here.
1380 void visitInstruction(Instruction &I) {
1381 // Everything else: stop propagating and check for poisoned shadow.
1382 if (ClDumpStrictInstructions)
1384 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
1385 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
1386 insertCheck(I.getOperand(i), &I);
1387 setShadow(&I, getCleanShadow(&I));
1388 setOrigin(&I, getCleanOrigin());
1392 /// \brief AMD64-specific implementation of VarArgHelper.
1393 struct VarArgAMD64Helper : public VarArgHelper {
1394 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
1395 // See a comment in visitCallSite for more details.
1396 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
1397 static const unsigned AMD64FpEndOffset = 176;
1400 MemorySanitizer &MS;
1401 MemorySanitizerVisitor &MSV;
1402 Value *VAArgTLSCopy;
1403 Value *VAArgOverflowSize;
1405 SmallVector<CallInst*, 16> VAStartInstrumentationList;
1407 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
1408 MemorySanitizerVisitor &MSV)
1409 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
1411 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
1413 ArgKind classifyArgument(Value* arg) {
1414 // A very rough approximation of X86_64 argument classification rules.
1415 Type *T = arg->getType();
1416 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
1417 return AK_FloatingPoint;
1418 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
1419 return AK_GeneralPurpose;
1420 if (T->isPointerTy())
1421 return AK_GeneralPurpose;
1425 // For VarArg functions, store the argument shadow in an ABI-specific format
1426 // that corresponds to va_list layout.
1427 // We do this because Clang lowers va_arg in the frontend, and this pass
1428 // only sees the low level code that deals with va_list internals.
1429 // A much easier alternative (provided that Clang emits va_arg instructions)
1430 // would have been to associate each live instance of va_list with a copy of
1431 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
1433 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
1434 unsigned GpOffset = 0;
1435 unsigned FpOffset = AMD64GpEndOffset;
1436 unsigned OverflowOffset = AMD64FpEndOffset;
1437 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1438 ArgIt != End; ++ArgIt) {
1440 ArgKind AK = classifyArgument(A);
1441 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
1443 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
1447 case AK_GeneralPurpose:
1448 Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
1451 case AK_FloatingPoint:
1452 Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
1456 uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
1457 Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
1458 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
1460 IRB.CreateStore(MSV.getShadow(A), Base);
1462 Constant *OverflowSize =
1463 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
1464 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
1467 /// \brief Compute the shadow address for a given va_arg.
1468 Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
1470 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
1471 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1472 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
1476 void visitVAStartInst(VAStartInst &I) {
1477 IRBuilder<> IRB(&I);
1478 VAStartInstrumentationList.push_back(&I);
1479 Value *VAListTag = I.getArgOperand(0);
1480 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1482 // Unpoison the whole __va_list_tag.
1483 // FIXME: magic ABI constants.
1484 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1485 /* size */24, /* alignment */16, false);
1488 void visitVACopyInst(VACopyInst &I) {
1489 IRBuilder<> IRB(&I);
1490 Value *VAListTag = I.getArgOperand(0);
1491 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1493 // Unpoison the whole __va_list_tag.
1494 // FIXME: magic ABI constants.
1495 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1496 /* size */ 24, /* alignment */ 16, false);
1499 void finalizeInstrumentation() {
1500 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
1501 "finalizeInstrumentation called twice");
1502 if (!VAStartInstrumentationList.empty()) {
1503 // If there is a va_start in this function, make a backup copy of
1504 // va_arg_tls somewhere in the function entry block.
1505 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1506 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
1508 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
1510 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
1511 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
1514 // Instrument va_start.
1515 // Copy va_list shadow from the backup copy of the TLS contents.
1516 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
1517 CallInst *OrigInst = VAStartInstrumentationList[i];
1518 IRBuilder<> IRB(OrigInst->getNextNode());
1519 Value *VAListTag = OrigInst->getArgOperand(0);
1521 Value *RegSaveAreaPtrPtr =
1523 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1524 ConstantInt::get(MS.IntptrTy, 16)),
1525 Type::getInt64PtrTy(*MS.C));
1526 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
1527 Value *RegSaveAreaShadowPtr =
1528 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
1529 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
1530 AMD64FpEndOffset, 16);
1532 Value *OverflowArgAreaPtrPtr =
1534 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1535 ConstantInt::get(MS.IntptrTy, 8)),
1536 Type::getInt64PtrTy(*MS.C));
1537 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
1538 Value *OverflowArgAreaShadowPtr =
1539 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
1541 getShadowPtrForVAArgument(VAArgTLSCopy, IRB, AMD64FpEndOffset);
1542 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
1547 VarArgHelper* CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
1548 MemorySanitizerVisitor &Visitor) {
1549 return new VarArgAMD64Helper(Func, Msan, Visitor);
1554 bool MemorySanitizer::runOnFunction(Function &F) {
1555 MemorySanitizerVisitor Visitor(F, *this);
1557 // Clear out readonly/readnone attributes.
1559 B.addAttribute(Attributes::ReadOnly)
1560 .addAttribute(Attributes::ReadNone);
1561 F.removeAttribute(AttrListPtr::FunctionIndex,
1562 Attributes::get(F.getContext(), B));
1564 return Visitor.runOnFunction();