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