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