quick fix: remove GlobalVariable::GlobalVariable mistakenly commited at r144933....
[oota-llvm.git] / lib / Transforms / Instrumentation / AddressSanitizer.cpp
1 //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
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 //
10 // This file is a part of AddressSanitizer, an address sanity checker.
11 // Details of the algorithm:
12 //  http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "asan"
17
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/Function.h"
25 #include "llvm/InlineAsm.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/Module.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/DataTypes.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/IRBuilder.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Regex.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Support/system_error.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Transforms/Instrumentation.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/ModuleUtils.h"
42 #include "llvm/Type.h"
43
44 #include <string>
45 #include <algorithm>
46
47 using namespace llvm;
48
49 static const uint64_t kDefaultShadowScale = 3;
50 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
51 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
52
53 static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
54 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
55 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
56
57 static const char *kAsanModuleCtorName = "asan.module_ctor";
58 static const char *kAsanReportErrorTemplate = "__asan_report_";
59 static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
60 static const char *kAsanInitName = "__asan_init";
61 static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
62 static const char *kAsanMappingScaleName = "__asan_mapping_scale";
63 static const char *kAsanStackMallocName = "__asan_stack_malloc";
64 static const char *kAsanStackFreeName = "__asan_stack_free";
65
66 static const int kAsanStackLeftRedzoneMagic = 0xf1;
67 static const int kAsanStackMidRedzoneMagic = 0xf2;
68 static const int kAsanStackRightRedzoneMagic = 0xf3;
69 static const int kAsanStackPartialRedzoneMagic = 0xf4;
70
71 // Command-line flags.
72
73 // This flag may need to be replaced with -f[no-]asan-reads.
74 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
75        cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
76 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
77        cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
78 // This flag may need to be replaced with -f[no]asan-stack.
79 static cl::opt<bool> ClStack("asan-stack",
80        cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
81 // This flag may need to be replaced with -f[no]asan-use-after-return.
82 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
83        cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
84 // This flag may need to be replaced with -f[no]asan-globals.
85 static cl::opt<bool> ClGlobals("asan-globals",
86        cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
87 static cl::opt<bool> ClMemIntrin("asan-memintrin",
88        cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
89 // This flag may need to be replaced with -fasan-blacklist.
90 static cl::opt<std::string>  ClBlackListFile("asan-blacklist",
91        cl::desc("File containing the list of functions to ignore "
92                 "during instrumentation"), cl::Hidden);
93 static cl::opt<bool> ClUseCall("asan-use-call",
94        cl::desc("Use function call to generate a crash"), cl::Hidden,
95        cl::init(true));
96
97 // These flags allow to change the shadow mapping.
98 // The shadow mapping looks like
99 //    Shadow = (Mem >> scale) + (1 << offset_log)
100 static cl::opt<int> ClMappingScale("asan-mapping-scale",
101        cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
102 static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
103        cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
104
105 // Optimization flags. Not user visible, used mostly for testing
106 // and benchmarking the tool.
107 static cl::opt<bool> ClOpt("asan-opt",
108        cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
109 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
110        cl::desc("Instrument the same temp just once"), cl::Hidden,
111        cl::init(true));
112 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
113        cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
114
115 // Debug flags.
116 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
117                             cl::init(0));
118 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
119                                  cl::Hidden, cl::init(0));
120 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
121                                         cl::Hidden, cl::desc("Debug func"));
122 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
123                                cl::Hidden, cl::init(-1));
124 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
125                                cl::Hidden, cl::init(-1));
126
127 namespace {
128
129 // Blacklisted functions are not instrumented.
130 // The blacklist file contains one or more lines like this:
131 // ---
132 // fun:FunctionWildCard
133 // ---
134 // This is similar to the "ignore" feature of ThreadSanitizer.
135 // http://code.google.com/p/data-race-test/wiki/ThreadSanitizerIgnores
136 class BlackList {
137  public:
138   BlackList(const std::string &Path);
139   bool isIn(const Function &F);
140  private:
141   Regex *Functions;
142 };
143
144 /// AddressSanitizer: instrument the code in module to find memory bugs.
145 struct AddressSanitizer : public ModulePass {
146   AddressSanitizer();
147   void instrumentMop(Instruction *I);
148   void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
149                          Value *Addr, uint32_t TypeSize, bool IsWrite);
150   Instruction *generateCrashCode(IRBuilder<> &IRB, Value *Addr,
151                                  bool IsWrite, uint32_t TypeSize);
152   bool instrumentMemIntrinsic(MemIntrinsic *MI);
153   void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
154                                   Value *Size,
155                                    Instruction *InsertBefore, bool IsWrite);
156   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
157   bool handleFunction(Module &M, Function &F);
158   bool poisonStackInFunction(Module &M, Function &F);
159   virtual bool runOnModule(Module &M);
160   bool insertGlobalRedzones(Module &M);
161   BranchInst *splitBlockAndInsertIfThen(Instruction *SplitBefore, Value *Cmp);
162   static char ID;  // Pass identification, replacement for typeid
163
164  private:
165
166   uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
167     Type *Ty = AI->getAllocatedType();
168     uint64_t SizeInBytes = TD->getTypeStoreSizeInBits(Ty) / 8;
169     return SizeInBytes;
170   }
171   uint64_t getAlignedSize(uint64_t SizeInBytes) {
172     return ((SizeInBytes + RedzoneSize - 1)
173             / RedzoneSize) * RedzoneSize;
174   }
175   uint64_t getAlignedAllocaSize(AllocaInst *AI) {
176     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
177     return getAlignedSize(SizeInBytes);
178   }
179
180   void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
181                    Value *ShadowBase, bool DoPoison);
182
183   Module      *CurrentModule;
184   LLVMContext *C;
185   TargetData *TD;
186   uint64_t MappingOffset;
187   int MappingScale;
188   size_t RedzoneSize;
189   int LongSize;
190   Type *IntptrTy;
191   Type *IntptrPtrTy;
192   Function *AsanCtorFunction;
193   Function *AsanInitFunction;
194   Instruction *CtorInsertBefore;
195   OwningPtr<BlackList> BL;
196 };
197 }  // namespace
198
199 char AddressSanitizer::ID = 0;
200 INITIALIZE_PASS(AddressSanitizer, "asan",
201     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
202     false, false)
203 AddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
204 ModulePass *llvm::createAddressSanitizerPass() {
205   return new AddressSanitizer();
206 }
207
208 // Create a constant for Str so that we can pass it to the run-time lib.
209 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
210   Constant *StrConst = ConstantArray::get(M.getContext(), Str);
211   return new GlobalVariable(M, StrConst->getType(), true,
212                             GlobalValue::PrivateLinkage, StrConst, "");
213 }
214
215 // Split the basic block and insert an if-then code.
216 // Before:
217 //   Head
218 //   SplitBefore
219 //   Tail
220 // After:
221 //   Head
222 //   if (Cmp)
223 //     NewBasicBlock
224 //   SplitBefore
225 //   Tail
226 //
227 // Returns the NewBasicBlock's terminator.
228 BranchInst *AddressSanitizer::splitBlockAndInsertIfThen(
229     Instruction *SplitBefore, Value *Cmp) {
230   BasicBlock *Head = SplitBefore->getParent();
231   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
232   TerminatorInst *HeadOldTerm = Head->getTerminator();
233   BasicBlock *NewBasicBlock =
234       BasicBlock::Create(*C, "", Head->getParent());
235   BranchInst *HeadNewTerm = BranchInst::Create(/*ifTrue*/NewBasicBlock,
236                                                /*ifFalse*/Tail,
237                                                Cmp);
238   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
239
240   BranchInst *CheckTerm = BranchInst::Create(Tail, NewBasicBlock);
241   return CheckTerm;
242 }
243
244 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
245   // Shadow >> scale
246   Shadow = IRB.CreateLShr(Shadow, MappingScale);
247   if (MappingOffset == 0)
248     return Shadow;
249   // (Shadow >> scale) | offset
250   return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
251                                                MappingOffset));
252 }
253
254 void AddressSanitizer::instrumentMemIntrinsicParam(Instruction *OrigIns,
255     Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
256   // Check the first byte.
257   {
258     IRBuilder<> IRB(InsertBefore);
259     instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
260   }
261   // Check the last byte.
262   {
263     IRBuilder<> IRB(InsertBefore);
264     Value *SizeMinusOne = IRB.CreateSub(
265         Size, ConstantInt::get(Size->getType(), 1));
266     SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
267     Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
268     Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
269     instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
270   }
271 }
272
273 // Instrument memset/memmove/memcpy
274 bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
275   Value *Dst = MI->getDest();
276   MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
277   Value *Src = MemTran ? MemTran->getSource() : NULL;
278   Value *Length = MI->getLength();
279
280   Constant *ConstLength = dyn_cast<Constant>(Length);
281   Instruction *InsertBefore = MI;
282   if (ConstLength) {
283     if (ConstLength->isNullValue()) return false;
284   } else {
285     // The size is not a constant so it could be zero -- check at run-time.
286     IRBuilder<> IRB(InsertBefore);
287
288     Value *Cmp = IRB.CreateICmpNE(Length,
289                                    Constant::getNullValue(Length->getType()));
290     InsertBefore = splitBlockAndInsertIfThen(InsertBefore, Cmp);
291   }
292
293   instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
294   if (Src)
295     instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
296   return true;
297 }
298
299 static Value *getLDSTOperand(Instruction *I) {
300   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
301     return LI->getPointerOperand();
302   }
303   return cast<StoreInst>(*I).getPointerOperand();
304 }
305
306 void AddressSanitizer::instrumentMop(Instruction *I) {
307   int IsWrite = isa<StoreInst>(*I);
308   Value *Addr = getLDSTOperand(I);
309   if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
310     // We are accessing a global scalar variable. Nothing to catch here.
311     return;
312   }
313   Type *OrigPtrTy = Addr->getType();
314   Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
315
316   assert(OrigTy->isSized());
317   uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
318
319   if (TypeSize != 8  && TypeSize != 16 &&
320       TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
321     // Ignore all unusual sizes.
322     return;
323   }
324
325   IRBuilder<> IRB(I);
326   instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
327 }
328
329 Instruction *AddressSanitizer::generateCrashCode(
330     IRBuilder<> &IRB, Value *Addr, bool IsWrite, uint32_t TypeSize) {
331
332   if (ClUseCall) {
333     // Here we use a call instead of arch-specific asm to report an error.
334     // This is almost always slower (because the codegen needs to generate
335     // prologue/epilogue for otherwise leaf functions) and generates more code.
336     // This mode could be useful if we can not use SIGILL for some reason.
337     //
338     // IsWrite and TypeSize are encoded in the function name.
339     std::string FunctionName = std::string(kAsanReportErrorTemplate) +
340         (IsWrite ? "store" : "load") + itostr(TypeSize / 8);
341     Value *ReportWarningFunc = CurrentModule->getOrInsertFunction(
342         FunctionName, IRB.getVoidTy(), IntptrTy, NULL);
343     CallInst *Call = IRB.CreateCall(ReportWarningFunc, Addr);
344     Call->setDoesNotReturn();
345     return Call;
346   }
347
348   uint32_t LogOfSizeInBytes = CountTrailingZeros_32(TypeSize / 8);
349   assert(8U * (1 << LogOfSizeInBytes) == TypeSize);
350   uint8_t TelltaleValue = IsWrite * 8 + LogOfSizeInBytes;
351   assert(TelltaleValue < 16);
352
353   // Move the failing address to %rax/%eax
354   FunctionType *Fn1Ty = FunctionType::get(
355       IRB.getVoidTy(), ArrayRef<Type*>(IntptrTy), false);
356   const char *MovStr = LongSize == 32
357       ? "mov $0, %eax" : "mov $0, %rax";
358   Value *AsmMov = InlineAsm::get(
359       Fn1Ty, StringRef(MovStr), StringRef("r"), true);
360   IRB.CreateCall(AsmMov, Addr);
361
362   // crash with ud2; could use int3, but it is less friendly to gdb.
363   // after ud2 put a 1-byte instruction that encodes the access type and size.
364
365   const char *TelltaleInsns[16] = {
366     "push   %eax",  // 0x50
367     "push   %ecx",  // 0x51
368     "push   %edx",  // 0x52
369     "push   %ebx",  // 0x53
370     "push   %esp",  // 0x54
371     "push   %ebp",  // 0x55
372     "push   %esi",  // 0x56
373     "push   %edi",  // 0x57
374     "pop    %eax",  // 0x58
375     "pop    %ecx",  // 0x59
376     "pop    %edx",  // 0x5a
377     "pop    %ebx",  // 0x5b
378     "pop    %esp",  // 0x5c
379     "pop    %ebp",  // 0x5d
380     "pop    %esi",  // 0x5e
381     "pop    %edi"   // 0x5f
382   };
383
384   std::string AsmStr = "ud2;";
385   AsmStr += TelltaleInsns[TelltaleValue];
386   Value *MyAsm = InlineAsm::get(FunctionType::get(Type::getVoidTy(*C), false),
387                                 StringRef(AsmStr), StringRef(""), true);
388   CallInst *AsmCall = IRB.CreateCall(MyAsm);
389
390   // This saves us one jump, but triggers a bug in RA (or somewhere else):
391   // while building 483.xalancbmk the compiler goes into infinite loop in
392   // llvm::SpillPlacement::iterate() / RAGreedy::growRegion
393   // AsmCall->setDoesNotReturn();
394   return AsmCall;
395 }
396
397 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
398                                          IRBuilder<> &IRB, Value *Addr,
399                                          uint32_t TypeSize, bool IsWrite) {
400   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
401
402   Type *ShadowTy  = IntegerType::get(
403       *C, std::max(8U, TypeSize >> MappingScale));
404   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
405   Value *ShadowPtr = memToShadow(AddrLong, IRB);
406   Value *CmpVal = Constant::getNullValue(ShadowTy);
407   Value *ShadowValue = IRB.CreateLoad(
408       IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
409
410   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
411
412   Instruction *CheckTerm = splitBlockAndInsertIfThen(
413       cast<Instruction>(Cmp)->getNextNode(), Cmp);
414   IRBuilder<> IRB2(CheckTerm);
415
416   size_t Granularity = 1 << MappingScale;
417   if (TypeSize < 8 * Granularity) {
418     // Addr & (Granularity - 1)
419     Value *Lower3Bits = IRB2.CreateAnd(
420         AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
421     // (Addr & (Granularity - 1)) + size - 1
422     Value *LastAccessedByte = IRB2.CreateAdd(
423         Lower3Bits, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
424     // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
425     LastAccessedByte = IRB2.CreateIntCast(
426         LastAccessedByte, IRB.getInt8Ty(), false);
427     // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
428     Value *Cmp2 = IRB2.CreateICmpSGE(LastAccessedByte, ShadowValue);
429
430     CheckTerm = splitBlockAndInsertIfThen(CheckTerm, Cmp2);
431   }
432
433   IRBuilder<> IRB1(CheckTerm);
434   Instruction *Crash = generateCrashCode(IRB1, AddrLong, IsWrite, TypeSize);
435   Crash->setDebugLoc(OrigIns->getDebugLoc());
436 }
437
438 // This function replaces all global variables with new variables that have
439 // trailing redzones. It also creates a function that poisons
440 // redzones and inserts this function into llvm.global_ctors.
441 bool AddressSanitizer::insertGlobalRedzones(Module &M) {
442   SmallVector<GlobalVariable *, 16> GlobalsToChange;
443
444   for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
445        E = M.getGlobalList().end(); G != E; ++G) {
446     Type *Ty = cast<PointerType>(G->getType())->getElementType();
447     DEBUG(dbgs() << "GLOBAL: " << *G);
448
449     if (!Ty->isSized()) continue;
450     if (!G->hasInitializer()) continue;
451     // Touch only those globals that will not be defined in other modules.
452     // Don't handle ODR type linkages since other modules may be built w/o asan.
453     if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
454         G->getLinkage() != GlobalVariable::PrivateLinkage &&
455         G->getLinkage() != GlobalVariable::InternalLinkage)
456       continue;
457     // For now, just ignore this Alloca if the alignment is large.
458     if (G->getAlignment() > RedzoneSize) continue;
459
460     // Ignore all the globals with the names starting with "\01L_OBJC_".
461     // Many of those are put into the .cstring section. The linker compresses
462     // that section by removing the spare \0s after the string terminator, so
463     // our redzones get broken.
464     if ((G->getName().find("\01L_OBJC_") == 0) ||
465         (G->getName().find("\01l_OBJC_") == 0)) {
466       DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
467       continue;
468     }
469
470     // Ignore the globals from the __OBJC section. The ObjC runtime assumes
471     // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
472     // them.
473     if (G->hasSection()) {
474       StringRef Section(G->getSection());
475       if ((Section.find("__OBJC,") == 0) ||
476           (Section.find("__DATA, __objc_") == 0)) {
477         DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
478         continue;
479       }
480     }
481
482     GlobalsToChange.push_back(G);
483   }
484
485   size_t n = GlobalsToChange.size();
486   if (n == 0) return false;
487
488   // A global is described by a structure
489   //   size_t beg;
490   //   size_t size;
491   //   size_t size_with_redzone;
492   //   const char *name;
493   // We initialize an array of such structures and pass it to a run-time call.
494   StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
495                                                IntptrTy, IntptrTy, NULL);
496   SmallVector<Constant *, 16> Initializers(n);
497
498   IRBuilder<> IRB(CtorInsertBefore);
499
500   for (size_t i = 0; i < n; i++) {
501     GlobalVariable *G = GlobalsToChange[i];
502     PointerType *PtrTy = cast<PointerType>(G->getType());
503     Type *Ty = PtrTy->getElementType();
504     uint64_t SizeInBytes = TD->getTypeStoreSizeInBits(Ty) / 8;
505     uint64_t RightRedzoneSize = RedzoneSize +
506         (RedzoneSize - (SizeInBytes % RedzoneSize));
507     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
508
509     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
510     Constant *NewInitializer = ConstantStruct::get(
511         NewTy, G->getInitializer(),
512         Constant::getNullValue(RightRedZoneTy), NULL);
513
514     GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
515
516     // Create a new global variable with enough space for a redzone.
517     GlobalVariable *NewGlobal = new GlobalVariable(
518         M, NewTy, G->isConstant(), G->getLinkage(),
519         NewInitializer, "", G, G->isThreadLocal());
520     NewGlobal->copyAttributesFrom(G);
521     NewGlobal->setAlignment(RedzoneSize);
522
523     Value *Indices2[2];
524     Indices2[0] = IRB.getInt32(0);
525     Indices2[1] = IRB.getInt32(0);
526
527     G->replaceAllUsesWith(
528         ConstantExpr::getGetElementPtr(NewGlobal, Indices2, 2));
529     NewGlobal->takeName(G);
530     G->eraseFromParent();
531
532     Initializers[i] = ConstantStruct::get(
533         GlobalStructTy,
534         ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
535         ConstantInt::get(IntptrTy, SizeInBytes),
536         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
537         ConstantExpr::getPointerCast(Name, IntptrTy),
538         NULL);
539     DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
540   }
541
542   ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
543   GlobalVariable *AllGlobals = new GlobalVariable(
544       M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
545       ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
546
547   Function *AsanRegisterGlobals = cast<Function>(M.getOrInsertFunction(
548       kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
549   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
550
551   IRB.CreateCall2(AsanRegisterGlobals,
552                   IRB.CreatePointerCast(AllGlobals, IntptrTy),
553                   ConstantInt::get(IntptrTy, n));
554
555   DEBUG(dbgs() << M);
556   return true;
557 }
558
559 // virtual
560 bool AddressSanitizer::runOnModule(Module &M) {
561   // Initialize the private fields. No one has accessed them before.
562   TD = getAnalysisIfAvailable<TargetData>();
563   if (!TD)
564     return false;
565   BL.reset(new BlackList(ClBlackListFile));
566
567   CurrentModule = &M;
568   C = &(M.getContext());
569   LongSize = TD->getPointerSizeInBits();
570   IntptrTy = Type::getIntNTy(*C, LongSize);
571   IntptrPtrTy = PointerType::get(IntptrTy, 0);
572
573   AsanCtorFunction = Function::Create(
574       FunctionType::get(Type::getVoidTy(*C), false),
575       GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
576   BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
577   CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
578
579   // call __asan_init in the module ctor.
580   IRBuilder<> IRB(CtorInsertBefore);
581   AsanInitFunction = cast<Function>(
582       M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
583   AsanInitFunction->setLinkage(Function::ExternalLinkage);
584   IRB.CreateCall(AsanInitFunction);
585
586   MappingOffset = LongSize == 32
587       ? kDefaultShadowOffset32 : kDefaultShadowOffset64;
588   if (ClMappingOffsetLog >= 0) {
589     if (ClMappingOffsetLog == 0) {
590       // special case
591       MappingOffset = 0;
592     } else {
593       MappingOffset = 1ULL << ClMappingOffsetLog;
594     }
595   }
596   MappingScale = kDefaultShadowScale;
597   if (ClMappingScale) {
598     MappingScale = ClMappingScale;
599   }
600   // Redzone used for stack and globals is at least 32 bytes.
601   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
602   RedzoneSize = std::max(32, (int)(1 << MappingScale));
603
604   bool Res = false;
605
606   if (ClGlobals)
607     Res |= insertGlobalRedzones(M);
608
609   // Tell the run-time the current values of mapping offset and scale.
610   GlobalValue *asan_mapping_offset =
611       new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
612                      ConstantInt::get(IntptrTy, MappingOffset),
613                      kAsanMappingOffsetName);
614   GlobalValue *asan_mapping_scale =
615       new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
616                          ConstantInt::get(IntptrTy, MappingScale),
617                          kAsanMappingScaleName);
618   // Read these globals, otherwise they may be optimized away.
619   IRB.CreateLoad(asan_mapping_scale, true);
620   IRB.CreateLoad(asan_mapping_offset, true);
621
622
623   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
624     if (F->isDeclaration()) continue;
625     Res |= handleFunction(M, *F);
626   }
627
628   appendToGlobalCtors(M, AsanCtorFunction, 1 /*high priority*/);
629
630   return Res;
631 }
632
633 bool AddressSanitizer::handleFunction(Module &M, Function &F) {
634   if (BL->isIn(F)) return false;
635   if (&F == AsanCtorFunction) return false;
636
637   if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
638     return false;
639   // We want to instrument every address only once per basic block
640   // (unless there are calls between uses).
641   SmallSet<Value*, 16> TempsToInstrument;
642   SmallVector<Instruction*, 16> ToInstrument;
643
644   // Fill the set of memory operations to instrument.
645   for (Function::iterator FI = F.begin(), FE = F.end();
646        FI != FE; ++FI) {
647     TempsToInstrument.clear();
648     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
649          BI != BE; ++BI) {
650       if ((isa<LoadInst>(BI) && ClInstrumentReads) ||
651           (isa<StoreInst>(BI) && ClInstrumentWrites)) {
652         Value *Addr = getLDSTOperand(BI);
653         if (ClOpt && ClOptSameTemp) {
654           if (!TempsToInstrument.insert(Addr))
655             continue;  // We've seen this temp in the current BB.
656         }
657       } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
658         // ok, take it.
659       } else {
660         if (isa<CallInst>(BI)) {
661           // A call inside BB.
662           TempsToInstrument.clear();
663         }
664         continue;
665       }
666       ToInstrument.push_back(BI);
667     }
668   }
669
670   // Instrument.
671   int NumInstrumented = 0;
672   for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
673     Instruction *Inst = ToInstrument[i];
674     if (ClDebugMin < 0 || ClDebugMax < 0 ||
675         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
676       if (isa<StoreInst>(Inst) || isa<LoadInst>(Inst))
677         instrumentMop(Inst);
678       else
679         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
680     }
681     NumInstrumented++;
682   }
683
684   DEBUG(dbgs() << F);
685
686   bool ChangedStack = poisonStackInFunction(M, F);
687
688   // For each NSObject descendant having a +load method, this method is invoked
689   // by the ObjC runtime before any of the static constructors is called.
690   // Therefore we need to instrument such methods with a call to __asan_init
691   // at the beginning in order to initialize our runtime before any access to
692   // the shadow memory.
693   // We cannot just ignore these methods, because they may call other
694   // instrumented functions.
695   if (F.getName().find(" load]") != std::string::npos) {
696     IRBuilder<> IRB(F.begin()->begin());
697     IRB.CreateCall(AsanInitFunction);
698   }
699
700   return NumInstrumented > 0 || ChangedStack;
701 }
702
703 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
704   if (ShadowRedzoneSize == 1) return PoisonByte;
705   if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
706   if (ShadowRedzoneSize == 4)
707     return (PoisonByte << 24) + (PoisonByte << 16) +
708         (PoisonByte << 8) + (PoisonByte);
709   assert(0 && "ShadowRedzoneSize is either 1, 2 or 4");
710   return 0;
711 }
712
713 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
714                                             size_t Size,
715                                             size_t RedzoneSize,
716                                             size_t ShadowGranularity,
717                                             uint8_t Magic) {
718   for (size_t i = 0; i < RedzoneSize;
719        i+= ShadowGranularity, Shadow++) {
720     if (i + ShadowGranularity <= Size) {
721       *Shadow = 0;  // fully addressable
722     } else if (i >= Size) {
723       *Shadow = Magic;  // unaddressable
724     } else {
725       *Shadow = Size - i;  // first Size-i bytes are addressable
726     }
727   }
728 }
729
730 void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
731                                    IRBuilder<> IRB,
732                                    Value *ShadowBase, bool DoPoison) {
733   size_t ShadowRZSize = RedzoneSize >> MappingScale;
734   assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
735   Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
736   Type *RZPtrTy = PointerType::get(RZTy, 0);
737
738   Value *PoisonLeft  = ConstantInt::get(RZTy,
739     ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
740   Value *PoisonMid   = ConstantInt::get(RZTy,
741     ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
742   Value *PoisonRight = ConstantInt::get(RZTy,
743     ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
744
745   // poison the first red zone.
746   IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
747
748   // poison all other red zones.
749   uint64_t Pos = RedzoneSize;
750   for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
751     AllocaInst *AI = AllocaVec[i];
752     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
753     uint64_t AlignedSize = getAlignedAllocaSize(AI);
754     assert(AlignedSize - SizeInBytes < RedzoneSize);
755     Value *Ptr = NULL;
756
757     Pos += AlignedSize;
758
759     assert(ShadowBase->getType() == IntptrTy);
760     if (SizeInBytes < AlignedSize) {
761       // Poison the partial redzone at right
762       Ptr = IRB.CreateAdd(
763           ShadowBase, ConstantInt::get(IntptrTy,
764                                        (Pos >> MappingScale) - ShadowRZSize));
765       size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
766       uint32_t Poison = 0;
767       if (DoPoison) {
768         PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
769                                         RedzoneSize,
770                                         1ULL << MappingScale,
771                                         kAsanStackPartialRedzoneMagic);
772       }
773       Value *PartialPoison = ConstantInt::get(RZTy, Poison);
774       IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
775     }
776
777     // Poison the full redzone at right.
778     Ptr = IRB.CreateAdd(ShadowBase,
779                         ConstantInt::get(IntptrTy, Pos >> MappingScale));
780     Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
781     IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
782
783     Pos += RedzoneSize;
784   }
785 }
786
787 // Find all static Alloca instructions and put
788 // poisoned red zones around all of them.
789 // Then unpoison everything back before the function returns.
790 //
791 // Stack poisoning does not play well with exception handling.
792 // When an exception is thrown, we essentially bypass the code
793 // that unpoisones the stack. This is why the run-time library has
794 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
795 // stack in the interceptor. This however does not work inside the
796 // actual function which catches the exception. Most likely because the
797 // compiler hoists the load of the shadow value somewhere too high.
798 // This causes asan to report a non-existing bug on 453.povray.
799 // It sounds like an LLVM bug.
800 bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
801   if (!ClStack) return false;
802   SmallVector<AllocaInst*, 16> AllocaVec;
803   SmallVector<Instruction*, 8> RetVec;
804   uint64_t TotalSize = 0;
805
806   // Filter out Alloca instructions we want (and can) handle.
807   // Collect Ret instructions.
808   for (Function::iterator FI = F.begin(), FE = F.end();
809        FI != FE; ++FI) {
810     BasicBlock &BB = *FI;
811     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
812          BI != BE; ++BI) {
813       if (isa<ReturnInst>(BI)) {
814           RetVec.push_back(BI);
815           continue;
816       }
817
818       AllocaInst *AI = dyn_cast<AllocaInst>(BI);
819       if (!AI) continue;
820       if (AI->isArrayAllocation()) continue;
821       if (!AI->isStaticAlloca()) continue;
822       if (!AI->getAllocatedType()->isSized()) continue;
823       if (AI->getAlignment() > RedzoneSize) continue;
824       AllocaVec.push_back(AI);
825       uint64_t AlignedSize =  getAlignedAllocaSize(AI);
826       TotalSize += AlignedSize;
827     }
828   }
829
830   if (AllocaVec.empty()) return false;
831
832   uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
833
834   bool DoStackMalloc = ClUseAfterReturn
835       && LocalStackSize <= kMaxStackMallocSize;
836
837   Instruction *InsBefore = AllocaVec[0];
838   IRBuilder<> IRB(InsBefore);
839
840
841   Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
842   AllocaInst *MyAlloca =
843       new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
844   MyAlloca->setAlignment(RedzoneSize);
845   assert(MyAlloca->isStaticAlloca());
846   Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
847   Value *LocalStackBase = OrigStackBase;
848
849   if (DoStackMalloc) {
850     Value *AsanStackMallocFunc = M.getOrInsertFunction(
851         kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
852     LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
853         ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
854   }
855
856   // This string will be parsed by the run-time (DescribeStackAddress).
857   SmallString<2048> StackDescriptionStorage;
858   raw_svector_ostream StackDescription(StackDescriptionStorage);
859   StackDescription << F.getName() << " " << AllocaVec.size() << " ";
860
861   uint64_t Pos = RedzoneSize;
862   // Replace Alloca instructions with base+offset.
863   for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
864     AllocaInst *AI = AllocaVec[i];
865     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
866     StringRef Name = AI->getName();
867     StackDescription << Pos << " " << SizeInBytes << " "
868                      << Name.size() << " " << Name << " ";
869     uint64_t AlignedSize = getAlignedAllocaSize(AI);
870     assert((AlignedSize % RedzoneSize) == 0);
871     AI->replaceAllUsesWith(
872         IRB.CreateIntToPtr(
873             IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
874             AI->getType()));
875     Pos += AlignedSize + RedzoneSize;
876   }
877   assert(Pos == LocalStackSize);
878
879   // Write the Magic value and the frame description constant to the redzone.
880   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
881   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
882                   BasePlus0);
883   Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
884                                    ConstantInt::get(IntptrTy, LongSize/8));
885   BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
886   Value *Description = IRB.CreatePointerCast(
887       createPrivateGlobalForString(M, StackDescription.str()),
888       IntptrTy);
889   IRB.CreateStore(Description, BasePlus1);
890
891   // Poison the stack redzones at the entry.
892   Value *ShadowBase = memToShadow(LocalStackBase, IRB);
893   PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
894
895   Value *AsanStackFreeFunc = NULL;
896   if (DoStackMalloc) {
897     AsanStackFreeFunc = M.getOrInsertFunction(
898         kAsanStackFreeName, IRB.getVoidTy(),
899         IntptrTy, IntptrTy, IntptrTy, NULL);
900   }
901
902   // Unpoison the stack before all ret instructions.
903   for (size_t i = 0, n = RetVec.size(); i < n; i++) {
904     Instruction *Ret = RetVec[i];
905     IRBuilder<> IRBRet(Ret);
906
907     // Mark the current frame as retired.
908     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
909                        BasePlus0);
910     // Unpoison the stack.
911     PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
912
913     if (DoStackMalloc) {
914       IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
915                          ConstantInt::get(IntptrTy, LocalStackSize),
916                          OrigStackBase);
917     }
918   }
919
920   if (ClDebugStack) {
921     DEBUG(dbgs() << F);
922   }
923
924   return true;
925 }
926
927 BlackList::BlackList(const std::string &Path) {
928   Functions = NULL;
929   const char *kFunPrefix = "fun:";
930   if (!ClBlackListFile.size()) return;
931   std::string Fun;
932
933   OwningPtr<MemoryBuffer> File;
934   if (error_code EC = MemoryBuffer::getFile(ClBlackListFile.c_str(), File)) {
935     errs() << EC.message();
936     exit(1);
937   }
938   MemoryBuffer *Buff = File.take();
939   const char *Data = Buff->getBufferStart();
940   size_t DataLen = Buff->getBufferSize();
941   SmallVector<StringRef, 16> Lines;
942   SplitString(StringRef(Data, DataLen), Lines, "\n\r");
943   for (size_t i = 0, numLines = Lines.size(); i < numLines; i++) {
944     if (Lines[i].startswith(kFunPrefix)) {
945       std::string ThisFunc = Lines[i].substr(strlen(kFunPrefix));
946       if (Fun.size()) {
947         Fun += "|";
948       }
949       // add ThisFunc replacing * with .*
950       for (size_t j = 0, n = ThisFunc.size(); j < n; j++) {
951         if (ThisFunc[j] == '*')
952           Fun += '.';
953         Fun += ThisFunc[j];
954       }
955     }
956   }
957   if (Fun.size()) {
958     Functions = new Regex(Fun);
959   }
960 }
961
962 bool BlackList::isIn(const Function &F) {
963   if (Functions) {
964     bool Res = Functions->match(F.getName());
965     return Res;
966   }
967   return false;
968 }