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