blob: b92c0efb65301fe54159195a3622fa5699e77af2 [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"
Chandler Carruthdbd69582012-11-30 03:08:41 +000054#include "llvm/InstVisitor.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000055#include "llvm/IntrinsicInst.h"
56#include "llvm/IRBuilder.h"
57#include "llvm/LLVMContext.h"
58#include "llvm/MDBuilder.h"
59#include "llvm/Module.h"
60#include "llvm/Type.h"
61#include "llvm/ADT/DepthFirstIterator.h"
62#include "llvm/ADT/SmallString.h"
63#include "llvm/ADT/SmallVector.h"
64#include "llvm/ADT/ValueMap.h"
65#include "llvm/Transforms/Instrumentation.h"
66#include "llvm/Transforms/Utils/BasicBlockUtils.h"
67#include "llvm/Transforms/Utils/ModuleUtils.h"
68#include "llvm/Support/CommandLine.h"
69#include "llvm/Support/Compiler.h"
70#include "llvm/Support/Debug.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000071#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
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000506 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
507 Value *ShadowLong =
508 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
Evgeniy Stepanov62ba6112012-11-29 13:43:05 +0000509 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000510 Value *Add =
511 IRB.CreateAdd(ShadowLong,
512 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
Evgeniy Stepanov62ba6112012-11-29 13:43:05 +0000513 Value *SecondAnd =
514 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
515 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000516 }
517
518 /// \brief Compute the shadow address for a given function argument.
519 ///
520 /// Shadow = ParamTLS+ArgOffset.
521 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
522 int ArgOffset) {
523 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
524 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
525 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
526 "_msarg");
527 }
528
529 /// \brief Compute the origin address for a given function argument.
530 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
531 int ArgOffset) {
532 if (!ClTrackOrigins) return 0;
533 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
534 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
535 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
536 "_msarg_o");
537 }
538
539 /// \brief Compute the shadow address for a retval.
540 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
541 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
542 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
543 "_msret");
544 }
545
546 /// \brief Compute the origin address for a retval.
547 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
548 // We keep a single origin for the entire retval. Might be too optimistic.
549 return MS.RetvalOriginTLS;
550 }
551
552 /// \brief Set SV to be the shadow value for V.
553 void setShadow(Value *V, Value *SV) {
554 assert(!ShadowMap.count(V) && "Values may only have one shadow");
555 ShadowMap[V] = SV;
556 }
557
558 /// \brief Set Origin to be the origin value for V.
559 void setOrigin(Value *V, Value *Origin) {
560 if (!ClTrackOrigins) return;
561 assert(!OriginMap.count(V) && "Values may only have one origin");
562 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
563 OriginMap[V] = Origin;
564 }
565
566 /// \brief Create a clean shadow value for a given value.
567 ///
568 /// Clean shadow (all zeroes) means all bits of the value are defined
569 /// (initialized).
570 Value *getCleanShadow(Value *V) {
571 Type *ShadowTy = getShadowTy(V);
572 if (!ShadowTy)
573 return 0;
574 return Constant::getNullValue(ShadowTy);
575 }
576
577 /// \brief Create a dirty shadow of a given shadow type.
578 Constant *getPoisonedShadow(Type *ShadowTy) {
579 assert(ShadowTy);
580 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
581 return Constant::getAllOnesValue(ShadowTy);
582 StructType *ST = cast<StructType>(ShadowTy);
583 SmallVector<Constant *, 4> Vals;
584 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
585 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
586 return ConstantStruct::get(ST, Vals);
587 }
588
589 /// \brief Create a clean (zero) origin.
590 Value *getCleanOrigin() {
591 return Constant::getNullValue(MS.OriginTy);
592 }
593
594 /// \brief Get the shadow value for a given Value.
595 ///
596 /// This function either returns the value set earlier with setShadow,
597 /// or extracts if from ParamTLS (for function arguments).
598 Value *getShadow(Value *V) {
599 if (Instruction *I = dyn_cast<Instruction>(V)) {
600 // For instructions the shadow is already stored in the map.
601 Value *Shadow = ShadowMap[V];
602 if (!Shadow) {
603 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000604 (void)I;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000605 assert(Shadow && "No shadow for a value");
606 }
607 return Shadow;
608 }
609 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
610 Value *AllOnes = getPoisonedShadow(getShadowTy(V));
611 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000612 (void)U;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000613 return AllOnes;
614 }
615 if (Argument *A = dyn_cast<Argument>(V)) {
616 // For arguments we compute the shadow on demand and store it in the map.
617 Value **ShadowPtr = &ShadowMap[V];
618 if (*ShadowPtr)
619 return *ShadowPtr;
620 Function *F = A->getParent();
621 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
622 unsigned ArgOffset = 0;
623 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
624 AI != AE; ++AI) {
625 if (!AI->getType()->isSized()) {
626 DEBUG(dbgs() << "Arg is not sized\n");
627 continue;
628 }
629 unsigned Size = AI->hasByValAttr()
630 ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
631 : MS.TD->getTypeAllocSize(AI->getType());
632 if (A == AI) {
633 Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
634 if (AI->hasByValAttr()) {
635 // ByVal pointer itself has clean shadow. We copy the actual
636 // argument shadow to the underlying memory.
637 Value *Cpy = EntryIRB.CreateMemCpy(
638 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
639 Base, Size, AI->getParamAlignment());
640 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000641 (void)Cpy;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000642 *ShadowPtr = getCleanShadow(V);
643 } else {
644 *ShadowPtr = EntryIRB.CreateLoad(Base);
645 }
646 DEBUG(dbgs() << " ARG: " << *AI << " ==> " <<
647 **ShadowPtr << "\n");
648 if (ClTrackOrigins) {
649 Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
650 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
651 }
652 }
653 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
654 }
655 assert(*ShadowPtr && "Could not find shadow for an argument");
656 return *ShadowPtr;
657 }
658 // For everything else the shadow is zero.
659 return getCleanShadow(V);
660 }
661
662 /// \brief Get the shadow for i-th argument of the instruction I.
663 Value *getShadow(Instruction *I, int i) {
664 return getShadow(I->getOperand(i));
665 }
666
667 /// \brief Get the origin for a value.
668 Value *getOrigin(Value *V) {
669 if (!ClTrackOrigins) return 0;
670 if (isa<Instruction>(V) || isa<Argument>(V)) {
671 Value *Origin = OriginMap[V];
672 if (!Origin) {
673 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
674 Origin = getCleanOrigin();
675 }
676 return Origin;
677 }
678 return getCleanOrigin();
679 }
680
681 /// \brief Get the origin for i-th argument of the instruction I.
682 Value *getOrigin(Instruction *I, int i) {
683 return getOrigin(I->getOperand(i));
684 }
685
686 /// \brief Remember the place where a shadow check should be inserted.
687 ///
688 /// This location will be later instrumented with a check that will print a
689 /// UMR warning in runtime if the value is not fully defined.
690 void insertCheck(Value *Val, Instruction *OrigIns) {
691 assert(Val);
692 if (!InsertChecks) return;
693 Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
694 if (!Shadow) return;
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000695#ifndef NDEBUG
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000696 Type *ShadowTy = Shadow->getType();
697 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
698 "Can only insert checks for integer and vector shadow types");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000699#endif
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000700 Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
701 InstrumentationList.push_back(
702 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
703 }
704
705 //------------------- Visitors.
706
707 /// \brief Instrument LoadInst
708 ///
709 /// Loads the corresponding shadow and (optionally) origin.
710 /// Optionally, checks that the load address is fully defined.
711 void visitLoadInst(LoadInst &I) {
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000712 assert(I.getType()->isSized() && "Load type must have size");
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000713 IRBuilder<> IRB(&I);
714 Type *ShadowTy = getShadowTy(&I);
715 Value *Addr = I.getPointerOperand();
716 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
Evgeniy Stepanoveeb8b7c2012-11-29 14:05:53 +0000717 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000718
719 if (ClCheckAccessAddress)
720 insertCheck(I.getPointerOperand(), &I);
721
722 if (ClTrackOrigins)
Evgeniy Stepanoveeb8b7c2012-11-29 14:05:53 +0000723 setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), I.getAlignment()));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000724 }
725
726 /// \brief Instrument StoreInst
727 ///
728 /// Stores the corresponding shadow and (optionally) origin.
729 /// Optionally, checks that the store address is fully defined.
730 /// Volatile stores check that the value being stored is fully defined.
731 void visitStoreInst(StoreInst &I) {
732 IRBuilder<> IRB(&I);
733 Value *Val = I.getValueOperand();
734 Value *Addr = I.getPointerOperand();
735 Value *Shadow = getShadow(Val);
736 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
737
Evgeniy Stepanoveeb8b7c2012-11-29 14:05:53 +0000738 StoreInst *NewSI = IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000739 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000740 (void)NewSI;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000741 // If the store is volatile, add a check.
742 if (I.isVolatile())
743 insertCheck(Val, &I);
744 if (ClCheckAccessAddress)
745 insertCheck(Addr, &I);
746
747 if (ClTrackOrigins)
Evgeniy Stepanoveeb8b7c2012-11-29 14:05:53 +0000748 IRB.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRB), I.getAlignment());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000749 }
750
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +0000751 // Vector manipulation.
752 void visitExtractElementInst(ExtractElementInst &I) {
753 insertCheck(I.getOperand(1), &I);
754 IRBuilder<> IRB(&I);
755 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
756 "_msprop"));
757 setOrigin(&I, getOrigin(&I, 0));
758 }
759
760 void visitInsertElementInst(InsertElementInst &I) {
761 insertCheck(I.getOperand(2), &I);
762 IRBuilder<> IRB(&I);
763 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
764 I.getOperand(2), "_msprop"));
765 setOriginForNaryOp(I);
766 }
767
768 void visitShuffleVectorInst(ShuffleVectorInst &I) {
769 insertCheck(I.getOperand(2), &I);
770 IRBuilder<> IRB(&I);
771 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
772 I.getOperand(2), "_msprop"));
773 setOriginForNaryOp(I);
774 }
775
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000776 // Casts.
777 void visitSExtInst(SExtInst &I) {
778 IRBuilder<> IRB(&I);
779 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
780 setOrigin(&I, getOrigin(&I, 0));
781 }
782
783 void visitZExtInst(ZExtInst &I) {
784 IRBuilder<> IRB(&I);
785 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
786 setOrigin(&I, getOrigin(&I, 0));
787 }
788
789 void visitTruncInst(TruncInst &I) {
790 IRBuilder<> IRB(&I);
791 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
792 setOrigin(&I, getOrigin(&I, 0));
793 }
794
795 void visitBitCastInst(BitCastInst &I) {
796 IRBuilder<> IRB(&I);
797 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
798 setOrigin(&I, getOrigin(&I, 0));
799 }
800
801 void visitPtrToIntInst(PtrToIntInst &I) {
802 IRBuilder<> IRB(&I);
803 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
804 "_msprop_ptrtoint"));
805 setOrigin(&I, getOrigin(&I, 0));
806 }
807
808 void visitIntToPtrInst(IntToPtrInst &I) {
809 IRBuilder<> IRB(&I);
810 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
811 "_msprop_inttoptr"));
812 setOrigin(&I, getOrigin(&I, 0));
813 }
814
815 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
816 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
817 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
818 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
819 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
820 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
821
822 /// \brief Propagate shadow for bitwise AND.
823 ///
824 /// This code is exact, i.e. if, for example, a bit in the left argument
825 /// is defined and 0, then neither the value not definedness of the
826 /// corresponding bit in B don't affect the resulting shadow.
827 void visitAnd(BinaryOperator &I) {
828 IRBuilder<> IRB(&I);
829 // "And" of 0 and a poisoned value results in unpoisoned value.
830 // 1&1 => 1; 0&1 => 0; p&1 => p;
831 // 1&0 => 0; 0&0 => 0; p&0 => 0;
832 // 1&p => p; 0&p => 0; p&p => p;
833 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
834 Value *S1 = getShadow(&I, 0);
835 Value *S2 = getShadow(&I, 1);
836 Value *V1 = I.getOperand(0);
837 Value *V2 = I.getOperand(1);
838 if (V1->getType() != S1->getType()) {
839 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
840 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
841 }
842 Value *S1S2 = IRB.CreateAnd(S1, S2);
843 Value *V1S2 = IRB.CreateAnd(V1, S2);
844 Value *S1V2 = IRB.CreateAnd(S1, V2);
845 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
846 setOriginForNaryOp(I);
847 }
848
849 void visitOr(BinaryOperator &I) {
850 IRBuilder<> IRB(&I);
851 // "Or" of 1 and a poisoned value results in unpoisoned value.
852 // 1|1 => 1; 0|1 => 1; p|1 => 1;
853 // 1|0 => 1; 0|0 => 0; p|0 => p;
854 // 1|p => 1; 0|p => p; p|p => p;
855 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
856 Value *S1 = getShadow(&I, 0);
857 Value *S2 = getShadow(&I, 1);
858 Value *V1 = IRB.CreateNot(I.getOperand(0));
859 Value *V2 = IRB.CreateNot(I.getOperand(1));
860 if (V1->getType() != S1->getType()) {
861 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
862 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
863 }
864 Value *S1S2 = IRB.CreateAnd(S1, S2);
865 Value *V1S2 = IRB.CreateAnd(V1, S2);
866 Value *S1V2 = IRB.CreateAnd(S1, V2);
867 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
868 setOriginForNaryOp(I);
869 }
870
871 /// \brief Propagate origin for an instruction.
872 ///
873 /// This is a general case of origin propagation. For an Nary operation,
874 /// is set to the origin of an argument that is not entirely initialized.
Evgeniy Stepanovf433cec2012-11-29 14:44:00 +0000875 /// If there is more than one such arguments, the rightmost of them is picked.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000876 /// It does not matter which one is picked if all arguments are initialized.
877 void setOriginForNaryOp(Instruction &I) {
878 if (!ClTrackOrigins) return;
879 IRBuilder<> IRB(&I);
880 Value *Origin = getOrigin(&I, 0);
881 for (unsigned Op = 1, n = I.getNumOperands(); Op < n; ++Op) {
Evgeniy Stepanovf433cec2012-11-29 14:44:00 +0000882 Value *S = convertToShadowTyNoVec(getShadow(&I, Op), IRB);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000883 Origin = IRB.CreateSelect(IRB.CreateICmpNE(S, getCleanShadow(S)),
Evgeniy Stepanovf433cec2012-11-29 14:44:00 +0000884 getOrigin(&I, Op), Origin);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000885 }
886 setOrigin(&I, Origin);
887 }
888
889 /// \brief Propagate shadow for a binary operation.
890 ///
891 /// Shadow = Shadow0 | Shadow1, all 3 must have the same type.
892 /// Bitwise OR is selected as an operation that will never lose even a bit of
893 /// poison.
894 void handleShadowOrBinary(Instruction &I) {
895 IRBuilder<> IRB(&I);
896 Value *Shadow0 = getShadow(&I, 0);
897 Value *Shadow1 = getShadow(&I, 1);
898 setShadow(&I, IRB.CreateOr(Shadow0, Shadow1, "_msprop"));
899 setOriginForNaryOp(I);
900 }
901
902 /// \brief Propagate shadow for arbitrary operation.
903 ///
904 /// This is a general case of shadow propagation, used in all cases where we
905 /// don't know and/or care about what the operation actually does.
906 /// It converts all input shadow values to a common type (extending or
907 /// truncating as necessary), and bitwise OR's them.
908 ///
909 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
910 /// fully initialized), and less prone to false positives.
911 // FIXME: is the casting actually correct?
912 // FIXME: merge this with handleShadowOrBinary.
913 void handleShadowOr(Instruction &I) {
914 IRBuilder<> IRB(&I);
915 Value *Shadow = getShadow(&I, 0);
916 for (unsigned Op = 1, n = I.getNumOperands(); Op < n; ++Op)
917 Shadow = IRB.CreateOr(
918 Shadow, IRB.CreateIntCast(getShadow(&I, Op), Shadow->getType(), false),
919 "_msprop");
920 Shadow = IRB.CreateIntCast(Shadow, getShadowTy(&I), false);
921 setShadow(&I, Shadow);
922 setOriginForNaryOp(I);
923 }
924
925 void visitFAdd(BinaryOperator &I) { handleShadowOrBinary(I); }
926 void visitFSub(BinaryOperator &I) { handleShadowOrBinary(I); }
927 void visitFMul(BinaryOperator &I) { handleShadowOrBinary(I); }
928 void visitAdd(BinaryOperator &I) { handleShadowOrBinary(I); }
929 void visitSub(BinaryOperator &I) { handleShadowOrBinary(I); }
930 void visitXor(BinaryOperator &I) { handleShadowOrBinary(I); }
931 void visitMul(BinaryOperator &I) { handleShadowOrBinary(I); }
932
933 void handleDiv(Instruction &I) {
934 IRBuilder<> IRB(&I);
935 // Strict on the second argument.
936 insertCheck(I.getOperand(1), &I);
937 setShadow(&I, getShadow(&I, 0));
938 setOrigin(&I, getOrigin(&I, 0));
939 }
940
941 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
942 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
943 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
944 void visitURem(BinaryOperator &I) { handleDiv(I); }
945 void visitSRem(BinaryOperator &I) { handleDiv(I); }
946 void visitFRem(BinaryOperator &I) { handleDiv(I); }
947
948 /// \brief Instrument == and != comparisons.
949 ///
950 /// Sometimes the comparison result is known even if some of the bits of the
951 /// arguments are not.
952 void handleEqualityComparison(ICmpInst &I) {
953 IRBuilder<> IRB(&I);
954 Value *A = I.getOperand(0);
955 Value *B = I.getOperand(1);
956 Value *Sa = getShadow(A);
957 Value *Sb = getShadow(B);
958 if (A->getType()->isPointerTy())
959 A = IRB.CreatePointerCast(A, MS.IntptrTy);
960 if (B->getType()->isPointerTy())
961 B = IRB.CreatePointerCast(B, MS.IntptrTy);
962 // A == B <==> (C = A^B) == 0
963 // A != B <==> (C = A^B) != 0
964 // Sc = Sa | Sb
965 Value *C = IRB.CreateXor(A, B);
966 Value *Sc = IRB.CreateOr(Sa, Sb);
967 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
968 // Result is defined if one of the following is true
969 // * there is a defined 1 bit in C
970 // * C is fully defined
971 // Si = !(C & ~Sc) && Sc
972 Value *Zero = Constant::getNullValue(Sc->getType());
973 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
974 Value *Si =
975 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
976 IRB.CreateICmpEQ(
977 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
978 Si->setName("_msprop_icmp");
979 setShadow(&I, Si);
980 setOriginForNaryOp(I);
981 }
982
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +0000983 /// \brief Instrument signed relational comparisons.
984 ///
985 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
986 /// propagating the highest bit of the shadow. Everything else is delegated
987 /// to handleShadowOr().
988 void handleSignedRelationalComparison(ICmpInst &I) {
989 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
990 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
991 Value* op = NULL;
992 CmpInst::Predicate pre = I.getPredicate();
993 if (constOp0 && constOp0->isNullValue() &&
994 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
995 op = I.getOperand(1);
996 } else if (constOp1 && constOp1->isNullValue() &&
997 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
998 op = I.getOperand(0);
999 }
1000 if (op) {
1001 IRBuilder<> IRB(&I);
1002 Value* Shadow =
1003 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1004 setShadow(&I, Shadow);
1005 setOrigin(&I, getOrigin(op));
1006 } else {
1007 handleShadowOr(I);
1008 }
1009 }
1010
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001011 void visitICmpInst(ICmpInst &I) {
1012 if (ClHandleICmp && I.isEquality())
1013 handleEqualityComparison(I);
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001014 else if (ClHandleICmp && I.isSigned() && I.isRelational())
1015 handleSignedRelationalComparison(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001016 else
1017 handleShadowOr(I);
1018 }
1019
1020 void visitFCmpInst(FCmpInst &I) {
1021 handleShadowOr(I);
1022 }
1023
1024 void handleShift(BinaryOperator &I) {
1025 IRBuilder<> IRB(&I);
1026 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1027 // Otherwise perform the same shift on S1.
1028 Value *S1 = getShadow(&I, 0);
1029 Value *S2 = getShadow(&I, 1);
1030 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1031 S2->getType());
1032 Value *V2 = I.getOperand(1);
1033 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1034 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1035 setOriginForNaryOp(I);
1036 }
1037
1038 void visitShl(BinaryOperator &I) { handleShift(I); }
1039 void visitAShr(BinaryOperator &I) { handleShift(I); }
1040 void visitLShr(BinaryOperator &I) { handleShift(I); }
1041
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001042 /// \brief Instrument llvm.memmove
1043 ///
1044 /// At this point we don't know if llvm.memmove will be inlined or not.
1045 /// If we don't instrument it and it gets inlined,
1046 /// our interceptor will not kick in and we will lose the memmove.
1047 /// If we instrument the call here, but it does not get inlined,
1048 /// we will memove the shadow twice: which is bad in case
1049 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1050 ///
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001051 /// Similar situation exists for memcpy and memset.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001052 void visitMemMoveInst(MemMoveInst &I) {
1053 IRBuilder<> IRB(&I);
1054 IRB.CreateCall3(
1055 MS.MemmoveFn,
1056 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1057 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1058 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1059 I.eraseFromParent();
1060 }
1061
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001062 // Similar to memmove: avoid copying shadow twice.
1063 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1064 // FIXME: consider doing manual inline for small constant sizes and proper
1065 // alignment.
1066 void visitMemCpyInst(MemCpyInst &I) {
1067 IRBuilder<> IRB(&I);
1068 IRB.CreateCall3(
1069 MS.MemcpyFn,
1070 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1071 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1072 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1073 I.eraseFromParent();
1074 }
1075
1076 // Same as memcpy.
1077 void visitMemSetInst(MemSetInst &I) {
1078 IRBuilder<> IRB(&I);
1079 IRB.CreateCall3(
1080 MS.MemsetFn,
1081 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1082 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1083 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1084 I.eraseFromParent();
1085 }
1086
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001087 void visitVAStartInst(VAStartInst &I) {
1088 VAHelper->visitVAStartInst(I);
1089 }
1090
1091 void visitVACopyInst(VACopyInst &I) {
1092 VAHelper->visitVACopyInst(I);
1093 }
1094
1095 void visitCallSite(CallSite CS) {
1096 Instruction &I = *CS.getInstruction();
1097 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1098 if (CS.isCall()) {
Evgeniy Stepanov7ad7e832012-11-29 14:32:03 +00001099 CallInst *Call = cast<CallInst>(&I);
1100
1101 // For inline asm, do the usual thing: check argument shadow and mark all
1102 // outputs as clean. Note that any side effects of the inline asm that are
1103 // not immediately visible in its constraints are not handled.
1104 if (Call->isInlineAsm()) {
1105 visitInstruction(I);
1106 return;
1107 }
1108
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001109 // Allow only tail calls with the same types, otherwise
1110 // we may have a false positive: shadow for a non-void RetVal
1111 // will get propagated to a void RetVal.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001112 if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1113 Call->setTailCall(false);
1114 if (isa<IntrinsicInst>(&I)) {
1115 // All intrinsics we care about are handled in corresponding visit*
1116 // methods. Add checks for the arguments, mark retval as clean.
1117 visitInstruction(I);
1118 return;
1119 }
1120 }
1121 IRBuilder<> IRB(&I);
1122 unsigned ArgOffset = 0;
1123 DEBUG(dbgs() << " CallSite: " << I << "\n");
1124 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1125 ArgIt != End; ++ArgIt) {
1126 Value *A = *ArgIt;
1127 unsigned i = ArgIt - CS.arg_begin();
1128 if (!A->getType()->isSized()) {
1129 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1130 continue;
1131 }
1132 unsigned Size = 0;
1133 Value *Store = 0;
1134 // Compute the Shadow for arg even if it is ByVal, because
1135 // in that case getShadow() will copy the actual arg shadow to
1136 // __msan_param_tls.
1137 Value *ArgShadow = getShadow(A);
1138 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1139 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
1140 " Shadow: " << *ArgShadow << "\n");
1141 if (CS.paramHasAttr(i + 1, Attributes::ByVal)) {
1142 assert(A->getType()->isPointerTy() &&
1143 "ByVal argument is not a pointer!");
1144 Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1145 unsigned Alignment = CS.getParamAlignment(i + 1);
1146 Store = IRB.CreateMemCpy(ArgShadowBase,
1147 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1148 Size, Alignment);
1149 } else {
1150 Size = MS.TD->getTypeAllocSize(A->getType());
1151 Store = IRB.CreateStore(ArgShadow, ArgShadowBase);
1152 }
1153 if (ClTrackOrigins)
1154 IRB.CreateStore(getOrigin(A),
1155 getOriginPtrForArgument(A, IRB, ArgOffset));
1156 assert(Size != 0 && Store != 0);
1157 DEBUG(dbgs() << " Param:" << *Store << "\n");
1158 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1159 }
1160 DEBUG(dbgs() << " done with call args\n");
1161
1162 FunctionType *FT =
1163 cast<FunctionType>(CS.getCalledValue()->getType()-> getContainedType(0));
1164 if (FT->isVarArg()) {
1165 VAHelper->visitCallSite(CS, IRB);
1166 }
1167
1168 // Now, get the shadow for the RetVal.
1169 if (!I.getType()->isSized()) return;
1170 IRBuilder<> IRBBefore(&I);
1171 // Untill we have full dynamic coverage, make sure the retval shadow is 0.
1172 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
1173 IRBBefore.CreateStore(getCleanShadow(&I), Base);
1174 Instruction *NextInsn = 0;
1175 if (CS.isCall()) {
1176 NextInsn = I.getNextNode();
1177 } else {
1178 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1179 if (!NormalDest->getSinglePredecessor()) {
1180 // FIXME: this case is tricky, so we are just conservative here.
1181 // Perhaps we need to split the edge between this BB and NormalDest,
1182 // but a naive attempt to use SplitEdge leads to a crash.
1183 setShadow(&I, getCleanShadow(&I));
1184 setOrigin(&I, getCleanOrigin());
1185 return;
1186 }
1187 NextInsn = NormalDest->getFirstInsertionPt();
1188 assert(NextInsn &&
1189 "Could not find insertion point for retval shadow load");
1190 }
1191 IRBuilder<> IRBAfter(NextInsn);
1192 setShadow(&I, IRBAfter.CreateLoad(getShadowPtrForRetval(&I, IRBAfter),
1193 "_msret"));
1194 if (ClTrackOrigins)
1195 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1196 }
1197
1198 void visitReturnInst(ReturnInst &I) {
1199 IRBuilder<> IRB(&I);
1200 if (Value *RetVal = I.getReturnValue()) {
1201 // Set the shadow for the RetVal.
1202 Value *Shadow = getShadow(RetVal);
1203 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
1204 DEBUG(dbgs() << "Return: " << *Shadow << "\n" << *ShadowPtr << "\n");
1205 IRB.CreateStore(Shadow, ShadowPtr);
1206 if (ClTrackOrigins)
1207 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
1208 }
1209 }
1210
1211 void visitPHINode(PHINode &I) {
1212 IRBuilder<> IRB(&I);
1213 ShadowPHINodes.push_back(&I);
1214 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
1215 "_msphi_s"));
1216 if (ClTrackOrigins)
1217 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
1218 "_msphi_o"));
1219 }
1220
1221 void visitAllocaInst(AllocaInst &I) {
1222 setShadow(&I, getCleanShadow(&I));
1223 if (!ClPoisonStack) return;
1224 IRBuilder<> IRB(I.getNextNode());
1225 uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
1226 if (ClPoisonStackWithCall) {
1227 IRB.CreateCall2(MS.MsanPoisonStackFn,
1228 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1229 ConstantInt::get(MS.IntptrTy, Size));
1230 } else {
1231 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
1232 IRB.CreateMemSet(ShadowBase, IRB.getInt8(ClPoisonStackPattern),
1233 Size, I.getAlignment());
1234 }
1235
1236 if (ClTrackOrigins) {
1237 setOrigin(&I, getCleanOrigin());
1238 SmallString<2048> StackDescriptionStorage;
1239 raw_svector_ostream StackDescription(StackDescriptionStorage);
1240 // We create a string with a description of the stack allocation and
1241 // pass it into __msan_set_alloca_origin.
1242 // It will be printed by the run-time if stack-originated UMR is found.
1243 // The first 4 bytes of the string are set to '----' and will be replaced
1244 // by __msan_va_arg_overflow_size_tls at the first call.
1245 StackDescription << "----" << I.getName() << "@" << F.getName();
1246 Value *Descr =
1247 createPrivateNonConstGlobalForString(*F.getParent(),
1248 StackDescription.str());
1249 IRB.CreateCall3(MS.MsanSetAllocaOriginFn,
1250 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1251 ConstantInt::get(MS.IntptrTy, Size),
1252 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()));
1253 }
1254 }
1255
1256 void visitSelectInst(SelectInst& I) {
1257 IRBuilder<> IRB(&I);
1258 setShadow(&I, IRB.CreateSelect(I.getCondition(),
1259 getShadow(I.getTrueValue()), getShadow(I.getFalseValue()),
1260 "_msprop"));
1261 if (ClTrackOrigins)
1262 setOrigin(&I, IRB.CreateSelect(I.getCondition(),
1263 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue())));
1264 }
1265
1266 void visitLandingPadInst(LandingPadInst &I) {
1267 // Do nothing.
1268 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
1269 setShadow(&I, getCleanShadow(&I));
1270 setOrigin(&I, getCleanOrigin());
1271 }
1272
1273 void visitGetElementPtrInst(GetElementPtrInst &I) {
1274 handleShadowOr(I);
1275 }
1276
1277 void visitExtractValueInst(ExtractValueInst &I) {
1278 IRBuilder<> IRB(&I);
1279 Value *Agg = I.getAggregateOperand();
1280 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
1281 Value *AggShadow = getShadow(Agg);
1282 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1283 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
1284 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
1285 setShadow(&I, ResShadow);
1286 setOrigin(&I, getCleanOrigin());
1287 }
1288
1289 void visitInsertValueInst(InsertValueInst &I) {
1290 IRBuilder<> IRB(&I);
1291 DEBUG(dbgs() << "InsertValue: " << I << "\n");
1292 Value *AggShadow = getShadow(I.getAggregateOperand());
1293 Value *InsShadow = getShadow(I.getInsertedValueOperand());
1294 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1295 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
1296 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
1297 DEBUG(dbgs() << " Res: " << *Res << "\n");
1298 setShadow(&I, Res);
1299 setOrigin(&I, getCleanOrigin());
1300 }
1301
1302 void dumpInst(Instruction &I) {
1303 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1304 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
1305 } else {
1306 errs() << "ZZZ " << I.getOpcodeName() << "\n";
1307 }
1308 errs() << "QQQ " << I << "\n";
1309 }
1310
1311 void visitResumeInst(ResumeInst &I) {
1312 DEBUG(dbgs() << "Resume: " << I << "\n");
1313 // Nothing to do here.
1314 }
1315
1316 void visitInstruction(Instruction &I) {
1317 // Everything else: stop propagating and check for poisoned shadow.
1318 if (ClDumpStrictInstructions)
1319 dumpInst(I);
1320 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
1321 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
1322 insertCheck(I.getOperand(i), &I);
1323 setShadow(&I, getCleanShadow(&I));
1324 setOrigin(&I, getCleanOrigin());
1325 }
1326};
1327
1328/// \brief AMD64-specific implementation of VarArgHelper.
1329struct VarArgAMD64Helper : public VarArgHelper {
1330 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
1331 // See a comment in visitCallSite for more details.
1332 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
1333 static const unsigned AMD64FpEndOffset = 176;
1334
1335 Function &F;
1336 MemorySanitizer &MS;
1337 MemorySanitizerVisitor &MSV;
1338 Value *VAArgTLSCopy;
1339 Value *VAArgOverflowSize;
1340
1341 SmallVector<CallInst*, 16> VAStartInstrumentationList;
1342
1343 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
1344 MemorySanitizerVisitor &MSV)
1345 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
1346
1347 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
1348
1349 ArgKind classifyArgument(Value* arg) {
1350 // A very rough approximation of X86_64 argument classification rules.
1351 Type *T = arg->getType();
1352 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
1353 return AK_FloatingPoint;
1354 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
1355 return AK_GeneralPurpose;
1356 if (T->isPointerTy())
1357 return AK_GeneralPurpose;
1358 return AK_Memory;
1359 }
1360
1361 // For VarArg functions, store the argument shadow in an ABI-specific format
1362 // that corresponds to va_list layout.
1363 // We do this because Clang lowers va_arg in the frontend, and this pass
1364 // only sees the low level code that deals with va_list internals.
1365 // A much easier alternative (provided that Clang emits va_arg instructions)
1366 // would have been to associate each live instance of va_list with a copy of
1367 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
1368 // order.
1369 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
1370 unsigned GpOffset = 0;
1371 unsigned FpOffset = AMD64GpEndOffset;
1372 unsigned OverflowOffset = AMD64FpEndOffset;
1373 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1374 ArgIt != End; ++ArgIt) {
1375 Value *A = *ArgIt;
1376 ArgKind AK = classifyArgument(A);
1377 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
1378 AK = AK_Memory;
1379 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
1380 AK = AK_Memory;
1381 Value *Base;
1382 switch (AK) {
1383 case AK_GeneralPurpose:
1384 Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
1385 GpOffset += 8;
1386 break;
1387 case AK_FloatingPoint:
1388 Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
1389 FpOffset += 16;
1390 break;
1391 case AK_Memory:
1392 uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
1393 Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
1394 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
1395 }
1396 IRB.CreateStore(MSV.getShadow(A), Base);
1397 }
1398 Constant *OverflowSize =
1399 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
1400 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
1401 }
1402
1403 /// \brief Compute the shadow address for a given va_arg.
1404 Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
1405 int ArgOffset) {
1406 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
1407 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1408 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
1409 "_msarg");
1410 }
1411
1412 void visitVAStartInst(VAStartInst &I) {
1413 IRBuilder<> IRB(&I);
1414 VAStartInstrumentationList.push_back(&I);
1415 Value *VAListTag = I.getArgOperand(0);
1416 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1417
1418 // Unpoison the whole __va_list_tag.
1419 // FIXME: magic ABI constants.
1420 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1421 /* size */24, /* alignment */16, false);
1422 }
1423
1424 void visitVACopyInst(VACopyInst &I) {
1425 IRBuilder<> IRB(&I);
1426 Value *VAListTag = I.getArgOperand(0);
1427 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1428
1429 // Unpoison the whole __va_list_tag.
1430 // FIXME: magic ABI constants.
1431 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1432 /* size */ 24, /* alignment */ 16, false);
1433 }
1434
1435 void finalizeInstrumentation() {
1436 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
1437 "finalizeInstrumentation called twice");
1438 if (!VAStartInstrumentationList.empty()) {
1439 // If there is a va_start in this function, make a backup copy of
1440 // va_arg_tls somewhere in the function entry block.
1441 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1442 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
1443 Value *CopySize =
1444 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
1445 VAArgOverflowSize);
1446 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
1447 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
1448 }
1449
1450 // Instrument va_start.
1451 // Copy va_list shadow from the backup copy of the TLS contents.
1452 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
1453 CallInst *OrigInst = VAStartInstrumentationList[i];
1454 IRBuilder<> IRB(OrigInst->getNextNode());
1455 Value *VAListTag = OrigInst->getArgOperand(0);
1456
1457 Value *RegSaveAreaPtrPtr =
1458 IRB.CreateIntToPtr(
1459 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1460 ConstantInt::get(MS.IntptrTy, 16)),
1461 Type::getInt64PtrTy(*MS.C));
1462 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
1463 Value *RegSaveAreaShadowPtr =
1464 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
1465 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
1466 AMD64FpEndOffset, 16);
1467
1468 Value *OverflowArgAreaPtrPtr =
1469 IRB.CreateIntToPtr(
1470 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1471 ConstantInt::get(MS.IntptrTy, 8)),
1472 Type::getInt64PtrTy(*MS.C));
1473 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
1474 Value *OverflowArgAreaShadowPtr =
1475 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
1476 Value *SrcPtr =
1477 getShadowPtrForVAArgument(VAArgTLSCopy, IRB, AMD64FpEndOffset);
1478 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
1479 }
1480 }
1481};
1482
1483VarArgHelper* CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
1484 MemorySanitizerVisitor &Visitor) {
1485 return new VarArgAMD64Helper(Func, Msan, Visitor);
1486}
1487
1488} // namespace
1489
1490bool MemorySanitizer::runOnFunction(Function &F) {
1491 MemorySanitizerVisitor Visitor(F, *this);
1492
1493 // Clear out readonly/readnone attributes.
1494 AttrBuilder B;
1495 B.addAttribute(Attributes::ReadOnly)
1496 .addAttribute(Attributes::ReadNone);
1497 F.removeAttribute(AttrListPtr::FunctionIndex,
1498 Attributes::get(F.getContext(), B));
1499
1500 return Visitor.runOnFunction();
1501}