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