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