ASan: add blacklist file to ASan pass options. Clang patch for this will follow.
[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/Transforms/Instrumentation.h"
19 #include "BlackList.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/DataLayout.h"
28 #include "llvm/Function.h"
29 #include "llvm/IRBuilder.h"
30 #include "llvm/InlineAsm.h"
31 #include "llvm/IntrinsicInst.h"
32 #include "llvm/LLVMContext.h"
33 #include "llvm/Module.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/DataTypes.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Support/system_error.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/ModuleUtils.h"
42 #include "llvm/Type.h"
43 #include <algorithm>
44 #include <string>
45
46 using namespace llvm;
47
48 static const uint64_t kDefaultShadowScale = 3;
49 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
50 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
51 static const uint64_t kDefaultShadowOffsetAndroid = 0;
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 *kAsanModuleDtorName = "asan.module_dtor";
59 static const int   kAsanCtorAndCtorPriority = 1;
60 static const char *kAsanReportErrorTemplate = "__asan_report_";
61 static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
62 static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
63 static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
64 static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
65 static const char *kAsanInitName = "__asan_init";
66 static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
67 static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
68 static const char *kAsanMappingScaleName = "__asan_mapping_scale";
69 static const char *kAsanStackMallocName = "__asan_stack_malloc";
70 static const char *kAsanStackFreeName = "__asan_stack_free";
71 static const char *kAsanGenPrefix = "__asan_gen_";
72
73 static const int kAsanStackLeftRedzoneMagic = 0xf1;
74 static const int kAsanStackMidRedzoneMagic = 0xf2;
75 static const int kAsanStackRightRedzoneMagic = 0xf3;
76 static const int kAsanStackPartialRedzoneMagic = 0xf4;
77
78 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
79 static const size_t kNumberOfAccessSizes = 5;
80
81 // Command-line flags.
82
83 // This flag may need to be replaced with -f[no-]asan-reads.
84 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
85        cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
86 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
87        cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
88 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
89        cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
90        cl::Hidden, cl::init(true));
91 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
92        cl::desc("use instrumentation with slow path for all accesses"),
93        cl::Hidden, cl::init(false));
94 // This flag limits the number of instructions to be instrumented
95 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
96 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
97 // set it to 10000.
98 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
99        cl::init(10000),
100        cl::desc("maximal number of instructions to instrument in any given BB"),
101        cl::Hidden);
102 // This flag may need to be replaced with -f[no]asan-stack.
103 static cl::opt<bool> ClStack("asan-stack",
104        cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
105 // This flag may need to be replaced with -f[no]asan-use-after-return.
106 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
107        cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
108 // This flag may need to be replaced with -f[no]asan-globals.
109 static cl::opt<bool> ClGlobals("asan-globals",
110        cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
111 static cl::opt<bool> ClInitializers("asan-initialization-order",
112        cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
113 static cl::opt<bool> ClMemIntrin("asan-memintrin",
114        cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
115 static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
116        cl::desc("File containing the list of objects to ignore "
117                 "during instrumentation"), cl::Hidden);
118
119 // These flags allow to change the shadow mapping.
120 // The shadow mapping looks like
121 //    Shadow = (Mem >> scale) + (1 << offset_log)
122 static cl::opt<int> ClMappingScale("asan-mapping-scale",
123        cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
124 static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
125        cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
126
127 // Optimization flags. Not user visible, used mostly for testing
128 // and benchmarking the tool.
129 static cl::opt<bool> ClOpt("asan-opt",
130        cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
131 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
132        cl::desc("Instrument the same temp just once"), cl::Hidden,
133        cl::init(true));
134 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
135        cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
136
137 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
138        cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
139        cl::Hidden, cl::init(false));
140
141 // Debug flags.
142 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
143                             cl::init(0));
144 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
145                                  cl::Hidden, cl::init(0));
146 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
147                                         cl::Hidden, cl::desc("Debug func"));
148 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
149                                cl::Hidden, cl::init(-1));
150 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
151                                cl::Hidden, cl::init(-1));
152
153 namespace {
154 /// A set of dynamically initialized globals extracted from metadata.
155 class SetOfDynamicallyInitializedGlobals {
156  public:
157   void Init(Module& M) {
158     // Clang generates metadata identifying all dynamically initialized globals.
159     NamedMDNode *DynamicGlobals =
160         M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
161     if (!DynamicGlobals)
162       return;
163     for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
164       MDNode *MDN = DynamicGlobals->getOperand(i);
165       assert(MDN->getNumOperands() == 1);
166       Value *VG = MDN->getOperand(0);
167       // The optimizer may optimize away a global entirely, in which case we
168       // cannot instrument access to it.
169       if (!VG)
170         continue;
171       DynInitGlobals.insert(cast<GlobalVariable>(VG));
172     }
173   }
174   bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
175  private:
176   SmallSet<GlobalValue*, 32> DynInitGlobals;
177 };
178
179 static int MappingScale() {
180   return ClMappingScale ? ClMappingScale : kDefaultShadowScale;
181 }
182
183 static size_t RedzoneSize() {
184   // Redzone used for stack and globals is at least 32 bytes.
185   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
186   return std::max(32U, 1U << MappingScale());
187 }
188
189 /// AddressSanitizer: instrument the code in module to find memory bugs.
190 struct AddressSanitizer : public FunctionPass {
191   AddressSanitizer(bool CheckInitOrder = false,
192                    bool CheckUseAfterReturn = false,
193                    bool CheckLifetime = false,
194                    StringRef BlacklistFile = StringRef())
195       : FunctionPass(ID),
196         CheckInitOrder(CheckInitOrder || ClInitializers),
197         CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
198         CheckLifetime(CheckLifetime || ClCheckLifetime),
199         BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
200                                             : BlacklistFile) {}
201   virtual const char *getPassName() const {
202     return "AddressSanitizerFunctionPass";
203   }
204   void instrumentMop(Instruction *I);
205   void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
206                          Value *Addr, uint32_t TypeSize, bool IsWrite);
207   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
208                            Value *ShadowValue, uint32_t TypeSize);
209   Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
210                                  bool IsWrite, size_t AccessSizeIndex);
211   bool instrumentMemIntrinsic(MemIntrinsic *MI);
212   void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
213                                    Value *Size,
214                                    Instruction *InsertBefore, bool IsWrite);
215   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
216   bool runOnFunction(Function &F);
217   void createInitializerPoisonCalls(Module &M,
218                                     Value *FirstAddr, Value *LastAddr);
219   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
220   bool poisonStackInFunction(Function &F);
221   virtual bool doInitialization(Module &M);
222   static char ID;  // Pass identification, replacement for typeid
223
224  private:
225   void initializeCallbacks(Module &M);
226   uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
227     Type *Ty = AI->getAllocatedType();
228     uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
229     return SizeInBytes;
230   }
231   uint64_t getAlignedSize(uint64_t SizeInBytes) {
232     size_t RZ = RedzoneSize();
233     return ((SizeInBytes + RZ - 1) / RZ) * RZ;
234   }
235   uint64_t getAlignedAllocaSize(AllocaInst *AI) {
236     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
237     return getAlignedSize(SizeInBytes);
238   }
239
240   bool ShouldInstrumentGlobal(GlobalVariable *G);
241   void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
242                    Value *ShadowBase, bool DoPoison);
243   bool LooksLikeCodeInBug11395(Instruction *I);
244   void FindDynamicInitializers(Module &M);
245
246   bool CheckInitOrder;
247   bool CheckUseAfterReturn;
248   bool CheckLifetime;
249   LLVMContext *C;
250   DataLayout *TD;
251   uint64_t MappingOffset;
252   int LongSize;
253   Type *IntptrTy;
254   Type *IntptrPtrTy;
255   Function *AsanCtorFunction;
256   Function *AsanInitFunction;
257   Function *AsanStackMallocFunc, *AsanStackFreeFunc;
258   Function *AsanHandleNoReturnFunc;
259   SmallString<64> BlacklistFile;
260   OwningPtr<BlackList> BL;
261   // This array is indexed by AccessIsWrite and log2(AccessSize).
262   Function *AsanErrorCallback[2][kNumberOfAccessSizes];
263   InlineAsm *EmptyAsm;
264   SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
265 };
266
267 class AddressSanitizerModule : public ModulePass {
268  public:
269   AddressSanitizerModule(bool CheckInitOrder = false,
270                          StringRef BlacklistFile = StringRef())
271       : ModulePass(ID),
272         CheckInitOrder(CheckInitOrder || ClInitializers),
273         BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
274                                             : BlacklistFile) {}
275   bool runOnModule(Module &M);
276   static char ID;  // Pass identification, replacement for typeid
277   virtual const char *getPassName() const {
278     return "AddressSanitizerModule";
279   }
280  private:
281   bool ShouldInstrumentGlobal(GlobalVariable *G);
282   void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
283                                     Value *LastAddr);
284
285   bool CheckInitOrder;
286   SmallString<64> BlacklistFile;
287   OwningPtr<BlackList> BL;
288   SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
289   Type *IntptrTy;
290   LLVMContext *C;
291   DataLayout *TD;
292 };
293
294 }  // namespace
295
296 char AddressSanitizer::ID = 0;
297 INITIALIZE_PASS(AddressSanitizer, "asan",
298     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
299     false, false)
300 FunctionPass *llvm::createAddressSanitizerFunctionPass(
301     bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
302     StringRef BlacklistFile) {
303   return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
304                               CheckLifetime, BlacklistFile);
305 }
306
307 char AddressSanitizerModule::ID = 0;
308 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
309     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
310     "ModulePass", false, false)
311 ModulePass *llvm::createAddressSanitizerModulePass(
312     bool CheckInitOrder, StringRef BlacklistFile) {
313   return new AddressSanitizerModule(CheckInitOrder, BlacklistFile);
314 }
315
316 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
317   size_t Res = CountTrailingZeros_32(TypeSize / 8);
318   assert(Res < kNumberOfAccessSizes);
319   return Res;
320 }
321
322 // Create a constant for Str so that we can pass it to the run-time lib.
323 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
324   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
325   return new GlobalVariable(M, StrConst->getType(), true,
326                             GlobalValue::PrivateLinkage, StrConst,
327                             kAsanGenPrefix);
328 }
329
330 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
331   return G->getName().find(kAsanGenPrefix) == 0;
332 }
333
334 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
335   // Shadow >> scale
336   Shadow = IRB.CreateLShr(Shadow, MappingScale());
337   if (MappingOffset == 0)
338     return Shadow;
339   // (Shadow >> scale) | offset
340   return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
341                                                MappingOffset));
342 }
343
344 void AddressSanitizer::instrumentMemIntrinsicParam(
345     Instruction *OrigIns,
346     Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
347   // Check the first byte.
348   {
349     IRBuilder<> IRB(InsertBefore);
350     instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
351   }
352   // Check the last byte.
353   {
354     IRBuilder<> IRB(InsertBefore);
355     Value *SizeMinusOne = IRB.CreateSub(
356         Size, ConstantInt::get(Size->getType(), 1));
357     SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
358     Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
359     Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
360     instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
361   }
362 }
363
364 // Instrument memset/memmove/memcpy
365 bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
366   Value *Dst = MI->getDest();
367   MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
368   Value *Src = MemTran ? MemTran->getSource() : 0;
369   Value *Length = MI->getLength();
370
371   Constant *ConstLength = dyn_cast<Constant>(Length);
372   Instruction *InsertBefore = MI;
373   if (ConstLength) {
374     if (ConstLength->isNullValue()) return false;
375   } else {
376     // The size is not a constant so it could be zero -- check at run-time.
377     IRBuilder<> IRB(InsertBefore);
378
379     Value *Cmp = IRB.CreateICmpNE(Length,
380                                   Constant::getNullValue(Length->getType()));
381     InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
382   }
383
384   instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
385   if (Src)
386     instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
387   return true;
388 }
389
390 // If I is an interesting memory access, return the PointerOperand
391 // and set IsWrite. Otherwise return NULL.
392 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
393   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
394     if (!ClInstrumentReads) return NULL;
395     *IsWrite = false;
396     return LI->getPointerOperand();
397   }
398   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
399     if (!ClInstrumentWrites) return NULL;
400     *IsWrite = true;
401     return SI->getPointerOperand();
402   }
403   if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
404     if (!ClInstrumentAtomics) return NULL;
405     *IsWrite = true;
406     return RMW->getPointerOperand();
407   }
408   if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
409     if (!ClInstrumentAtomics) return NULL;
410     *IsWrite = true;
411     return XCHG->getPointerOperand();
412   }
413   return NULL;
414 }
415
416 void AddressSanitizer::instrumentMop(Instruction *I) {
417   bool IsWrite = false;
418   Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
419   assert(Addr);
420   if (ClOpt && ClOptGlobals) {
421     if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
422       // If initialization order checking is disabled, a simple access to a
423       // dynamically initialized global is always valid.
424       if (!CheckInitOrder)
425         return;
426       // If a global variable does not have dynamic initialization we don't
427       // have to instrument it.  However, if a global does not have initailizer
428       // at all, we assume it has dynamic initializer (in other TU).
429       if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
430         return;
431     }
432   }
433
434   Type *OrigPtrTy = Addr->getType();
435   Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
436
437   assert(OrigTy->isSized());
438   uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
439
440   if (TypeSize != 8  && TypeSize != 16 &&
441       TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
442     // Ignore all unusual sizes.
443     return;
444   }
445
446   IRBuilder<> IRB(I);
447   instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
448 }
449
450 // Validate the result of Module::getOrInsertFunction called for an interface
451 // function of AddressSanitizer. If the instrumented module defines a function
452 // with the same name, their prototypes must match, otherwise
453 // getOrInsertFunction returns a bitcast.
454 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
455   if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
456   FuncOrBitcast->dump();
457   report_fatal_error("trying to redefine an AddressSanitizer "
458                      "interface function");
459 }
460
461 Instruction *AddressSanitizer::generateCrashCode(
462     Instruction *InsertBefore, Value *Addr,
463     bool IsWrite, size_t AccessSizeIndex) {
464   IRBuilder<> IRB(InsertBefore);
465   CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
466                                   Addr);
467   // We don't do Call->setDoesNotReturn() because the BB already has
468   // UnreachableInst at the end.
469   // This EmptyAsm is required to avoid callback merge.
470   IRB.CreateCall(EmptyAsm);
471   return Call;
472 }
473
474 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
475                                             Value *ShadowValue,
476                                             uint32_t TypeSize) {
477   size_t Granularity = 1 << MappingScale();
478   // Addr & (Granularity - 1)
479   Value *LastAccessedByte = IRB.CreateAnd(
480       AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
481   // (Addr & (Granularity - 1)) + size - 1
482   if (TypeSize / 8 > 1)
483     LastAccessedByte = IRB.CreateAdd(
484         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
485   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
486   LastAccessedByte = IRB.CreateIntCast(
487       LastAccessedByte, ShadowValue->getType(), false);
488   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
489   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
490 }
491
492 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
493                                          IRBuilder<> &IRB, Value *Addr,
494                                          uint32_t TypeSize, bool IsWrite) {
495   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
496
497   Type *ShadowTy  = IntegerType::get(
498       *C, std::max(8U, TypeSize >> MappingScale()));
499   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
500   Value *ShadowPtr = memToShadow(AddrLong, IRB);
501   Value *CmpVal = Constant::getNullValue(ShadowTy);
502   Value *ShadowValue = IRB.CreateLoad(
503       IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
504
505   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
506   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
507   size_t Granularity = 1 << MappingScale();
508   TerminatorInst *CrashTerm = 0;
509
510   if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
511     TerminatorInst *CheckTerm =
512         SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
513     assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
514     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
515     IRB.SetInsertPoint(CheckTerm);
516     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
517     BasicBlock *CrashBlock =
518         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
519     CrashTerm = new UnreachableInst(*C, CrashBlock);
520     BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
521     ReplaceInstWithInst(CheckTerm, NewTerm);
522   } else {
523     CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
524   }
525
526   Instruction *Crash =
527       generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
528   Crash->setDebugLoc(OrigIns->getDebugLoc());
529 }
530
531 void AddressSanitizerModule::createInitializerPoisonCalls(
532     Module &M, Value *FirstAddr, Value *LastAddr) {
533   // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
534   Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
535   // If that function is not present, this TU contains no globals, or they have
536   // all been optimized away
537   if (!GlobalInit)
538     return;
539
540   // Set up the arguments to our poison/unpoison functions.
541   IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
542
543   // Declare our poisoning and unpoisoning functions.
544   Function *AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
545       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
546   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
547   Function *AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
548       kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
549   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
550
551   // Add a call to poison all external globals before the given function starts.
552   IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
553
554   // Add calls to unpoison all globals before each return instruction.
555   for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
556       I != E; ++I) {
557     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
558       CallInst::Create(AsanUnpoisonGlobals, "", RI);
559     }
560   }
561 }
562
563 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
564   Type *Ty = cast<PointerType>(G->getType())->getElementType();
565   DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
566
567   if (BL->isIn(*G)) return false;
568   if (!Ty->isSized()) return false;
569   if (!G->hasInitializer()) return false;
570   if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
571   // Touch only those globals that will not be defined in other modules.
572   // Don't handle ODR type linkages since other modules may be built w/o asan.
573   if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
574       G->getLinkage() != GlobalVariable::PrivateLinkage &&
575       G->getLinkage() != GlobalVariable::InternalLinkage)
576     return false;
577   // Two problems with thread-locals:
578   //   - The address of the main thread's copy can't be computed at link-time.
579   //   - Need to poison all copies, not just the main thread's one.
580   if (G->isThreadLocal())
581     return false;
582   // For now, just ignore this Alloca if the alignment is large.
583   if (G->getAlignment() > RedzoneSize()) return false;
584
585   // Ignore all the globals with the names starting with "\01L_OBJC_".
586   // Many of those are put into the .cstring section. The linker compresses
587   // that section by removing the spare \0s after the string terminator, so
588   // our redzones get broken.
589   if ((G->getName().find("\01L_OBJC_") == 0) ||
590       (G->getName().find("\01l_OBJC_") == 0)) {
591     DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
592     return false;
593   }
594
595   if (G->hasSection()) {
596     StringRef Section(G->getSection());
597     // Ignore the globals from the __OBJC section. The ObjC runtime assumes
598     // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
599     // them.
600     if ((Section.find("__OBJC,") == 0) ||
601         (Section.find("__DATA, __objc_") == 0)) {
602       DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
603       return false;
604     }
605     // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
606     // Constant CFString instances are compiled in the following way:
607     //  -- the string buffer is emitted into
608     //     __TEXT,__cstring,cstring_literals
609     //  -- the constant NSConstantString structure referencing that buffer
610     //     is placed into __DATA,__cfstring
611     // Therefore there's no point in placing redzones into __DATA,__cfstring.
612     // Moreover, it causes the linker to crash on OS X 10.7
613     if (Section.find("__DATA,__cfstring") == 0) {
614       DEBUG(dbgs() << "Ignoring CFString: " << *G);
615       return false;
616     }
617   }
618
619   return true;
620 }
621
622 // This function replaces all global variables with new variables that have
623 // trailing redzones. It also creates a function that poisons
624 // redzones and inserts this function into llvm.global_ctors.
625 bool AddressSanitizerModule::runOnModule(Module &M) {
626   if (!ClGlobals) return false;
627   TD = getAnalysisIfAvailable<DataLayout>();
628   if (!TD)
629     return false;
630   BL.reset(new BlackList(BlacklistFile));
631   if (BL->isIn(M)) return false;
632   DynamicallyInitializedGlobals.Init(M);
633   C = &(M.getContext());
634   IntptrTy = Type::getIntNTy(*C, TD->getPointerSizeInBits());
635
636   SmallVector<GlobalVariable *, 16> GlobalsToChange;
637
638   for (Module::GlobalListType::iterator G = M.global_begin(),
639        E = M.global_end(); G != E; ++G) {
640     if (ShouldInstrumentGlobal(G))
641       GlobalsToChange.push_back(G);
642   }
643
644   size_t n = GlobalsToChange.size();
645   if (n == 0) return false;
646
647   // A global is described by a structure
648   //   size_t beg;
649   //   size_t size;
650   //   size_t size_with_redzone;
651   //   const char *name;
652   //   size_t has_dynamic_init;
653   // We initialize an array of such structures and pass it to a run-time call.
654   StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
655                                                IntptrTy, IntptrTy,
656                                                IntptrTy, NULL);
657   SmallVector<Constant *, 16> Initializers(n), DynamicInit;
658
659
660   Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
661   assert(CtorFunc);
662   IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
663
664   // The addresses of the first and last dynamically initialized globals in
665   // this TU.  Used in initialization order checking.
666   Value *FirstDynamic = 0, *LastDynamic = 0;
667
668   for (size_t i = 0; i < n; i++) {
669     GlobalVariable *G = GlobalsToChange[i];
670     PointerType *PtrTy = cast<PointerType>(G->getType());
671     Type *Ty = PtrTy->getElementType();
672     uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
673     size_t RZ = RedzoneSize();
674     uint64_t RightRedzoneSize = RZ + (RZ - (SizeInBytes % RZ));
675     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
676     // Determine whether this global should be poisoned in initialization.
677     bool GlobalHasDynamicInitializer =
678         DynamicallyInitializedGlobals.Contains(G);
679     // Don't check initialization order if this global is blacklisted.
680     GlobalHasDynamicInitializer &= !BL->isInInit(*G);
681
682     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
683     Constant *NewInitializer = ConstantStruct::get(
684         NewTy, G->getInitializer(),
685         Constant::getNullValue(RightRedZoneTy), NULL);
686
687     SmallString<2048> DescriptionOfGlobal = G->getName();
688     DescriptionOfGlobal += " (";
689     DescriptionOfGlobal += M.getModuleIdentifier();
690     DescriptionOfGlobal += ")";
691     GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
692
693     // Create a new global variable with enough space for a redzone.
694     GlobalVariable *NewGlobal = new GlobalVariable(
695         M, NewTy, G->isConstant(), G->getLinkage(),
696         NewInitializer, "", G, G->getThreadLocalMode());
697     NewGlobal->copyAttributesFrom(G);
698     NewGlobal->setAlignment(RZ);
699
700     Value *Indices2[2];
701     Indices2[0] = IRB.getInt32(0);
702     Indices2[1] = IRB.getInt32(0);
703
704     G->replaceAllUsesWith(
705         ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
706     NewGlobal->takeName(G);
707     G->eraseFromParent();
708
709     Initializers[i] = ConstantStruct::get(
710         GlobalStructTy,
711         ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
712         ConstantInt::get(IntptrTy, SizeInBytes),
713         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
714         ConstantExpr::getPointerCast(Name, IntptrTy),
715         ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
716         NULL);
717
718     // Populate the first and last globals declared in this TU.
719     if (CheckInitOrder && GlobalHasDynamicInitializer) {
720       LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
721       if (FirstDynamic == 0)
722         FirstDynamic = LastDynamic;
723     }
724
725     DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
726   }
727
728   ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
729   GlobalVariable *AllGlobals = new GlobalVariable(
730       M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
731       ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
732
733   // Create calls for poisoning before initializers run and unpoisoning after.
734   if (CheckInitOrder && FirstDynamic && LastDynamic)
735     createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
736
737   Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
738       kAsanRegisterGlobalsName, IRB.getVoidTy(),
739       IntptrTy, IntptrTy, NULL));
740   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
741
742   IRB.CreateCall2(AsanRegisterGlobals,
743                   IRB.CreatePointerCast(AllGlobals, IntptrTy),
744                   ConstantInt::get(IntptrTy, n));
745
746   // We also need to unregister globals at the end, e.g. when a shared library
747   // gets closed.
748   Function *AsanDtorFunction = Function::Create(
749       FunctionType::get(Type::getVoidTy(*C), false),
750       GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
751   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
752   IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
753   Function *AsanUnregisterGlobals =
754       checkInterfaceFunction(M.getOrInsertFunction(
755           kAsanUnregisterGlobalsName,
756           IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
757   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
758
759   IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
760                        IRB.CreatePointerCast(AllGlobals, IntptrTy),
761                        ConstantInt::get(IntptrTy, n));
762   appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
763
764   DEBUG(dbgs() << M);
765   return true;
766 }
767
768 void AddressSanitizer::initializeCallbacks(Module &M) {
769   IRBuilder<> IRB(*C);
770   // Create __asan_report* callbacks.
771   for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
772     for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
773          AccessSizeIndex++) {
774       // IsWrite and TypeSize are encoded in the function name.
775       std::string FunctionName = std::string(kAsanReportErrorTemplate) +
776           (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
777       // If we are merging crash callbacks, they have two parameters.
778       AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
779           checkInterfaceFunction(M.getOrInsertFunction(
780               FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
781     }
782   }
783
784   AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
785       kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
786   AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
787       kAsanStackFreeName, IRB.getVoidTy(),
788       IntptrTy, IntptrTy, IntptrTy, NULL));
789   AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
790       kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
791
792   // We insert an empty inline asm after __asan_report* to avoid callback merge.
793   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
794                             StringRef(""), StringRef(""),
795                             /*hasSideEffects=*/true);
796 }
797
798 // virtual
799 bool AddressSanitizer::doInitialization(Module &M) {
800   // Initialize the private fields. No one has accessed them before.
801   TD = getAnalysisIfAvailable<DataLayout>();
802
803   if (!TD)
804     return false;
805   BL.reset(new BlackList(BlacklistFile));
806   DynamicallyInitializedGlobals.Init(M);
807
808   C = &(M.getContext());
809   LongSize = TD->getPointerSizeInBits();
810   IntptrTy = Type::getIntNTy(*C, LongSize);
811   IntptrPtrTy = PointerType::get(IntptrTy, 0);
812
813   AsanCtorFunction = Function::Create(
814       FunctionType::get(Type::getVoidTy(*C), false),
815       GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
816   BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
817   // call __asan_init in the module ctor.
818   IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
819   AsanInitFunction = checkInterfaceFunction(
820       M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
821   AsanInitFunction->setLinkage(Function::ExternalLinkage);
822   IRB.CreateCall(AsanInitFunction);
823
824   llvm::Triple targetTriple(M.getTargetTriple());
825   bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android;
826
827   MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
828     (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
829   if (ClMappingOffsetLog >= 0) {
830     if (ClMappingOffsetLog == 0) {
831       // special case
832       MappingOffset = 0;
833     } else {
834       MappingOffset = 1ULL << ClMappingOffsetLog;
835     }
836   }
837
838
839   if (ClMappingOffsetLog >= 0) {
840     // Tell the run-time the current values of mapping offset and scale.
841     GlobalValue *asan_mapping_offset =
842         new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
843                        ConstantInt::get(IntptrTy, MappingOffset),
844                        kAsanMappingOffsetName);
845     // Read the global, otherwise it may be optimized away.
846     IRB.CreateLoad(asan_mapping_offset, true);
847   }
848   if (ClMappingScale) {
849     GlobalValue *asan_mapping_scale =
850         new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
851                            ConstantInt::get(IntptrTy, MappingScale()),
852                            kAsanMappingScaleName);
853     // Read the global, otherwise it may be optimized away.
854     IRB.CreateLoad(asan_mapping_scale, true);
855   }
856
857   appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
858
859   return true;
860 }
861
862 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
863   // For each NSObject descendant having a +load method, this method is invoked
864   // by the ObjC runtime before any of the static constructors is called.
865   // Therefore we need to instrument such methods with a call to __asan_init
866   // at the beginning in order to initialize our runtime before any access to
867   // the shadow memory.
868   // We cannot just ignore these methods, because they may call other
869   // instrumented functions.
870   if (F.getName().find(" load]") != std::string::npos) {
871     IRBuilder<> IRB(F.begin()->begin());
872     IRB.CreateCall(AsanInitFunction);
873     return true;
874   }
875   return false;
876 }
877
878 bool AddressSanitizer::runOnFunction(Function &F) {
879   if (BL->isIn(F)) return false;
880   if (&F == AsanCtorFunction) return false;
881   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
882   initializeCallbacks(*F.getParent());
883
884   // If needed, insert __asan_init before checking for AddressSafety attr.
885   maybeInsertAsanInitAtFunctionEntry(F);
886
887   if (!F.getFnAttributes().hasAttribute(Attributes::AddressSafety))
888     return false;
889
890   if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
891     return false;
892
893   // We want to instrument every address only once per basic block (unless there
894   // are calls between uses).
895   SmallSet<Value*, 16> TempsToInstrument;
896   SmallVector<Instruction*, 16> ToInstrument;
897   SmallVector<Instruction*, 8> NoReturnCalls;
898   bool IsWrite;
899
900   // Fill the set of memory operations to instrument.
901   for (Function::iterator FI = F.begin(), FE = F.end();
902        FI != FE; ++FI) {
903     TempsToInstrument.clear();
904     int NumInsnsPerBB = 0;
905     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
906          BI != BE; ++BI) {
907       if (LooksLikeCodeInBug11395(BI)) return false;
908       if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
909         if (ClOpt && ClOptSameTemp) {
910           if (!TempsToInstrument.insert(Addr))
911             continue;  // We've seen this temp in the current BB.
912         }
913       } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
914         // ok, take it.
915       } else {
916         if (CallInst *CI = dyn_cast<CallInst>(BI)) {
917           // A call inside BB.
918           TempsToInstrument.clear();
919           if (CI->doesNotReturn()) {
920             NoReturnCalls.push_back(CI);
921           }
922         }
923         continue;
924       }
925       ToInstrument.push_back(BI);
926       NumInsnsPerBB++;
927       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
928         break;
929     }
930   }
931
932   // Instrument.
933   int NumInstrumented = 0;
934   for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
935     Instruction *Inst = ToInstrument[i];
936     if (ClDebugMin < 0 || ClDebugMax < 0 ||
937         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
938       if (isInterestingMemoryAccess(Inst, &IsWrite))
939         instrumentMop(Inst);
940       else
941         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
942     }
943     NumInstrumented++;
944   }
945
946   bool ChangedStack = poisonStackInFunction(F);
947
948   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
949   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
950   for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
951     Instruction *CI = NoReturnCalls[i];
952     IRBuilder<> IRB(CI);
953     IRB.CreateCall(AsanHandleNoReturnFunc);
954   }
955   DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
956
957   return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
958 }
959
960 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
961   if (ShadowRedzoneSize == 1) return PoisonByte;
962   if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
963   if (ShadowRedzoneSize == 4)
964     return (PoisonByte << 24) + (PoisonByte << 16) +
965         (PoisonByte << 8) + (PoisonByte);
966   llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
967 }
968
969 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
970                                             size_t Size,
971                                             size_t RZSize,
972                                             size_t ShadowGranularity,
973                                             uint8_t Magic) {
974   for (size_t i = 0; i < RZSize;
975        i+= ShadowGranularity, Shadow++) {
976     if (i + ShadowGranularity <= Size) {
977       *Shadow = 0;  // fully addressable
978     } else if (i >= Size) {
979       *Shadow = Magic;  // unaddressable
980     } else {
981       *Shadow = Size - i;  // first Size-i bytes are addressable
982     }
983   }
984 }
985
986 void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
987                                    IRBuilder<> IRB,
988                                    Value *ShadowBase, bool DoPoison) {
989   size_t ShadowRZSize = RedzoneSize() >> MappingScale();
990   assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
991   Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
992   Type *RZPtrTy = PointerType::get(RZTy, 0);
993
994   Value *PoisonLeft  = ConstantInt::get(RZTy,
995     ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
996   Value *PoisonMid   = ConstantInt::get(RZTy,
997     ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
998   Value *PoisonRight = ConstantInt::get(RZTy,
999     ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1000
1001   // poison the first red zone.
1002   IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1003
1004   // poison all other red zones.
1005   uint64_t Pos = RedzoneSize();
1006   for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1007     AllocaInst *AI = AllocaVec[i];
1008     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1009     uint64_t AlignedSize = getAlignedAllocaSize(AI);
1010     assert(AlignedSize - SizeInBytes < RedzoneSize());
1011     Value *Ptr = NULL;
1012
1013     Pos += AlignedSize;
1014
1015     assert(ShadowBase->getType() == IntptrTy);
1016     if (SizeInBytes < AlignedSize) {
1017       // Poison the partial redzone at right
1018       Ptr = IRB.CreateAdd(
1019           ShadowBase, ConstantInt::get(IntptrTy,
1020                                        (Pos >> MappingScale()) - ShadowRZSize));
1021       size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
1022       uint32_t Poison = 0;
1023       if (DoPoison) {
1024         PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
1025                                         RedzoneSize(),
1026                                         1ULL << MappingScale(),
1027                                         kAsanStackPartialRedzoneMagic);
1028       }
1029       Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1030       IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1031     }
1032
1033     // Poison the full redzone at right.
1034     Ptr = IRB.CreateAdd(ShadowBase,
1035                         ConstantInt::get(IntptrTy, Pos >> MappingScale()));
1036     Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
1037     IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1038
1039     Pos += RedzoneSize();
1040   }
1041 }
1042
1043 // Workaround for bug 11395: we don't want to instrument stack in functions
1044 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1045 // FIXME: remove once the bug 11395 is fixed.
1046 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1047   if (LongSize != 32) return false;
1048   CallInst *CI = dyn_cast<CallInst>(I);
1049   if (!CI || !CI->isInlineAsm()) return false;
1050   if (CI->getNumArgOperands() <= 5) return false;
1051   // We have inline assembly with quite a few arguments.
1052   return true;
1053 }
1054
1055 // Find all static Alloca instructions and put
1056 // poisoned red zones around all of them.
1057 // Then unpoison everything back before the function returns.
1058 //
1059 // Stack poisoning does not play well with exception handling.
1060 // When an exception is thrown, we essentially bypass the code
1061 // that unpoisones the stack. This is why the run-time library has
1062 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
1063 // stack in the interceptor. This however does not work inside the
1064 // actual function which catches the exception. Most likely because the
1065 // compiler hoists the load of the shadow value somewhere too high.
1066 // This causes asan to report a non-existing bug on 453.povray.
1067 // It sounds like an LLVM bug.
1068 bool AddressSanitizer::poisonStackInFunction(Function &F) {
1069   if (!ClStack) return false;
1070   SmallVector<AllocaInst*, 16> AllocaVec;
1071   SmallVector<Instruction*, 8> RetVec;
1072   uint64_t TotalSize = 0;
1073
1074   // Filter out Alloca instructions we want (and can) handle.
1075   // Collect Ret instructions.
1076   for (Function::iterator FI = F.begin(), FE = F.end();
1077        FI != FE; ++FI) {
1078     BasicBlock &BB = *FI;
1079     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
1080          BI != BE; ++BI) {
1081       if (isa<ReturnInst>(BI)) {
1082           RetVec.push_back(BI);
1083           continue;
1084       }
1085
1086       AllocaInst *AI = dyn_cast<AllocaInst>(BI);
1087       if (!AI) continue;
1088       if (AI->isArrayAllocation()) continue;
1089       if (!AI->isStaticAlloca()) continue;
1090       if (!AI->getAllocatedType()->isSized()) continue;
1091       if (AI->getAlignment() > RedzoneSize()) continue;
1092       AllocaVec.push_back(AI);
1093       uint64_t AlignedSize =  getAlignedAllocaSize(AI);
1094       TotalSize += AlignedSize;
1095     }
1096   }
1097
1098   if (AllocaVec.empty()) return false;
1099
1100   uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize();
1101
1102   bool DoStackMalloc = CheckUseAfterReturn
1103       && LocalStackSize <= kMaxStackMallocSize;
1104
1105   Instruction *InsBefore = AllocaVec[0];
1106   IRBuilder<> IRB(InsBefore);
1107
1108
1109   Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1110   AllocaInst *MyAlloca =
1111       new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1112   MyAlloca->setAlignment(RedzoneSize());
1113   assert(MyAlloca->isStaticAlloca());
1114   Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1115   Value *LocalStackBase = OrigStackBase;
1116
1117   if (DoStackMalloc) {
1118     LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1119         ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1120   }
1121
1122   // This string will be parsed by the run-time (DescribeStackAddress).
1123   SmallString<2048> StackDescriptionStorage;
1124   raw_svector_ostream StackDescription(StackDescriptionStorage);
1125   StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1126
1127   uint64_t Pos = RedzoneSize();
1128   // Replace Alloca instructions with base+offset.
1129   for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1130     AllocaInst *AI = AllocaVec[i];
1131     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1132     StringRef Name = AI->getName();
1133     StackDescription << Pos << " " << SizeInBytes << " "
1134                      << Name.size() << " " << Name << " ";
1135     uint64_t AlignedSize = getAlignedAllocaSize(AI);
1136     assert((AlignedSize % RedzoneSize()) == 0);
1137     AI->replaceAllUsesWith(
1138         IRB.CreateIntToPtr(
1139             IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1140             AI->getType()));
1141     Pos += AlignedSize + RedzoneSize();
1142   }
1143   assert(Pos == LocalStackSize);
1144
1145   // Write the Magic value and the frame description constant to the redzone.
1146   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1147   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1148                   BasePlus0);
1149   Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1150                                    ConstantInt::get(IntptrTy, LongSize/8));
1151   BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1152   GlobalVariable *StackDescriptionGlobal =
1153       createPrivateGlobalForString(*F.getParent(), StackDescription.str());
1154   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
1155   IRB.CreateStore(Description, BasePlus1);
1156
1157   // Poison the stack redzones at the entry.
1158   Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1159   PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1160
1161   // Unpoison the stack before all ret instructions.
1162   for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1163     Instruction *Ret = RetVec[i];
1164     IRBuilder<> IRBRet(Ret);
1165
1166     // Mark the current frame as retired.
1167     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1168                        BasePlus0);
1169     // Unpoison the stack.
1170     PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1171
1172     if (DoStackMalloc) {
1173       IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1174                          ConstantInt::get(IntptrTy, LocalStackSize),
1175                          OrigStackBase);
1176     }
1177   }
1178
1179   // We are done. Remove the old unused alloca instructions.
1180   for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1181     AllocaVec[i]->eraseFromParent();
1182
1183   if (ClDebugStack) {
1184     DEBUG(dbgs() << F);
1185   }
1186
1187   return true;
1188 }