blob: bc9e709fd47b3868c5d699d7c0c51ba1d0b109a4 [file] [log] [blame]
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001//===-- MemorySanitizer.cpp - detector of uninitialized reads -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This file is a part of MemorySanitizer, a detector of uninitialized
11/// reads.
12///
13/// Status: early prototype.
14///
15/// The algorithm of the tool is similar to Memcheck
16/// (http://goo.gl/QKbem). We associate a few shadow bits with every
17/// byte of the application memory, poison the shadow of the malloc-ed
18/// or alloca-ed memory, load the shadow bits on every memory read,
19/// propagate the shadow bits through some of the arithmetic
20/// instruction (including MOV), store the shadow bits on every memory
21/// write, report a bug on some other instructions (e.g. JMP) if the
22/// associated shadow is poisoned.
23///
24/// But there are differences too. The first and the major one:
25/// compiler instrumentation instead of binary instrumentation. This
26/// gives us much better register allocation, possible compiler
27/// optimizations and a fast start-up. But this brings the major issue
28/// as well: msan needs to see all program events, including system
29/// calls and reads/writes in system libraries, so we either need to
30/// compile *everything* with msan or use a binary translation
31/// component (e.g. DynamoRIO) to instrument pre-built libraries.
32/// Another difference from Memcheck is that we use 8 shadow bits per
33/// byte of application memory and use a direct shadow mapping. This
34/// greatly simplifies the instrumentation code and avoids races on
35/// shadow updates (Memcheck is single-threaded so races are not a
36/// concern there. Memcheck uses 2 shadow bits per byte with a slow
37/// path storage that uses 8 bits per byte).
38///
39/// The default value of shadow is 0, which means "clean" (not poisoned).
40///
41/// Every module initializer should call __msan_init to ensure that the
42/// shadow memory is ready. On error, __msan_warning is called. Since
43/// parameters and return values may be passed via registers, we have a
44/// specialized thread-local shadow for return values
45/// (__msan_retval_tls) and parameters (__msan_param_tls).
46//===----------------------------------------------------------------------===//
47
48#define DEBUG_TYPE "msan"
49
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"
75
76using namespace llvm;
77
78static const uint64_t kShadowMask32 = 1ULL << 31;
79static const uint64_t kShadowMask64 = 1ULL << 46;
80static const uint64_t kOriginOffset32 = 1ULL << 30;
81static const uint64_t kOriginOffset64 = 1ULL << 45;
82
83// This is an important flag that makes the reports much more
84// informative at the cost of greater slowdown. Not fully implemented
85// yet.
86// FIXME: this should be a top-level clang flag, e.g.
87// -fmemory-sanitizer-full.
88static cl::opt<bool> ClTrackOrigins("msan-track-origins",
89 cl::desc("Track origins (allocation sites) of poisoned memory"),
90 cl::Hidden, cl::init(false));
91static cl::opt<bool> ClKeepGoing("msan-keep-going",
92 cl::desc("keep going after reporting a UMR"),
93 cl::Hidden, cl::init(false));
94static cl::opt<bool> ClPoisonStack("msan-poison-stack",
95 cl::desc("poison uninitialized stack variables"),
96 cl::Hidden, cl::init(true));
97static 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));
100static 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));
103
104static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
105 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
106 cl::Hidden, cl::init(true));
107
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.
114static 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));
117
118static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
119 cl::desc("print out instructions with default strict semantics"),
120 cl::Hidden, cl::init(false));
121
122static 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);
125
126namespace {
127
128/// \brief An instrumentation pass implementing detection of uninitialized
129/// reads.
130///
131/// MemorySanitizer: instrument the code in module to find
132/// uninitialized reads.
133class MemorySanitizer : public FunctionPass {
134public:
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.
140
141private:
142 DataLayout *TD;
143 LLVMContext *C;
144 Type *IntptrTy;
145 Type *OriginTy;
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
161 /// function.
162 GlobalVariable *OriginTLS;
163
164 /// \brief The run-time callback to print a warning.
165 Value *WarningFn;
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
169 /// allocation.
170 Value *MsanSetAllocaOriginFn;
171 /// \brief Run-time helper that poisons stack on function entry.
172 Value *MsanPoisonStackFn;
173 /// \brief The actual "memmove" function.
174 Value *MemmoveFn;
175
176 /// \brief Address mask used in application-to-shadow address calculation.
177 /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
178 uint64_t 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;
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000186 /// \brief An empty volatile inline asm that prevents callback merge.
187 InlineAsm *EmptyAsm;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000188
189 friend class MemorySanitizerVisitor;
190 friend class VarArgAMD64Helper;
191};
192} // namespace
193
194char MemorySanitizer::ID = 0;
195INITIALIZE_PASS(MemorySanitizer, "msan",
196 "MemorySanitizer: detects uninitialized reads.",
197 false, false)
198
199FunctionPass *llvm::createMemorySanitizerPass() {
200 return new MemorySanitizer();
201}
202
203/// \brief Create a non-const global initialized with the given string.
204///
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.
208static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
209 StringRef Str) {
210 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
211 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
212 GlobalValue::PrivateLinkage, StrConst, "");
213}
214
215/// \brief Module-level initialization.
216///
217/// Obtains pointers to the required runtime library functions, and
218/// inserts a call to __msan_init to the module's constructor list.
219bool MemorySanitizer::doInitialization(Module &M) {
220 TD = getAnalysisIfAvailable<DataLayout>();
221 if (!TD)
222 return false;
223 BL.reset(new BlackList(ClBlackListFile));
224 C = &(M.getContext());
225 unsigned PtrSize = TD->getPointerSizeInBits(/* AddressSpace */0);
226 switch (PtrSize) {
227 case 64:
228 ShadowMask = kShadowMask64;
229 OriginOffset = kOriginOffset64;
230 break;
231 case 32:
232 ShadowMask = kShadowMask32;
233 OriginOffset = kOriginOffset32;
234 break;
235 default:
236 report_fatal_error("unsupported pointer size");
237 break;
238 }
239
240 IRBuilder<> IRB(*C);
241 IntptrTy = IRB.getIntPtrTy(TD);
242 OriginTy = IRB.getInt32Ty();
243
244 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
245
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);
249
250 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::LinkOnceODRLinkage,
251 IRB.getInt32(ClTrackOrigins), "__msan_track_origins");
252
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);
259
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 "memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
270 IntptrTy, NULL);
271
272 // Create globals.
273 RetvalTLS = new GlobalVariable(
274 M, ArrayType::get(IRB.getInt64Ty(), 8), false,
275 GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0,
276 GlobalVariable::GeneralDynamicTLSModel);
277 RetvalOriginTLS = new GlobalVariable(
278 M, OriginTy, false, GlobalVariable::ExternalLinkage, 0,
279 "__msan_retval_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
280
281 ParamTLS = new GlobalVariable(
282 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
283 GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0,
284 GlobalVariable::GeneralDynamicTLSModel);
285 ParamOriginTLS = new GlobalVariable(
286 M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage,
287 0, "__msan_param_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
288
289 VAArgTLS = new GlobalVariable(
290 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
291 GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0,
292 GlobalVariable::GeneralDynamicTLSModel);
293 VAArgOverflowSizeTLS = new GlobalVariable(
294 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0,
295 "__msan_va_arg_overflow_size_tls", 0,
296 GlobalVariable::GeneralDynamicTLSModel);
297 OriginTLS = new GlobalVariable(
298 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0,
299 "__msan_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000300
301 // We insert an empty inline asm after __msan_report* to avoid callback merge.
302 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
303 StringRef(""), StringRef(""),
304 /*hasSideEffects=*/true);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000305 return true;
306}
307
308namespace {
309
310/// \brief A helper class that handles instrumentation of VarArg
311/// functions on a particular platform.
312///
313/// Implementations are expected to insert the instrumentation
314/// necessary to propagate argument shadow through VarArg function
315/// calls. Visit* methods are called during an InstVisitor pass over
316/// the function, and should avoid creating new basic blocks. A new
317/// instance of this class is created for each instrumented function.
318struct VarArgHelper {
319 /// \brief Visit a CallSite.
320 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
321
322 /// \brief Visit a va_start call.
323 virtual void visitVAStartInst(VAStartInst &I) = 0;
324
325 /// \brief Visit a va_copy call.
326 virtual void visitVACopyInst(VACopyInst &I) = 0;
327
328 /// \brief Finalize function instrumentation.
329 ///
330 /// This method is called after visiting all interesting (see above)
331 /// instructions in a function.
332 virtual void finalizeInstrumentation() = 0;
333};
334
335struct MemorySanitizerVisitor;
336
337VarArgHelper*
338CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
339 MemorySanitizerVisitor &Visitor);
340
341/// This class does all the work for a given function. Store and Load
342/// instructions store and load corresponding shadow and origin
343/// values. Most instructions propagate shadow from arguments to their
344/// return values. Certain instructions (most importantly, BranchInst)
345/// test their argument shadow and print reports (with a runtime call) if it's
346/// non-zero.
347struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
348 Function &F;
349 MemorySanitizer &MS;
350 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
351 ValueMap<Value*, Value*> ShadowMap, OriginMap;
352 bool InsertChecks;
353 OwningPtr<VarArgHelper> VAHelper;
354
355 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
356 // See a comment in visitCallSite for more details.
357 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
358 static const unsigned AMD64FpEndOffset = 176;
359
360 struct ShadowOriginAndInsertPoint {
361 Instruction *Shadow;
362 Instruction *Origin;
363 Instruction *OrigIns;
364 ShadowOriginAndInsertPoint(Instruction *S, Instruction *O, Instruction *I)
365 : Shadow(S), Origin(O), OrigIns(I) { }
366 ShadowOriginAndInsertPoint() : Shadow(0), Origin(0), OrigIns(0) { }
367 };
368 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
369
370 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
371 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
372 InsertChecks = !MS.BL->isIn(F);
373 DEBUG(if (!InsertChecks)
374 dbgs() << "MemorySanitizer is not inserting checks into '"
375 << F.getName() << "'\n");
376 }
377
378 void materializeChecks() {
379 for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) {
380 Instruction *Shadow = InstrumentationList[i].Shadow;
381 Instruction *OrigIns = InstrumentationList[i].OrigIns;
382 IRBuilder<> IRB(OrigIns);
383 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
384 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
385 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
386 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
387 getCleanShadow(ConvertedShadow), "_mscmp");
388 Instruction *CheckTerm =
389 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp),
390 /* Unreachable */ !ClKeepGoing,
391 MS.ColdCallWeights);
392
393 IRB.SetInsertPoint(CheckTerm);
394 if (ClTrackOrigins) {
395 Instruction *Origin = InstrumentationList[i].Origin;
396 IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0),
397 MS.OriginTLS);
398 }
399 CallInst *Call = IRB.CreateCall(MS.WarningFn);
400 Call->setDebugLoc(OrigIns->getDebugLoc());
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000401 IRB.CreateCall(MS.EmptyAsm);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000402 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
403 }
404 DEBUG(dbgs() << "DONE:\n" << F);
405 }
406
407 /// \brief Add MemorySanitizer instrumentation to a function.
408 bool runOnFunction() {
409 if (!MS.TD) return false;
410 // Iterate all BBs in depth-first order and create shadow instructions
411 // for all instructions (where applicable).
412 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
413 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
414 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
415 BasicBlock *BB = *DI;
416 visit(*BB);
417 }
418
419 // Finalize PHI nodes.
420 for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) {
421 PHINode *PN = ShadowPHINodes[i];
422 PHINode *PNS = cast<PHINode>(getShadow(PN));
423 PHINode *PNO = ClTrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0;
424 size_t NumValues = PN->getNumIncomingValues();
425 for (size_t v = 0; v < NumValues; v++) {
426 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
427 if (PNO)
428 PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
429 }
430 }
431
432 VAHelper->finalizeInstrumentation();
433
434 materializeChecks();
435
436 return true;
437 }
438
439 /// \brief Compute the shadow type that corresponds to a given Value.
440 Type *getShadowTy(Value *V) {
441 return getShadowTy(V->getType());
442 }
443
444 /// \brief Compute the shadow type that corresponds to a given Type.
445 Type *getShadowTy(Type *OrigTy) {
446 if (!OrigTy->isSized()) {
447 return 0;
448 }
449 // For integer type, shadow is the same as the original type.
450 // This may return weird-sized types like i1.
451 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
452 return IT;
453 if (VectorType *VT = dyn_cast<VectorType>(OrigTy))
454 return VectorType::getInteger(VT);
455 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
456 SmallVector<Type*, 4> Elements;
457 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
458 Elements.push_back(getShadowTy(ST->getElementType(i)));
459 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
460 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
461 return Res;
462 }
463 uint32_t TypeSize = MS.TD->getTypeStoreSizeInBits(OrigTy);
464 return IntegerType::get(*MS.C, TypeSize);
465 }
466
467 /// \brief Flatten a vector type.
468 Type *getShadowTyNoVec(Type *ty) {
469 if (VectorType *vt = dyn_cast<VectorType>(ty))
470 return IntegerType::get(*MS.C, vt->getBitWidth());
471 return ty;
472 }
473
474 /// \brief Convert a shadow value to it's flattened variant.
475 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
476 Type *Ty = V->getType();
477 Type *NoVecTy = getShadowTyNoVec(Ty);
478 if (Ty == NoVecTy) return V;
479 return IRB.CreateBitCast(V, NoVecTy);
480 }
481
482 /// \brief Compute the shadow address that corresponds to a given application
483 /// address.
484 ///
485 /// Shadow = Addr & ~ShadowMask.
486 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
487 IRBuilder<> &IRB) {
488 Value *ShadowLong =
489 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
490 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
491 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
492 }
493
494 /// \brief Compute the origin address that corresponds to a given application
495 /// address.
496 ///
497 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
498 /// = Addr & (~ShadowMask & ~3ULL) + OriginOffset
499 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
500 Value *ShadowLong =
501 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
502 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask & ~3ULL));
503 Value *Add =
504 IRB.CreateAdd(ShadowLong,
505 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
506 return IRB.CreateIntToPtr(Add, PointerType::get(IRB.getInt32Ty(), 0));
507 }
508
509 /// \brief Compute the shadow address for a given function argument.
510 ///
511 /// Shadow = ParamTLS+ArgOffset.
512 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
513 int ArgOffset) {
514 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
515 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
516 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
517 "_msarg");
518 }
519
520 /// \brief Compute the origin address for a given function argument.
521 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
522 int ArgOffset) {
523 if (!ClTrackOrigins) return 0;
524 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
525 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
526 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
527 "_msarg_o");
528 }
529
530 /// \brief Compute the shadow address for a retval.
531 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
532 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
533 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
534 "_msret");
535 }
536
537 /// \brief Compute the origin address for a retval.
538 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
539 // We keep a single origin for the entire retval. Might be too optimistic.
540 return MS.RetvalOriginTLS;
541 }
542
543 /// \brief Set SV to be the shadow value for V.
544 void setShadow(Value *V, Value *SV) {
545 assert(!ShadowMap.count(V) && "Values may only have one shadow");
546 ShadowMap[V] = SV;
547 }
548
549 /// \brief Set Origin to be the origin value for V.
550 void setOrigin(Value *V, Value *Origin) {
551 if (!ClTrackOrigins) return;
552 assert(!OriginMap.count(V) && "Values may only have one origin");
553 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
554 OriginMap[V] = Origin;
555 }
556
557 /// \brief Create a clean shadow value for a given value.
558 ///
559 /// Clean shadow (all zeroes) means all bits of the value are defined
560 /// (initialized).
561 Value *getCleanShadow(Value *V) {
562 Type *ShadowTy = getShadowTy(V);
563 if (!ShadowTy)
564 return 0;
565 return Constant::getNullValue(ShadowTy);
566 }
567
568 /// \brief Create a dirty shadow of a given shadow type.
569 Constant *getPoisonedShadow(Type *ShadowTy) {
570 assert(ShadowTy);
571 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
572 return Constant::getAllOnesValue(ShadowTy);
573 StructType *ST = cast<StructType>(ShadowTy);
574 SmallVector<Constant *, 4> Vals;
575 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
576 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
577 return ConstantStruct::get(ST, Vals);
578 }
579
580 /// \brief Create a clean (zero) origin.
581 Value *getCleanOrigin() {
582 return Constant::getNullValue(MS.OriginTy);
583 }
584
585 /// \brief Get the shadow value for a given Value.
586 ///
587 /// This function either returns the value set earlier with setShadow,
588 /// or extracts if from ParamTLS (for function arguments).
589 Value *getShadow(Value *V) {
590 if (Instruction *I = dyn_cast<Instruction>(V)) {
591 // For instructions the shadow is already stored in the map.
592 Value *Shadow = ShadowMap[V];
593 if (!Shadow) {
594 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
595 assert(Shadow && "No shadow for a value");
596 }
597 return Shadow;
598 }
599 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
600 Value *AllOnes = getPoisonedShadow(getShadowTy(V));
601 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
602 return AllOnes;
603 }
604 if (Argument *A = dyn_cast<Argument>(V)) {
605 // For arguments we compute the shadow on demand and store it in the map.
606 Value **ShadowPtr = &ShadowMap[V];
607 if (*ShadowPtr)
608 return *ShadowPtr;
609 Function *F = A->getParent();
610 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
611 unsigned ArgOffset = 0;
612 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
613 AI != AE; ++AI) {
614 if (!AI->getType()->isSized()) {
615 DEBUG(dbgs() << "Arg is not sized\n");
616 continue;
617 }
618 unsigned Size = AI->hasByValAttr()
619 ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
620 : MS.TD->getTypeAllocSize(AI->getType());
621 if (A == AI) {
622 Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
623 if (AI->hasByValAttr()) {
624 // ByVal pointer itself has clean shadow. We copy the actual
625 // argument shadow to the underlying memory.
626 Value *Cpy = EntryIRB.CreateMemCpy(
627 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
628 Base, Size, AI->getParamAlignment());
629 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
630 *ShadowPtr = getCleanShadow(V);
631 } else {
632 *ShadowPtr = EntryIRB.CreateLoad(Base);
633 }
634 DEBUG(dbgs() << " ARG: " << *AI << " ==> " <<
635 **ShadowPtr << "\n");
636 if (ClTrackOrigins) {
637 Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
638 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
639 }
640 }
641 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
642 }
643 assert(*ShadowPtr && "Could not find shadow for an argument");
644 return *ShadowPtr;
645 }
646 // For everything else the shadow is zero.
647 return getCleanShadow(V);
648 }
649
650 /// \brief Get the shadow for i-th argument of the instruction I.
651 Value *getShadow(Instruction *I, int i) {
652 return getShadow(I->getOperand(i));
653 }
654
655 /// \brief Get the origin for a value.
656 Value *getOrigin(Value *V) {
657 if (!ClTrackOrigins) return 0;
658 if (isa<Instruction>(V) || isa<Argument>(V)) {
659 Value *Origin = OriginMap[V];
660 if (!Origin) {
661 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
662 Origin = getCleanOrigin();
663 }
664 return Origin;
665 }
666 return getCleanOrigin();
667 }
668
669 /// \brief Get the origin for i-th argument of the instruction I.
670 Value *getOrigin(Instruction *I, int i) {
671 return getOrigin(I->getOperand(i));
672 }
673
674 /// \brief Remember the place where a shadow check should be inserted.
675 ///
676 /// This location will be later instrumented with a check that will print a
677 /// UMR warning in runtime if the value is not fully defined.
678 void insertCheck(Value *Val, Instruction *OrigIns) {
679 assert(Val);
680 if (!InsertChecks) return;
681 Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
682 if (!Shadow) return;
683 Type *ShadowTy = Shadow->getType();
684 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
685 "Can only insert checks for integer and vector shadow types");
686 Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
687 InstrumentationList.push_back(
688 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
689 }
690
691 //------------------- Visitors.
692
693 /// \brief Instrument LoadInst
694 ///
695 /// Loads the corresponding shadow and (optionally) origin.
696 /// Optionally, checks that the load address is fully defined.
697 void visitLoadInst(LoadInst &I) {
698 Type *LoadTy = I.getType();
699 assert(LoadTy->isSized() && "Load type must have size");
700 IRBuilder<> IRB(&I);
701 Type *ShadowTy = getShadowTy(&I);
702 Value *Addr = I.getPointerOperand();
703 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
704 setShadow(&I, IRB.CreateLoad(ShadowPtr, "_msld"));
705
706 if (ClCheckAccessAddress)
707 insertCheck(I.getPointerOperand(), &I);
708
709 if (ClTrackOrigins)
710 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
711 }
712
713 /// \brief Instrument StoreInst
714 ///
715 /// Stores the corresponding shadow and (optionally) origin.
716 /// Optionally, checks that the store address is fully defined.
717 /// Volatile stores check that the value being stored is fully defined.
718 void visitStoreInst(StoreInst &I) {
719 IRBuilder<> IRB(&I);
720 Value *Val = I.getValueOperand();
721 Value *Addr = I.getPointerOperand();
722 Value *Shadow = getShadow(Val);
723 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
724
725 StoreInst *NewSI = IRB.CreateStore(Shadow, ShadowPtr);
726 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
727 // If the store is volatile, add a check.
728 if (I.isVolatile())
729 insertCheck(Val, &I);
730 if (ClCheckAccessAddress)
731 insertCheck(Addr, &I);
732
733 if (ClTrackOrigins)
734 IRB.CreateStore(getOrigin(Val), getOriginPtr(Addr, IRB));
735 }
736
737 // Casts.
738 void visitSExtInst(SExtInst &I) {
739 IRBuilder<> IRB(&I);
740 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
741 setOrigin(&I, getOrigin(&I, 0));
742 }
743
744 void visitZExtInst(ZExtInst &I) {
745 IRBuilder<> IRB(&I);
746 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
747 setOrigin(&I, getOrigin(&I, 0));
748 }
749
750 void visitTruncInst(TruncInst &I) {
751 IRBuilder<> IRB(&I);
752 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
753 setOrigin(&I, getOrigin(&I, 0));
754 }
755
756 void visitBitCastInst(BitCastInst &I) {
757 IRBuilder<> IRB(&I);
758 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
759 setOrigin(&I, getOrigin(&I, 0));
760 }
761
762 void visitPtrToIntInst(PtrToIntInst &I) {
763 IRBuilder<> IRB(&I);
764 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
765 "_msprop_ptrtoint"));
766 setOrigin(&I, getOrigin(&I, 0));
767 }
768
769 void visitIntToPtrInst(IntToPtrInst &I) {
770 IRBuilder<> IRB(&I);
771 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
772 "_msprop_inttoptr"));
773 setOrigin(&I, getOrigin(&I, 0));
774 }
775
776 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
777 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
778 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
779 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
780 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
781 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
782
783 /// \brief Propagate shadow for bitwise AND.
784 ///
785 /// This code is exact, i.e. if, for example, a bit in the left argument
786 /// is defined and 0, then neither the value not definedness of the
787 /// corresponding bit in B don't affect the resulting shadow.
788 void visitAnd(BinaryOperator &I) {
789 IRBuilder<> IRB(&I);
790 // "And" of 0 and a poisoned value results in unpoisoned value.
791 // 1&1 => 1; 0&1 => 0; p&1 => p;
792 // 1&0 => 0; 0&0 => 0; p&0 => 0;
793 // 1&p => p; 0&p => 0; p&p => p;
794 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
795 Value *S1 = getShadow(&I, 0);
796 Value *S2 = getShadow(&I, 1);
797 Value *V1 = I.getOperand(0);
798 Value *V2 = I.getOperand(1);
799 if (V1->getType() != S1->getType()) {
800 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
801 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
802 }
803 Value *S1S2 = IRB.CreateAnd(S1, S2);
804 Value *V1S2 = IRB.CreateAnd(V1, S2);
805 Value *S1V2 = IRB.CreateAnd(S1, V2);
806 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
807 setOriginForNaryOp(I);
808 }
809
810 void visitOr(BinaryOperator &I) {
811 IRBuilder<> IRB(&I);
812 // "Or" of 1 and a poisoned value results in unpoisoned value.
813 // 1|1 => 1; 0|1 => 1; p|1 => 1;
814 // 1|0 => 1; 0|0 => 0; p|0 => p;
815 // 1|p => 1; 0|p => p; p|p => p;
816 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
817 Value *S1 = getShadow(&I, 0);
818 Value *S2 = getShadow(&I, 1);
819 Value *V1 = IRB.CreateNot(I.getOperand(0));
820 Value *V2 = IRB.CreateNot(I.getOperand(1));
821 if (V1->getType() != S1->getType()) {
822 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
823 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
824 }
825 Value *S1S2 = IRB.CreateAnd(S1, S2);
826 Value *V1S2 = IRB.CreateAnd(V1, S2);
827 Value *S1V2 = IRB.CreateAnd(S1, V2);
828 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
829 setOriginForNaryOp(I);
830 }
831
832 /// \brief Propagate origin for an instruction.
833 ///
834 /// This is a general case of origin propagation. For an Nary operation,
835 /// is set to the origin of an argument that is not entirely initialized.
836 /// It does not matter which one is picked if all arguments are initialized.
837 void setOriginForNaryOp(Instruction &I) {
838 if (!ClTrackOrigins) return;
839 IRBuilder<> IRB(&I);
840 Value *Origin = getOrigin(&I, 0);
841 for (unsigned Op = 1, n = I.getNumOperands(); Op < n; ++Op) {
842 Value *S = convertToShadowTyNoVec(getShadow(&I, Op - 1), IRB);
843 Origin = IRB.CreateSelect(IRB.CreateICmpNE(S, getCleanShadow(S)),
844 Origin, getOrigin(&I, Op));
845 }
846 setOrigin(&I, Origin);
847 }
848
849 /// \brief Propagate shadow for a binary operation.
850 ///
851 /// Shadow = Shadow0 | Shadow1, all 3 must have the same type.
852 /// Bitwise OR is selected as an operation that will never lose even a bit of
853 /// poison.
854 void handleShadowOrBinary(Instruction &I) {
855 IRBuilder<> IRB(&I);
856 Value *Shadow0 = getShadow(&I, 0);
857 Value *Shadow1 = getShadow(&I, 1);
858 setShadow(&I, IRB.CreateOr(Shadow0, Shadow1, "_msprop"));
859 setOriginForNaryOp(I);
860 }
861
862 /// \brief Propagate shadow for arbitrary operation.
863 ///
864 /// This is a general case of shadow propagation, used in all cases where we
865 /// don't know and/or care about what the operation actually does.
866 /// It converts all input shadow values to a common type (extending or
867 /// truncating as necessary), and bitwise OR's them.
868 ///
869 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
870 /// fully initialized), and less prone to false positives.
871 // FIXME: is the casting actually correct?
872 // FIXME: merge this with handleShadowOrBinary.
873 void handleShadowOr(Instruction &I) {
874 IRBuilder<> IRB(&I);
875 Value *Shadow = getShadow(&I, 0);
876 for (unsigned Op = 1, n = I.getNumOperands(); Op < n; ++Op)
877 Shadow = IRB.CreateOr(
878 Shadow, IRB.CreateIntCast(getShadow(&I, Op), Shadow->getType(), false),
879 "_msprop");
880 Shadow = IRB.CreateIntCast(Shadow, getShadowTy(&I), false);
881 setShadow(&I, Shadow);
882 setOriginForNaryOp(I);
883 }
884
885 void visitFAdd(BinaryOperator &I) { handleShadowOrBinary(I); }
886 void visitFSub(BinaryOperator &I) { handleShadowOrBinary(I); }
887 void visitFMul(BinaryOperator &I) { handleShadowOrBinary(I); }
888 void visitAdd(BinaryOperator &I) { handleShadowOrBinary(I); }
889 void visitSub(BinaryOperator &I) { handleShadowOrBinary(I); }
890 void visitXor(BinaryOperator &I) { handleShadowOrBinary(I); }
891 void visitMul(BinaryOperator &I) { handleShadowOrBinary(I); }
892
893 void handleDiv(Instruction &I) {
894 IRBuilder<> IRB(&I);
895 // Strict on the second argument.
896 insertCheck(I.getOperand(1), &I);
897 setShadow(&I, getShadow(&I, 0));
898 setOrigin(&I, getOrigin(&I, 0));
899 }
900
901 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
902 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
903 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
904 void visitURem(BinaryOperator &I) { handleDiv(I); }
905 void visitSRem(BinaryOperator &I) { handleDiv(I); }
906 void visitFRem(BinaryOperator &I) { handleDiv(I); }
907
908 /// \brief Instrument == and != comparisons.
909 ///
910 /// Sometimes the comparison result is known even if some of the bits of the
911 /// arguments are not.
912 void handleEqualityComparison(ICmpInst &I) {
913 IRBuilder<> IRB(&I);
914 Value *A = I.getOperand(0);
915 Value *B = I.getOperand(1);
916 Value *Sa = getShadow(A);
917 Value *Sb = getShadow(B);
918 if (A->getType()->isPointerTy())
919 A = IRB.CreatePointerCast(A, MS.IntptrTy);
920 if (B->getType()->isPointerTy())
921 B = IRB.CreatePointerCast(B, MS.IntptrTy);
922 // A == B <==> (C = A^B) == 0
923 // A != B <==> (C = A^B) != 0
924 // Sc = Sa | Sb
925 Value *C = IRB.CreateXor(A, B);
926 Value *Sc = IRB.CreateOr(Sa, Sb);
927 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
928 // Result is defined if one of the following is true
929 // * there is a defined 1 bit in C
930 // * C is fully defined
931 // Si = !(C & ~Sc) && Sc
932 Value *Zero = Constant::getNullValue(Sc->getType());
933 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
934 Value *Si =
935 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
936 IRB.CreateICmpEQ(
937 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
938 Si->setName("_msprop_icmp");
939 setShadow(&I, Si);
940 setOriginForNaryOp(I);
941 }
942
943 void visitICmpInst(ICmpInst &I) {
944 if (ClHandleICmp && I.isEquality())
945 handleEqualityComparison(I);
946 else
947 handleShadowOr(I);
948 }
949
950 void visitFCmpInst(FCmpInst &I) {
951 handleShadowOr(I);
952 }
953
954 void handleShift(BinaryOperator &I) {
955 IRBuilder<> IRB(&I);
956 // If any of the S2 bits are poisoned, the whole thing is poisoned.
957 // Otherwise perform the same shift on S1.
958 Value *S1 = getShadow(&I, 0);
959 Value *S2 = getShadow(&I, 1);
960 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
961 S2->getType());
962 Value *V2 = I.getOperand(1);
963 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
964 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
965 setOriginForNaryOp(I);
966 }
967
968 void visitShl(BinaryOperator &I) { handleShift(I); }
969 void visitAShr(BinaryOperator &I) { handleShift(I); }
970 void visitLShr(BinaryOperator &I) { handleShift(I); }
971
972 void visitMemSetInst(MemSetInst &I) {
973 IRBuilder<> IRB(&I);
974 Value *Ptr = I.getArgOperand(0);
975 Value *Val = I.getArgOperand(1);
976 Value *ShadowPtr = getShadowPtr(Ptr, Val->getType(), IRB);
977 Value *ShadowVal = getCleanShadow(Val);
978 Value *Size = I.getArgOperand(2);
979 unsigned Align = I.getAlignment();
980 bool isVolatile = I.isVolatile();
981
982 IRB.CreateMemSet(ShadowPtr, ShadowVal, Size, Align, isVolatile);
983 }
984
985 void visitMemCpyInst(MemCpyInst &I) {
986 IRBuilder<> IRB(&I);
987 Value *Dst = I.getArgOperand(0);
988 Value *Src = I.getArgOperand(1);
989 Type *ElementType = dyn_cast<PointerType>(Dst->getType())->getElementType();
990 Value *ShadowDst = getShadowPtr(Dst, ElementType, IRB);
991 Value *ShadowSrc = getShadowPtr(Src, ElementType, IRB);
992 Value *Size = I.getArgOperand(2);
993 unsigned Align = I.getAlignment();
994 bool isVolatile = I.isVolatile();
995
996 IRB.CreateMemCpy(ShadowDst, ShadowSrc, Size, Align, isVolatile);
997 if (ClTrackOrigins)
998 IRB.CreateCall3(MS.MsanCopyOriginFn, Dst, Src, Size);
999 }
1000
1001 /// \brief Instrument llvm.memmove
1002 ///
1003 /// At this point we don't know if llvm.memmove will be inlined or not.
1004 /// If we don't instrument it and it gets inlined,
1005 /// our interceptor will not kick in and we will lose the memmove.
1006 /// If we instrument the call here, but it does not get inlined,
1007 /// we will memove the shadow twice: which is bad in case
1008 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1009 ///
1010 /// Similar situation exists for memcpy and memset, but for those functions
1011 /// calling instrumentation twice does not lead to incorrect results.
1012 void visitMemMoveInst(MemMoveInst &I) {
1013 IRBuilder<> IRB(&I);
1014 IRB.CreateCall3(
1015 MS.MemmoveFn,
1016 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1017 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1018 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1019 I.eraseFromParent();
1020 }
1021
1022 void visitVAStartInst(VAStartInst &I) {
1023 VAHelper->visitVAStartInst(I);
1024 }
1025
1026 void visitVACopyInst(VACopyInst &I) {
1027 VAHelper->visitVACopyInst(I);
1028 }
1029
1030 void visitCallSite(CallSite CS) {
1031 Instruction &I = *CS.getInstruction();
1032 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1033 if (CS.isCall()) {
1034 // Allow only tail calls with the same types, otherwise
1035 // we may have a false positive: shadow for a non-void RetVal
1036 // will get propagated to a void RetVal.
1037 CallInst *Call = cast<CallInst>(&I);
1038 if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1039 Call->setTailCall(false);
1040 if (isa<IntrinsicInst>(&I)) {
1041 // All intrinsics we care about are handled in corresponding visit*
1042 // methods. Add checks for the arguments, mark retval as clean.
1043 visitInstruction(I);
1044 return;
1045 }
1046 }
1047 IRBuilder<> IRB(&I);
1048 unsigned ArgOffset = 0;
1049 DEBUG(dbgs() << " CallSite: " << I << "\n");
1050 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1051 ArgIt != End; ++ArgIt) {
1052 Value *A = *ArgIt;
1053 unsigned i = ArgIt - CS.arg_begin();
1054 if (!A->getType()->isSized()) {
1055 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1056 continue;
1057 }
1058 unsigned Size = 0;
1059 Value *Store = 0;
1060 // Compute the Shadow for arg even if it is ByVal, because
1061 // in that case getShadow() will copy the actual arg shadow to
1062 // __msan_param_tls.
1063 Value *ArgShadow = getShadow(A);
1064 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1065 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
1066 " Shadow: " << *ArgShadow << "\n");
1067 if (CS.paramHasAttr(i + 1, Attributes::ByVal)) {
1068 assert(A->getType()->isPointerTy() &&
1069 "ByVal argument is not a pointer!");
1070 Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1071 unsigned Alignment = CS.getParamAlignment(i + 1);
1072 Store = IRB.CreateMemCpy(ArgShadowBase,
1073 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1074 Size, Alignment);
1075 } else {
1076 Size = MS.TD->getTypeAllocSize(A->getType());
1077 Store = IRB.CreateStore(ArgShadow, ArgShadowBase);
1078 }
1079 if (ClTrackOrigins)
1080 IRB.CreateStore(getOrigin(A),
1081 getOriginPtrForArgument(A, IRB, ArgOffset));
1082 assert(Size != 0 && Store != 0);
1083 DEBUG(dbgs() << " Param:" << *Store << "\n");
1084 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1085 }
1086 DEBUG(dbgs() << " done with call args\n");
1087
1088 FunctionType *FT =
1089 cast<FunctionType>(CS.getCalledValue()->getType()-> getContainedType(0));
1090 if (FT->isVarArg()) {
1091 VAHelper->visitCallSite(CS, IRB);
1092 }
1093
1094 // Now, get the shadow for the RetVal.
1095 if (!I.getType()->isSized()) return;
1096 IRBuilder<> IRBBefore(&I);
1097 // Untill we have full dynamic coverage, make sure the retval shadow is 0.
1098 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
1099 IRBBefore.CreateStore(getCleanShadow(&I), Base);
1100 Instruction *NextInsn = 0;
1101 if (CS.isCall()) {
1102 NextInsn = I.getNextNode();
1103 } else {
1104 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1105 if (!NormalDest->getSinglePredecessor()) {
1106 // FIXME: this case is tricky, so we are just conservative here.
1107 // Perhaps we need to split the edge between this BB and NormalDest,
1108 // but a naive attempt to use SplitEdge leads to a crash.
1109 setShadow(&I, getCleanShadow(&I));
1110 setOrigin(&I, getCleanOrigin());
1111 return;
1112 }
1113 NextInsn = NormalDest->getFirstInsertionPt();
1114 assert(NextInsn &&
1115 "Could not find insertion point for retval shadow load");
1116 }
1117 IRBuilder<> IRBAfter(NextInsn);
1118 setShadow(&I, IRBAfter.CreateLoad(getShadowPtrForRetval(&I, IRBAfter),
1119 "_msret"));
1120 if (ClTrackOrigins)
1121 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1122 }
1123
1124 void visitReturnInst(ReturnInst &I) {
1125 IRBuilder<> IRB(&I);
1126 if (Value *RetVal = I.getReturnValue()) {
1127 // Set the shadow for the RetVal.
1128 Value *Shadow = getShadow(RetVal);
1129 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
1130 DEBUG(dbgs() << "Return: " << *Shadow << "\n" << *ShadowPtr << "\n");
1131 IRB.CreateStore(Shadow, ShadowPtr);
1132 if (ClTrackOrigins)
1133 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
1134 }
1135 }
1136
1137 void visitPHINode(PHINode &I) {
1138 IRBuilder<> IRB(&I);
1139 ShadowPHINodes.push_back(&I);
1140 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
1141 "_msphi_s"));
1142 if (ClTrackOrigins)
1143 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
1144 "_msphi_o"));
1145 }
1146
1147 void visitAllocaInst(AllocaInst &I) {
1148 setShadow(&I, getCleanShadow(&I));
1149 if (!ClPoisonStack) return;
1150 IRBuilder<> IRB(I.getNextNode());
1151 uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
1152 if (ClPoisonStackWithCall) {
1153 IRB.CreateCall2(MS.MsanPoisonStackFn,
1154 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1155 ConstantInt::get(MS.IntptrTy, Size));
1156 } else {
1157 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
1158 IRB.CreateMemSet(ShadowBase, IRB.getInt8(ClPoisonStackPattern),
1159 Size, I.getAlignment());
1160 }
1161
1162 if (ClTrackOrigins) {
1163 setOrigin(&I, getCleanOrigin());
1164 SmallString<2048> StackDescriptionStorage;
1165 raw_svector_ostream StackDescription(StackDescriptionStorage);
1166 // We create a string with a description of the stack allocation and
1167 // pass it into __msan_set_alloca_origin.
1168 // It will be printed by the run-time if stack-originated UMR is found.
1169 // The first 4 bytes of the string are set to '----' and will be replaced
1170 // by __msan_va_arg_overflow_size_tls at the first call.
1171 StackDescription << "----" << I.getName() << "@" << F.getName();
1172 Value *Descr =
1173 createPrivateNonConstGlobalForString(*F.getParent(),
1174 StackDescription.str());
1175 IRB.CreateCall3(MS.MsanSetAllocaOriginFn,
1176 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1177 ConstantInt::get(MS.IntptrTy, Size),
1178 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()));
1179 }
1180 }
1181
1182 void visitSelectInst(SelectInst& I) {
1183 IRBuilder<> IRB(&I);
1184 setShadow(&I, IRB.CreateSelect(I.getCondition(),
1185 getShadow(I.getTrueValue()), getShadow(I.getFalseValue()),
1186 "_msprop"));
1187 if (ClTrackOrigins)
1188 setOrigin(&I, IRB.CreateSelect(I.getCondition(),
1189 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue())));
1190 }
1191
1192 void visitLandingPadInst(LandingPadInst &I) {
1193 // Do nothing.
1194 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
1195 setShadow(&I, getCleanShadow(&I));
1196 setOrigin(&I, getCleanOrigin());
1197 }
1198
1199 void visitGetElementPtrInst(GetElementPtrInst &I) {
1200 handleShadowOr(I);
1201 }
1202
1203 void visitExtractValueInst(ExtractValueInst &I) {
1204 IRBuilder<> IRB(&I);
1205 Value *Agg = I.getAggregateOperand();
1206 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
1207 Value *AggShadow = getShadow(Agg);
1208 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1209 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
1210 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
1211 setShadow(&I, ResShadow);
1212 setOrigin(&I, getCleanOrigin());
1213 }
1214
1215 void visitInsertValueInst(InsertValueInst &I) {
1216 IRBuilder<> IRB(&I);
1217 DEBUG(dbgs() << "InsertValue: " << I << "\n");
1218 Value *AggShadow = getShadow(I.getAggregateOperand());
1219 Value *InsShadow = getShadow(I.getInsertedValueOperand());
1220 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1221 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
1222 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
1223 DEBUG(dbgs() << " Res: " << *Res << "\n");
1224 setShadow(&I, Res);
1225 setOrigin(&I, getCleanOrigin());
1226 }
1227
1228 void dumpInst(Instruction &I) {
1229 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1230 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
1231 } else {
1232 errs() << "ZZZ " << I.getOpcodeName() << "\n";
1233 }
1234 errs() << "QQQ " << I << "\n";
1235 }
1236
1237 void visitResumeInst(ResumeInst &I) {
1238 DEBUG(dbgs() << "Resume: " << I << "\n");
1239 // Nothing to do here.
1240 }
1241
1242 void visitInstruction(Instruction &I) {
1243 // Everything else: stop propagating and check for poisoned shadow.
1244 if (ClDumpStrictInstructions)
1245 dumpInst(I);
1246 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
1247 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
1248 insertCheck(I.getOperand(i), &I);
1249 setShadow(&I, getCleanShadow(&I));
1250 setOrigin(&I, getCleanOrigin());
1251 }
1252};
1253
1254/// \brief AMD64-specific implementation of VarArgHelper.
1255struct VarArgAMD64Helper : public VarArgHelper {
1256 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
1257 // See a comment in visitCallSite for more details.
1258 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
1259 static const unsigned AMD64FpEndOffset = 176;
1260
1261 Function &F;
1262 MemorySanitizer &MS;
1263 MemorySanitizerVisitor &MSV;
1264 Value *VAArgTLSCopy;
1265 Value *VAArgOverflowSize;
1266
1267 SmallVector<CallInst*, 16> VAStartInstrumentationList;
1268
1269 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
1270 MemorySanitizerVisitor &MSV)
1271 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
1272
1273 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
1274
1275 ArgKind classifyArgument(Value* arg) {
1276 // A very rough approximation of X86_64 argument classification rules.
1277 Type *T = arg->getType();
1278 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
1279 return AK_FloatingPoint;
1280 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
1281 return AK_GeneralPurpose;
1282 if (T->isPointerTy())
1283 return AK_GeneralPurpose;
1284 return AK_Memory;
1285 }
1286
1287 // For VarArg functions, store the argument shadow in an ABI-specific format
1288 // that corresponds to va_list layout.
1289 // We do this because Clang lowers va_arg in the frontend, and this pass
1290 // only sees the low level code that deals with va_list internals.
1291 // A much easier alternative (provided that Clang emits va_arg instructions)
1292 // would have been to associate each live instance of va_list with a copy of
1293 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
1294 // order.
1295 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
1296 unsigned GpOffset = 0;
1297 unsigned FpOffset = AMD64GpEndOffset;
1298 unsigned OverflowOffset = AMD64FpEndOffset;
1299 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1300 ArgIt != End; ++ArgIt) {
1301 Value *A = *ArgIt;
1302 ArgKind AK = classifyArgument(A);
1303 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
1304 AK = AK_Memory;
1305 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
1306 AK = AK_Memory;
1307 Value *Base;
1308 switch (AK) {
1309 case AK_GeneralPurpose:
1310 Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
1311 GpOffset += 8;
1312 break;
1313 case AK_FloatingPoint:
1314 Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
1315 FpOffset += 16;
1316 break;
1317 case AK_Memory:
1318 uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
1319 Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
1320 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
1321 }
1322 IRB.CreateStore(MSV.getShadow(A), Base);
1323 }
1324 Constant *OverflowSize =
1325 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
1326 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
1327 }
1328
1329 /// \brief Compute the shadow address for a given va_arg.
1330 Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
1331 int ArgOffset) {
1332 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
1333 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1334 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
1335 "_msarg");
1336 }
1337
1338 void visitVAStartInst(VAStartInst &I) {
1339 IRBuilder<> IRB(&I);
1340 VAStartInstrumentationList.push_back(&I);
1341 Value *VAListTag = I.getArgOperand(0);
1342 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1343
1344 // Unpoison the whole __va_list_tag.
1345 // FIXME: magic ABI constants.
1346 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1347 /* size */24, /* alignment */16, false);
1348 }
1349
1350 void visitVACopyInst(VACopyInst &I) {
1351 IRBuilder<> IRB(&I);
1352 Value *VAListTag = I.getArgOperand(0);
1353 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1354
1355 // Unpoison the whole __va_list_tag.
1356 // FIXME: magic ABI constants.
1357 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1358 /* size */ 24, /* alignment */ 16, false);
1359 }
1360
1361 void finalizeInstrumentation() {
1362 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
1363 "finalizeInstrumentation called twice");
1364 if (!VAStartInstrumentationList.empty()) {
1365 // If there is a va_start in this function, make a backup copy of
1366 // va_arg_tls somewhere in the function entry block.
1367 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1368 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
1369 Value *CopySize =
1370 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
1371 VAArgOverflowSize);
1372 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
1373 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
1374 }
1375
1376 // Instrument va_start.
1377 // Copy va_list shadow from the backup copy of the TLS contents.
1378 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
1379 CallInst *OrigInst = VAStartInstrumentationList[i];
1380 IRBuilder<> IRB(OrigInst->getNextNode());
1381 Value *VAListTag = OrigInst->getArgOperand(0);
1382
1383 Value *RegSaveAreaPtrPtr =
1384 IRB.CreateIntToPtr(
1385 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1386 ConstantInt::get(MS.IntptrTy, 16)),
1387 Type::getInt64PtrTy(*MS.C));
1388 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
1389 Value *RegSaveAreaShadowPtr =
1390 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
1391 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
1392 AMD64FpEndOffset, 16);
1393
1394 Value *OverflowArgAreaPtrPtr =
1395 IRB.CreateIntToPtr(
1396 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1397 ConstantInt::get(MS.IntptrTy, 8)),
1398 Type::getInt64PtrTy(*MS.C));
1399 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
1400 Value *OverflowArgAreaShadowPtr =
1401 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
1402 Value *SrcPtr =
1403 getShadowPtrForVAArgument(VAArgTLSCopy, IRB, AMD64FpEndOffset);
1404 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
1405 }
1406 }
1407};
1408
1409VarArgHelper* CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
1410 MemorySanitizerVisitor &Visitor) {
1411 return new VarArgAMD64Helper(Func, Msan, Visitor);
1412}
1413
1414} // namespace
1415
1416bool MemorySanitizer::runOnFunction(Function &F) {
1417 MemorySanitizerVisitor Visitor(F, *this);
1418
1419 // Clear out readonly/readnone attributes.
1420 AttrBuilder B;
1421 B.addAttribute(Attributes::ReadOnly)
1422 .addAttribute(Attributes::ReadNone);
1423 F.removeAttribute(AttrListPtr::FunctionIndex,
1424 Attributes::get(F.getContext(), B));
1425
1426 return Visitor.runOnFunction();
1427}