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