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