[asan] adaptive redzones for globals (the larger the global the larger is the redzone)
[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     static const size_t kMaxGlobalRedzone = 1 << 18;
879     GlobalVariable *G = GlobalsToChange[i];
880     PointerType *PtrTy = cast<PointerType>(G->getType());
881     Type *Ty = PtrTy->getElementType();
882     uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
883     size_t MinRZ = RedzoneSize();
884     // MinRZ <= RZ <= kMaxGlobalRedzone
885     // and trying to make RZ to be ~ 1/4 of SizeInBytes.
886     size_t RZ = std::max(MinRZ,
887                          std::min(kMaxGlobalRedzone,
888                                   (SizeInBytes / MinRZ / 4) * MinRZ));
889     uint64_t RightRedzoneSize = RZ;
890     // Round up to MinRZ
891     if (SizeInBytes % MinRZ)
892       RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
893     assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
894     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
895     // Determine whether this global should be poisoned in initialization.
896     bool GlobalHasDynamicInitializer =
897         DynamicallyInitializedGlobals.Contains(G);
898     // Don't check initialization order if this global is blacklisted.
899     GlobalHasDynamicInitializer &= !BL->isInInit(*G);
900
901     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
902     Constant *NewInitializer = ConstantStruct::get(
903         NewTy, G->getInitializer(),
904         Constant::getNullValue(RightRedZoneTy), NULL);
905
906     SmallString<2048> DescriptionOfGlobal = G->getName();
907     DescriptionOfGlobal += " (";
908     DescriptionOfGlobal += M.getModuleIdentifier();
909     DescriptionOfGlobal += ")";
910     GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
911
912     // Create a new global variable with enough space for a redzone.
913     GlobalVariable *NewGlobal = new GlobalVariable(
914         M, NewTy, G->isConstant(), G->getLinkage(),
915         NewInitializer, "", G, G->getThreadLocalMode());
916     NewGlobal->copyAttributesFrom(G);
917     NewGlobal->setAlignment(MinRZ);
918
919     Value *Indices2[2];
920     Indices2[0] = IRB.getInt32(0);
921     Indices2[1] = IRB.getInt32(0);
922
923     G->replaceAllUsesWith(
924         ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
925     NewGlobal->takeName(G);
926     G->eraseFromParent();
927
928     Initializers[i] = ConstantStruct::get(
929         GlobalStructTy,
930         ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
931         ConstantInt::get(IntptrTy, SizeInBytes),
932         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
933         ConstantExpr::getPointerCast(Name, IntptrTy),
934         ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
935         NULL);
936
937     // Populate the first and last globals declared in this TU.
938     if (CheckInitOrder && GlobalHasDynamicInitializer) {
939       LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
940       if (FirstDynamic == 0)
941         FirstDynamic = LastDynamic;
942     }
943
944     DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
945   }
946
947   ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
948   GlobalVariable *AllGlobals = new GlobalVariable(
949       M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
950       ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
951
952   // Create calls for poisoning before initializers run and unpoisoning after.
953   if (CheckInitOrder && FirstDynamic && LastDynamic)
954     createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
955   IRB.CreateCall2(AsanRegisterGlobals,
956                   IRB.CreatePointerCast(AllGlobals, IntptrTy),
957                   ConstantInt::get(IntptrTy, n));
958
959   // We also need to unregister globals at the end, e.g. when a shared library
960   // gets closed.
961   Function *AsanDtorFunction = Function::Create(
962       FunctionType::get(Type::getVoidTy(*C), false),
963       GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
964   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
965   IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
966   IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
967                        IRB.CreatePointerCast(AllGlobals, IntptrTy),
968                        ConstantInt::get(IntptrTy, n));
969   appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
970
971   DEBUG(dbgs() << M);
972   return true;
973 }
974
975 void AddressSanitizer::initializeCallbacks(Module &M) {
976   IRBuilder<> IRB(*C);
977   // Create __asan_report* callbacks.
978   for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
979     for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
980          AccessSizeIndex++) {
981       // IsWrite and TypeSize are encoded in the function name.
982       std::string FunctionName = std::string(kAsanReportErrorTemplate) +
983           (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
984       // If we are merging crash callbacks, they have two parameters.
985       AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
986           checkInterfaceFunction(M.getOrInsertFunction(
987               FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
988     }
989   }
990
991   AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
992       kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
993   // We insert an empty inline asm after __asan_report* to avoid callback merge.
994   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
995                             StringRef(""), StringRef(""),
996                             /*hasSideEffects=*/true);
997 }
998
999 void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
1000   // Tell the values of mapping offset and scale to the run-time.
1001   GlobalValue *asan_mapping_offset =
1002       new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1003                      ConstantInt::get(IntptrTy, Mapping.Offset),
1004                      kAsanMappingOffsetName);
1005   // Read the global, otherwise it may be optimized away.
1006   IRB.CreateLoad(asan_mapping_offset, true);
1007
1008   GlobalValue *asan_mapping_scale =
1009       new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1010                          ConstantInt::get(IntptrTy, Mapping.Scale),
1011                          kAsanMappingScaleName);
1012   // Read the global, otherwise it may be optimized away.
1013   IRB.CreateLoad(asan_mapping_scale, true);
1014 }
1015
1016 // virtual
1017 bool AddressSanitizer::doInitialization(Module &M) {
1018   // Initialize the private fields. No one has accessed them before.
1019   TD = getAnalysisIfAvailable<DataLayout>();
1020
1021   if (!TD)
1022     return false;
1023   BL.reset(new BlackList(BlacklistFile));
1024   DynamicallyInitializedGlobals.Init(M);
1025
1026   C = &(M.getContext());
1027   LongSize = TD->getPointerSizeInBits();
1028   IntptrTy = Type::getIntNTy(*C, LongSize);
1029
1030   AsanCtorFunction = Function::Create(
1031       FunctionType::get(Type::getVoidTy(*C), false),
1032       GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1033   BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1034   // call __asan_init in the module ctor.
1035   IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1036   AsanInitFunction = checkInterfaceFunction(
1037       M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1038   AsanInitFunction->setLinkage(Function::ExternalLinkage);
1039   IRB.CreateCall(AsanInitFunction);
1040
1041   Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
1042   emitShadowMapping(M, IRB);
1043
1044   appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
1045   return true;
1046 }
1047
1048 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1049   // For each NSObject descendant having a +load method, this method is invoked
1050   // by the ObjC runtime before any of the static constructors is called.
1051   // Therefore we need to instrument such methods with a call to __asan_init
1052   // at the beginning in order to initialize our runtime before any access to
1053   // the shadow memory.
1054   // We cannot just ignore these methods, because they may call other
1055   // instrumented functions.
1056   if (F.getName().find(" load]") != std::string::npos) {
1057     IRBuilder<> IRB(F.begin()->begin());
1058     IRB.CreateCall(AsanInitFunction);
1059     return true;
1060   }
1061   return false;
1062 }
1063
1064 bool AddressSanitizer::runOnFunction(Function &F) {
1065   if (BL->isIn(F)) return false;
1066   if (&F == AsanCtorFunction) return false;
1067   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1068   initializeCallbacks(*F.getParent());
1069
1070   // If needed, insert __asan_init before checking for AddressSafety attr.
1071   maybeInsertAsanInitAtFunctionEntry(F);
1072
1073   if (!F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1074                                       Attribute::AddressSafety))
1075     return false;
1076
1077   if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1078     return false;
1079
1080   // We want to instrument every address only once per basic block (unless there
1081   // are calls between uses).
1082   SmallSet<Value*, 16> TempsToInstrument;
1083   SmallVector<Instruction*, 16> ToInstrument;
1084   SmallVector<Instruction*, 8> NoReturnCalls;
1085   bool IsWrite;
1086
1087   // Fill the set of memory operations to instrument.
1088   for (Function::iterator FI = F.begin(), FE = F.end();
1089        FI != FE; ++FI) {
1090     TempsToInstrument.clear();
1091     int NumInsnsPerBB = 0;
1092     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1093          BI != BE; ++BI) {
1094       if (LooksLikeCodeInBug11395(BI)) return false;
1095       if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
1096         if (ClOpt && ClOptSameTemp) {
1097           if (!TempsToInstrument.insert(Addr))
1098             continue;  // We've seen this temp in the current BB.
1099         }
1100       } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1101         // ok, take it.
1102       } else {
1103         if (CallInst *CI = dyn_cast<CallInst>(BI)) {
1104           // A call inside BB.
1105           TempsToInstrument.clear();
1106           if (CI->doesNotReturn()) {
1107             NoReturnCalls.push_back(CI);
1108           }
1109         }
1110         continue;
1111       }
1112       ToInstrument.push_back(BI);
1113       NumInsnsPerBB++;
1114       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1115         break;
1116     }
1117   }
1118
1119   // Instrument.
1120   int NumInstrumented = 0;
1121   for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1122     Instruction *Inst = ToInstrument[i];
1123     if (ClDebugMin < 0 || ClDebugMax < 0 ||
1124         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1125       if (isInterestingMemoryAccess(Inst, &IsWrite))
1126         instrumentMop(Inst);
1127       else
1128         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1129     }
1130     NumInstrumented++;
1131   }
1132
1133   FunctionStackPoisoner FSP(F, *this);
1134   bool ChangedStack = FSP.runOnFunction();
1135
1136   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1137   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1138   for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1139     Instruction *CI = NoReturnCalls[i];
1140     IRBuilder<> IRB(CI);
1141     IRB.CreateCall(AsanHandleNoReturnFunc);
1142   }
1143   DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
1144
1145   return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1146 }
1147
1148 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1149   if (ShadowRedzoneSize == 1) return PoisonByte;
1150   if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1151   if (ShadowRedzoneSize == 4)
1152     return (PoisonByte << 24) + (PoisonByte << 16) +
1153         (PoisonByte << 8) + (PoisonByte);
1154   llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
1155 }
1156
1157 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1158                                             size_t Size,
1159                                             size_t RZSize,
1160                                             size_t ShadowGranularity,
1161                                             uint8_t Magic) {
1162   for (size_t i = 0; i < RZSize;
1163        i+= ShadowGranularity, Shadow++) {
1164     if (i + ShadowGranularity <= Size) {
1165       *Shadow = 0;  // fully addressable
1166     } else if (i >= Size) {
1167       *Shadow = Magic;  // unaddressable
1168     } else {
1169       *Shadow = Size - i;  // first Size-i bytes are addressable
1170     }
1171   }
1172 }
1173
1174 // Workaround for bug 11395: we don't want to instrument stack in functions
1175 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1176 // FIXME: remove once the bug 11395 is fixed.
1177 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1178   if (LongSize != 32) return false;
1179   CallInst *CI = dyn_cast<CallInst>(I);
1180   if (!CI || !CI->isInlineAsm()) return false;
1181   if (CI->getNumArgOperands() <= 5) return false;
1182   // We have inline assembly with quite a few arguments.
1183   return true;
1184 }
1185
1186 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1187   IRBuilder<> IRB(*C);
1188   AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
1189       kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
1190   AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
1191       kAsanStackFreeName, IRB.getVoidTy(),
1192       IntptrTy, IntptrTy, IntptrTy, NULL));
1193   AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1194       kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1195   AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1196       kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1197 }
1198
1199 void FunctionStackPoisoner::poisonRedZones(
1200   const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
1201   bool DoPoison) {
1202   size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
1203   assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1204   Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1205   Type *RZPtrTy = PointerType::get(RZTy, 0);
1206
1207   Value *PoisonLeft  = ConstantInt::get(RZTy,
1208     ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1209   Value *PoisonMid   = ConstantInt::get(RZTy,
1210     ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1211   Value *PoisonRight = ConstantInt::get(RZTy,
1212     ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1213
1214   // poison the first red zone.
1215   IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1216
1217   // poison all other red zones.
1218   uint64_t Pos = RedzoneSize();
1219   for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1220     AllocaInst *AI = AllocaVec[i];
1221     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1222     uint64_t AlignedSize = getAlignedAllocaSize(AI);
1223     assert(AlignedSize - SizeInBytes < RedzoneSize());
1224     Value *Ptr = NULL;
1225
1226     Pos += AlignedSize;
1227
1228     assert(ShadowBase->getType() == IntptrTy);
1229     if (SizeInBytes < AlignedSize) {
1230       // Poison the partial redzone at right
1231       Ptr = IRB.CreateAdd(
1232           ShadowBase, ConstantInt::get(IntptrTy,
1233                                        (Pos >> Mapping.Scale) - ShadowRZSize));
1234       size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
1235       uint32_t Poison = 0;
1236       if (DoPoison) {
1237         PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
1238                                         RedzoneSize(),
1239                                         1ULL << Mapping.Scale,
1240                                         kAsanStackPartialRedzoneMagic);
1241       }
1242       Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1243       IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1244     }
1245
1246     // Poison the full redzone at right.
1247     Ptr = IRB.CreateAdd(ShadowBase,
1248                         ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
1249     bool LastAlloca = (i == AllocaVec.size() - 1);
1250     Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
1251     IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1252
1253     Pos += RedzoneSize();
1254   }
1255 }
1256
1257 void FunctionStackPoisoner::poisonStack() {
1258   uint64_t LocalStackSize = TotalStackSize +
1259                             (AllocaVec.size() + 1) * RedzoneSize();
1260
1261   bool DoStackMalloc = ASan.CheckUseAfterReturn
1262       && LocalStackSize <= kMaxStackMallocSize;
1263
1264   assert(AllocaVec.size() > 0);
1265   Instruction *InsBefore = AllocaVec[0];
1266   IRBuilder<> IRB(InsBefore);
1267
1268
1269   Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1270   AllocaInst *MyAlloca =
1271       new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1272   if (ClRealignStack && StackAlignment < RedzoneSize())
1273     StackAlignment = RedzoneSize();
1274   MyAlloca->setAlignment(StackAlignment);
1275   assert(MyAlloca->isStaticAlloca());
1276   Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1277   Value *LocalStackBase = OrigStackBase;
1278
1279   if (DoStackMalloc) {
1280     LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1281         ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1282   }
1283
1284   // This string will be parsed by the run-time (DescribeStackAddress).
1285   SmallString<2048> StackDescriptionStorage;
1286   raw_svector_ostream StackDescription(StackDescriptionStorage);
1287   StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1288
1289   // Insert poison calls for lifetime intrinsics for alloca.
1290   bool HavePoisonedAllocas = false;
1291   for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1292     const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1293     IntrinsicInst *II = APC.InsBefore;
1294     AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1295     assert(AI);
1296     IRBuilder<> IRB(II);
1297     poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1298     HavePoisonedAllocas |= APC.DoPoison;
1299   }
1300
1301   uint64_t Pos = RedzoneSize();
1302   // Replace Alloca instructions with base+offset.
1303   for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1304     AllocaInst *AI = AllocaVec[i];
1305     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1306     StringRef Name = AI->getName();
1307     StackDescription << Pos << " " << SizeInBytes << " "
1308                      << Name.size() << " " << Name << " ";
1309     uint64_t AlignedSize = getAlignedAllocaSize(AI);
1310     assert((AlignedSize % RedzoneSize()) == 0);
1311     Value *NewAllocaPtr = IRB.CreateIntToPtr(
1312             IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1313             AI->getType());
1314     replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1315     AI->replaceAllUsesWith(NewAllocaPtr);
1316     Pos += AlignedSize + RedzoneSize();
1317   }
1318   assert(Pos == LocalStackSize);
1319
1320   // Write the Magic value and the frame description constant to the redzone.
1321   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1322   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1323                   BasePlus0);
1324   Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1325                                    ConstantInt::get(IntptrTy,
1326                                                     ASan.LongSize/8));
1327   BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1328   GlobalVariable *StackDescriptionGlobal =
1329       createPrivateGlobalForString(*F.getParent(), StackDescription.str());
1330   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1331                                              IntptrTy);
1332   IRB.CreateStore(Description, BasePlus1);
1333
1334   // Poison the stack redzones at the entry.
1335   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1336   poisonRedZones(AllocaVec, IRB, ShadowBase, true);
1337
1338   // Unpoison the stack before all ret instructions.
1339   for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1340     Instruction *Ret = RetVec[i];
1341     IRBuilder<> IRBRet(Ret);
1342     // Mark the current frame as retired.
1343     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1344                        BasePlus0);
1345     // Unpoison the stack.
1346     poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
1347     if (DoStackMalloc) {
1348       // In use-after-return mode, mark the whole stack frame unaddressable.
1349       IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1350                          ConstantInt::get(IntptrTy, LocalStackSize),
1351                          OrigStackBase);
1352     } else if (HavePoisonedAllocas) {
1353       // If we poisoned some allocas in llvm.lifetime analysis,
1354       // unpoison whole stack frame now.
1355       assert(LocalStackBase == OrigStackBase);
1356       poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1357     }
1358   }
1359
1360   // We are done. Remove the old unused alloca instructions.
1361   for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1362     AllocaVec[i]->eraseFromParent();
1363 }
1364
1365 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1366                                          IRBuilder<> IRB, bool DoPoison) {
1367   // For now just insert the call to ASan runtime.
1368   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1369   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1370   IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1371                            : AsanUnpoisonStackMemoryFunc,
1372                   AddrArg, SizeArg);
1373 }
1374
1375 // Handling llvm.lifetime intrinsics for a given %alloca:
1376 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1377 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1378 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1379 //     could be poisoned by previous llvm.lifetime.end instruction, as the
1380 //     variable may go in and out of scope several times, e.g. in loops).
1381 // (3) if we poisoned at least one %alloca in a function,
1382 //     unpoison the whole stack frame at function exit.
1383
1384 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1385   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1386     // We're intested only in allocas we can handle.
1387     return isInterestingAlloca(*AI) ? AI : 0;
1388   // See if we've already calculated (or started to calculate) alloca for a
1389   // given value.
1390   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1391   if (I != AllocaForValue.end())
1392     return I->second;
1393   // Store 0 while we're calculating alloca for value V to avoid
1394   // infinite recursion if the value references itself.
1395   AllocaForValue[V] = 0;
1396   AllocaInst *Res = 0;
1397   if (CastInst *CI = dyn_cast<CastInst>(V))
1398     Res = findAllocaForValue(CI->getOperand(0));
1399   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1400     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1401       Value *IncValue = PN->getIncomingValue(i);
1402       // Allow self-referencing phi-nodes.
1403       if (IncValue == PN) continue;
1404       AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1405       // AI for incoming values should exist and should all be equal.
1406       if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1407         return 0;
1408       Res = IncValueAI;
1409     }
1410   }
1411   if (Res != 0)
1412     AllocaForValue[V] = Res;
1413   return Res;
1414 }