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