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