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