[ASan/Win] Fix issue 305 -- don't instrument .CRT initializer/terminator callbacks
[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 #include "llvm/Transforms/Instrumentation.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DepthFirstIterator.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/IR/CallSite.h"
27 #include "llvm/IR/DIBuilder.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/InlineAsm.h"
32 #include "llvm/IR/InstVisitor.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/MDBuilder.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/DataTypes.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Endian.h"
42 #include "llvm/Support/system_error.h"
43 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Cloning.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Transforms/Utils/ModuleUtils.h"
48 #include "llvm/Transforms/Utils/SpecialCaseList.h"
49 #include <algorithm>
50 #include <string>
51
52 using namespace llvm;
53
54 #define DEBUG_TYPE "asan"
55
56 static const uint64_t kDefaultShadowScale = 3;
57 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
58 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
59 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
60 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000;  // < 2G.
61 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
62 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
63 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
64 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
65
66 static const size_t kMinStackMallocSize = 1 << 6;  // 64B
67 static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
68 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
69 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
70
71 static const char *const kAsanModuleCtorName = "asan.module_ctor";
72 static const char *const kAsanModuleDtorName = "asan.module_dtor";
73 static const int         kAsanCtorAndCtorPriority = 1;
74 static const char *const kAsanReportErrorTemplate = "__asan_report_";
75 static const char *const kAsanReportLoadN = "__asan_report_load_n";
76 static const char *const kAsanReportStoreN = "__asan_report_store_n";
77 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
78 static const char *const kAsanUnregisterGlobalsName =
79     "__asan_unregister_globals";
80 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
81 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
82 static const char *const kAsanInitName = "__asan_init_v3";
83 static const char *const kAsanCovName = "__sanitizer_cov";
84 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
85 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
86 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
87 static const int         kMaxAsanStackMallocSizeClass = 10;
88 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
89 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
90 static const char *const kAsanGenPrefix = "__asan_gen_";
91 static const char *const kAsanPoisonStackMemoryName =
92     "__asan_poison_stack_memory";
93 static const char *const kAsanUnpoisonStackMemoryName =
94     "__asan_unpoison_stack_memory";
95
96 static const char *const kAsanOptionDetectUAR =
97     "__asan_option_detect_stack_use_after_return";
98
99 #ifndef NDEBUG
100 static const int kAsanStackAfterReturnMagic = 0xf5;
101 #endif
102
103 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
104 static const size_t kNumberOfAccessSizes = 5;
105
106 // Command-line flags.
107
108 // This flag may need to be replaced with -f[no-]asan-reads.
109 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
110        cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
111 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
112        cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
113 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
114        cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
115        cl::Hidden, cl::init(true));
116 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
117        cl::desc("use instrumentation with slow path for all accesses"),
118        cl::Hidden, cl::init(false));
119 // This flag limits the number of instructions to be instrumented
120 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
121 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
122 // set it to 10000.
123 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
124        cl::init(10000),
125        cl::desc("maximal number of instructions to instrument in any given BB"),
126        cl::Hidden);
127 // This flag may need to be replaced with -f[no]asan-stack.
128 static cl::opt<bool> ClStack("asan-stack",
129        cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
130 // This flag may need to be replaced with -f[no]asan-use-after-return.
131 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
132        cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
133 // This flag may need to be replaced with -f[no]asan-globals.
134 static cl::opt<bool> ClGlobals("asan-globals",
135        cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
136 static cl::opt<int> ClCoverage("asan-coverage",
137        cl::desc("ASan coverage. 0: none, 1: entry block, 2: all blocks"),
138        cl::Hidden, cl::init(false));
139 static cl::opt<int> ClCoverageBlockThreshold("asan-coverage-block-threshold",
140        cl::desc("Add coverage instrumentation only to the entry block if there "
141                 "are more than this number of blocks."),
142        cl::Hidden, cl::init(1500));
143 static cl::opt<bool> ClInitializers("asan-initialization-order",
144        cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
145 static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
146        cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
147        cl::Hidden, cl::init(false));
148 static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
149        cl::desc("Realign stack to the value of this flag (power of two)"),
150        cl::Hidden, cl::init(32));
151 static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
152        cl::desc("File containing the list of objects to ignore "
153                 "during instrumentation"), cl::Hidden);
154 static cl::opt<int> ClInstrumentationWithCallsThreshold(
155     "asan-instrumentation-with-call-threshold",
156        cl::desc("If the function being instrumented contains more than "
157                 "this number of memory accesses, use callbacks instead of "
158                 "inline checks (-1 means never use callbacks)."),
159        cl::Hidden, cl::init(10000));
160 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
161        "asan-memory-access-callback-prefix",
162        cl::desc("Prefix for memory access callbacks"), cl::Hidden,
163        cl::init("__asan_"));
164
165 // This is an experimental feature that will allow to choose between
166 // instrumented and non-instrumented code at link-time.
167 // If this option is on, just before instrumenting a function we create its
168 // clone; if the function is not changed by asan the clone is deleted.
169 // If we end up with a clone, we put the instrumented function into a section
170 // called "ASAN" and the uninstrumented function into a section called "NOASAN".
171 //
172 // This is still a prototype, we need to figure out a way to keep two copies of
173 // a function so that the linker can easily choose one of them.
174 static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
175        cl::desc("Keep uninstrumented copies of functions"),
176        cl::Hidden, cl::init(false));
177
178 // These flags allow to change the shadow mapping.
179 // The shadow mapping looks like
180 //    Shadow = (Mem >> scale) + (1 << offset_log)
181 static cl::opt<int> ClMappingScale("asan-mapping-scale",
182        cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
183
184 // Optimization flags. Not user visible, used mostly for testing
185 // and benchmarking the tool.
186 static cl::opt<bool> ClOpt("asan-opt",
187        cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
188 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
189        cl::desc("Instrument the same temp just once"), cl::Hidden,
190        cl::init(true));
191 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
192        cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
193
194 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
195        cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
196        cl::Hidden, cl::init(false));
197
198 // Debug flags.
199 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
200                             cl::init(0));
201 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
202                                  cl::Hidden, cl::init(0));
203 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
204                                         cl::Hidden, cl::desc("Debug func"));
205 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
206                                cl::Hidden, cl::init(-1));
207 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
208                                cl::Hidden, cl::init(-1));
209
210 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
211 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
212 STATISTIC(NumOptimizedAccessesToGlobalArray,
213           "Number of optimized accesses to global arrays");
214 STATISTIC(NumOptimizedAccessesToGlobalVar,
215           "Number of optimized accesses to global vars");
216
217 namespace {
218 /// A set of dynamically initialized globals extracted from metadata.
219 class SetOfDynamicallyInitializedGlobals {
220  public:
221   void Init(Module& M) {
222     // Clang generates metadata identifying all dynamically initialized globals.
223     NamedMDNode *DynamicGlobals =
224         M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
225     if (!DynamicGlobals)
226       return;
227     for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
228       MDNode *MDN = DynamicGlobals->getOperand(i);
229       assert(MDN->getNumOperands() == 1);
230       Value *VG = MDN->getOperand(0);
231       // The optimizer may optimize away a global entirely, in which case we
232       // cannot instrument access to it.
233       if (!VG)
234         continue;
235       DynInitGlobals.insert(cast<GlobalVariable>(VG));
236     }
237   }
238   bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
239  private:
240   SmallSet<GlobalValue*, 32> DynInitGlobals;
241 };
242
243 /// This struct defines the shadow mapping using the rule:
244 ///   shadow = (mem >> Scale) ADD-or-OR Offset.
245 struct ShadowMapping {
246   int Scale;
247   uint64_t Offset;
248   bool OrShadowOffset;
249 };
250
251 static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
252   llvm::Triple TargetTriple(M.getTargetTriple());
253   bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
254   bool IsIOS = TargetTriple.getOS() == llvm::Triple::IOS;
255   bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
256   bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
257   bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
258                  TargetTriple.getArch() == llvm::Triple::ppc64le;
259   bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
260   bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
261                   TargetTriple.getArch() == llvm::Triple::mipsel;
262
263   ShadowMapping Mapping;
264
265   if (LongSize == 32) {
266     if (IsAndroid)
267       Mapping.Offset = 0;
268     else if (IsMIPS32)
269       Mapping.Offset = kMIPS32_ShadowOffset32;
270     else if (IsFreeBSD)
271       Mapping.Offset = kFreeBSD_ShadowOffset32;
272     else if (IsIOS)
273       Mapping.Offset = kIOSShadowOffset32;
274     else
275       Mapping.Offset = kDefaultShadowOffset32;
276   } else {  // LongSize == 64
277     if (IsPPC64)
278       Mapping.Offset = kPPC64_ShadowOffset64;
279     else if (IsFreeBSD)
280       Mapping.Offset = kFreeBSD_ShadowOffset64;
281     else if (IsLinux && IsX86_64)
282       Mapping.Offset = kSmallX86_64ShadowOffset;
283     else
284       Mapping.Offset = kDefaultShadowOffset64;
285   }
286
287   Mapping.Scale = kDefaultShadowScale;
288   if (ClMappingScale) {
289     Mapping.Scale = ClMappingScale;
290   }
291
292   // OR-ing shadow offset if more efficient (at least on x86) if the offset
293   // is a power of two, but on ppc64 we have to use add since the shadow
294   // offset is not necessary 1/8-th of the address space.
295   Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
296
297   return Mapping;
298 }
299
300 static size_t RedzoneSizeForScale(int MappingScale) {
301   // Redzone used for stack and globals is at least 32 bytes.
302   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
303   return std::max(32U, 1U << MappingScale);
304 }
305
306 /// AddressSanitizer: instrument the code in module to find memory bugs.
307 struct AddressSanitizer : public FunctionPass {
308   AddressSanitizer(bool CheckInitOrder = true,
309                    bool CheckUseAfterReturn = false,
310                    bool CheckLifetime = false,
311                    StringRef BlacklistFile = StringRef())
312       : FunctionPass(ID),
313         CheckInitOrder(CheckInitOrder || ClInitializers),
314         CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
315         CheckLifetime(CheckLifetime || ClCheckLifetime),
316         BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
317                                             : BlacklistFile) {}
318   const char *getPassName() const override {
319     return "AddressSanitizerFunctionPass";
320   }
321   void instrumentMop(Instruction *I, bool UseCalls);
322   void instrumentPointerComparisonOrSubtraction(Instruction *I);
323   void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
324                          Value *Addr, uint32_t TypeSize, bool IsWrite,
325                          Value *SizeArgument, bool UseCalls);
326   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
327                            Value *ShadowValue, uint32_t TypeSize);
328   Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
329                                  bool IsWrite, size_t AccessSizeIndex,
330                                  Value *SizeArgument);
331   void instrumentMemIntrinsic(MemIntrinsic *MI);
332   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
333   bool runOnFunction(Function &F) override;
334   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
335   bool doInitialization(Module &M) override;
336   static char ID;  // Pass identification, replacement for typeid
337
338  private:
339   void initializeCallbacks(Module &M);
340
341   bool LooksLikeCodeInBug11395(Instruction *I);
342   bool GlobalIsLinkerInitialized(GlobalVariable *G);
343   bool InjectCoverage(Function &F, const ArrayRef<BasicBlock*> AllBlocks);
344   void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
345
346   bool CheckInitOrder;
347   bool CheckUseAfterReturn;
348   bool CheckLifetime;
349   SmallString<64> BlacklistFile;
350
351   LLVMContext *C;
352   const DataLayout *DL;
353   int LongSize;
354   Type *IntptrTy;
355   ShadowMapping Mapping;
356   Function *AsanCtorFunction;
357   Function *AsanInitFunction;
358   Function *AsanHandleNoReturnFunc;
359   Function *AsanCovFunction;
360   Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
361   std::unique_ptr<SpecialCaseList> BL;
362   // This array is indexed by AccessIsWrite and log2(AccessSize).
363   Function *AsanErrorCallback[2][kNumberOfAccessSizes];
364   Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
365   // This array is indexed by AccessIsWrite.
366   Function *AsanErrorCallbackSized[2],
367            *AsanMemoryAccessCallbackSized[2];
368   Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
369   InlineAsm *EmptyAsm;
370   SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
371
372   friend struct FunctionStackPoisoner;
373 };
374
375 class AddressSanitizerModule : public ModulePass {
376  public:
377   AddressSanitizerModule(bool CheckInitOrder = true,
378                          StringRef BlacklistFile = StringRef())
379       : ModulePass(ID),
380         CheckInitOrder(CheckInitOrder || ClInitializers),
381         BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
382                                             : BlacklistFile) {}
383   bool runOnModule(Module &M) override;
384   static char ID;  // Pass identification, replacement for typeid
385   const char *getPassName() const override {
386     return "AddressSanitizerModule";
387   }
388
389  private:
390   void initializeCallbacks(Module &M);
391
392   bool ShouldInstrumentGlobal(GlobalVariable *G);
393   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
394   size_t MinRedzoneSizeForGlobal() const {
395     return RedzoneSizeForScale(Mapping.Scale);
396   }
397
398   bool CheckInitOrder;
399   SmallString<64> BlacklistFile;
400
401   std::unique_ptr<SpecialCaseList> BL;
402   SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
403   Type *IntptrTy;
404   LLVMContext *C;
405   const DataLayout *DL;
406   ShadowMapping Mapping;
407   Function *AsanPoisonGlobals;
408   Function *AsanUnpoisonGlobals;
409   Function *AsanRegisterGlobals;
410   Function *AsanUnregisterGlobals;
411 };
412
413 // Stack poisoning does not play well with exception handling.
414 // When an exception is thrown, we essentially bypass the code
415 // that unpoisones the stack. This is why the run-time library has
416 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
417 // stack in the interceptor. This however does not work inside the
418 // actual function which catches the exception. Most likely because the
419 // compiler hoists the load of the shadow value somewhere too high.
420 // This causes asan to report a non-existing bug on 453.povray.
421 // It sounds like an LLVM bug.
422 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
423   Function &F;
424   AddressSanitizer &ASan;
425   DIBuilder DIB;
426   LLVMContext *C;
427   Type *IntptrTy;
428   Type *IntptrPtrTy;
429   ShadowMapping Mapping;
430
431   SmallVector<AllocaInst*, 16> AllocaVec;
432   SmallVector<Instruction*, 8> RetVec;
433   unsigned StackAlignment;
434
435   Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
436            *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
437   Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
438
439   // Stores a place and arguments of poisoning/unpoisoning call for alloca.
440   struct AllocaPoisonCall {
441     IntrinsicInst *InsBefore;
442     AllocaInst *AI;
443     uint64_t Size;
444     bool DoPoison;
445   };
446   SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
447
448   // Maps Value to an AllocaInst from which the Value is originated.
449   typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
450   AllocaForValueMapTy AllocaForValue;
451
452   FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
453       : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
454         IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
455         Mapping(ASan.Mapping),
456         StackAlignment(1 << Mapping.Scale) {}
457
458   bool runOnFunction() {
459     if (!ClStack) return false;
460     // Collect alloca, ret, lifetime instructions etc.
461     for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
462       visit(*BB);
463
464     if (AllocaVec.empty()) return false;
465
466     initializeCallbacks(*F.getParent());
467
468     poisonStack();
469
470     if (ClDebugStack) {
471       DEBUG(dbgs() << F);
472     }
473     return true;
474   }
475
476   // Finds all static Alloca instructions and puts
477   // poisoned red zones around all of them.
478   // Then unpoison everything back before the function returns.
479   void poisonStack();
480
481   // ----------------------- Visitors.
482   /// \brief Collect all Ret instructions.
483   void visitReturnInst(ReturnInst &RI) {
484     RetVec.push_back(&RI);
485   }
486
487   /// \brief Collect Alloca instructions we want (and can) handle.
488   void visitAllocaInst(AllocaInst &AI) {
489     if (!isInterestingAlloca(AI)) return;
490
491     StackAlignment = std::max(StackAlignment, AI.getAlignment());
492     AllocaVec.push_back(&AI);
493   }
494
495   /// \brief Collect lifetime intrinsic calls to check for use-after-scope
496   /// errors.
497   void visitIntrinsicInst(IntrinsicInst &II) {
498     if (!ASan.CheckLifetime) return;
499     Intrinsic::ID ID = II.getIntrinsicID();
500     if (ID != Intrinsic::lifetime_start &&
501         ID != Intrinsic::lifetime_end)
502       return;
503     // Found lifetime intrinsic, add ASan instrumentation if necessary.
504     ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
505     // If size argument is undefined, don't do anything.
506     if (Size->isMinusOne()) return;
507     // Check that size doesn't saturate uint64_t and can
508     // be stored in IntptrTy.
509     const uint64_t SizeValue = Size->getValue().getLimitedValue();
510     if (SizeValue == ~0ULL ||
511         !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
512       return;
513     // Find alloca instruction that corresponds to llvm.lifetime argument.
514     AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
515     if (!AI) return;
516     bool DoPoison = (ID == Intrinsic::lifetime_end);
517     AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
518     AllocaPoisonCallVec.push_back(APC);
519   }
520
521   // ---------------------- Helpers.
522   void initializeCallbacks(Module &M);
523
524   // Check if we want (and can) handle this alloca.
525   bool isInterestingAlloca(AllocaInst &AI) const {
526     return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
527             AI.getAllocatedType()->isSized() &&
528             // alloca() may be called with 0 size, ignore it.
529             getAllocaSizeInBytes(&AI) > 0);
530   }
531
532   uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
533     Type *Ty = AI->getAllocatedType();
534     uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
535     return SizeInBytes;
536   }
537   /// Finds alloca where the value comes from.
538   AllocaInst *findAllocaForValue(Value *V);
539   void poisonRedZones(const ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
540                       Value *ShadowBase, bool DoPoison);
541   void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
542
543   void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
544                                           int Size);
545 };
546
547 }  // namespace
548
549 char AddressSanitizer::ID = 0;
550 INITIALIZE_PASS(AddressSanitizer, "asan",
551     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
552     false, false)
553 FunctionPass *llvm::createAddressSanitizerFunctionPass(
554     bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
555     StringRef BlacklistFile) {
556   return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
557                               CheckLifetime, BlacklistFile);
558 }
559
560 char AddressSanitizerModule::ID = 0;
561 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
562     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
563     "ModulePass", false, false)
564 ModulePass *llvm::createAddressSanitizerModulePass(
565     bool CheckInitOrder, StringRef BlacklistFile) {
566   return new AddressSanitizerModule(CheckInitOrder, BlacklistFile);
567 }
568
569 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
570   size_t Res = countTrailingZeros(TypeSize / 8);
571   assert(Res < kNumberOfAccessSizes);
572   return Res;
573 }
574
575 // \brief Create a constant for Str so that we can pass it to the run-time lib.
576 static GlobalVariable *createPrivateGlobalForString(
577     Module &M, StringRef Str, bool AllowMerging) {
578   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
579   // We use private linkage for module-local strings. If they can be merged
580   // with another one, we set the unnamed_addr attribute.
581   GlobalVariable *GV =
582       new GlobalVariable(M, StrConst->getType(), true,
583                          GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
584   if (AllowMerging)
585     GV->setUnnamedAddr(true);
586   GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
587   return GV;
588 }
589
590 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
591   return G->getName().find(kAsanGenPrefix) == 0;
592 }
593
594 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
595   // Shadow >> scale
596   Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
597   if (Mapping.Offset == 0)
598     return Shadow;
599   // (Shadow >> scale) | offset
600   if (Mapping.OrShadowOffset)
601     return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
602   else
603     return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
604 }
605
606 // Instrument memset/memmove/memcpy
607 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
608   IRBuilder<> IRB(MI);
609   Instruction *Call = nullptr;
610   if (isa<MemTransferInst>(MI)) {
611     Call = IRB.CreateCall3(
612         isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
613         IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
614         IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
615         IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
616   } else if (isa<MemSetInst>(MI)) {
617     Call = IRB.CreateCall3(
618         AsanMemset,
619         IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
620         IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
621         IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
622   }
623   Call->setDebugLoc(MI->getDebugLoc());
624   MI->eraseFromParent();
625 }
626
627 // If I is an interesting memory access, return the PointerOperand
628 // and set IsWrite. Otherwise return NULL.
629 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
630   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
631     if (!ClInstrumentReads) return nullptr;
632     *IsWrite = false;
633     return LI->getPointerOperand();
634   }
635   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
636     if (!ClInstrumentWrites) return nullptr;
637     *IsWrite = true;
638     return SI->getPointerOperand();
639   }
640   if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
641     if (!ClInstrumentAtomics) return nullptr;
642     *IsWrite = true;
643     return RMW->getPointerOperand();
644   }
645   if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
646     if (!ClInstrumentAtomics) return nullptr;
647     *IsWrite = true;
648     return XCHG->getPointerOperand();
649   }
650   return nullptr;
651 }
652
653 static bool isPointerOperand(Value *V) {
654   return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
655 }
656
657 // This is a rough heuristic; it may cause both false positives and
658 // false negatives. The proper implementation requires cooperation with
659 // the frontend.
660 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
661   if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
662     if (!Cmp->isRelational())
663       return false;
664   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
665     if (BO->getOpcode() != Instruction::Sub)
666       return false;
667   } else {
668     return false;
669   }
670   if (!isPointerOperand(I->getOperand(0)) ||
671       !isPointerOperand(I->getOperand(1)))
672       return false;
673   return true;
674 }
675
676 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
677   // If a global variable does not have dynamic initialization we don't
678   // have to instrument it.  However, if a global does not have initializer
679   // at all, we assume it has dynamic initializer (in other TU).
680   return G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G);
681 }
682
683 void
684 AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
685   IRBuilder<> IRB(I);
686   Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
687   Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
688   for (int i = 0; i < 2; i++) {
689     if (Param[i]->getType()->isPointerTy())
690       Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
691   }
692   IRB.CreateCall2(F, Param[0], Param[1]);
693 }
694
695 void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
696   bool IsWrite = false;
697   Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
698   assert(Addr);
699   if (ClOpt && ClOptGlobals) {
700     if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
701       // If initialization order checking is disabled, a simple access to a
702       // dynamically initialized global is always valid.
703       if (!CheckInitOrder || GlobalIsLinkerInitialized(G)) {
704         NumOptimizedAccessesToGlobalVar++;
705         return;
706       }
707     }
708     ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
709     if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
710       if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
711         if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
712           NumOptimizedAccessesToGlobalArray++;
713           return;
714         }
715       }
716     }
717   }
718
719   Type *OrigPtrTy = Addr->getType();
720   Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
721
722   assert(OrigTy->isSized());
723   uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
724
725   assert((TypeSize % 8) == 0);
726
727   if (IsWrite)
728     NumInstrumentedWrites++;
729   else
730     NumInstrumentedReads++;
731
732   // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
733   if (TypeSize == 8  || TypeSize == 16 ||
734       TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
735     return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
736   // Instrument unusual size (but still multiple of 8).
737   // We can not do it with a single check, so we do 1-byte check for the first
738   // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
739   // to report the actual access size.
740   IRBuilder<> IRB(I);
741   Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
742   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
743   if (UseCalls) {
744     CallInst *Check =
745         IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
746     Check->setDebugLoc(I->getDebugLoc());
747   } else {
748     Value *LastByte = IRB.CreateIntToPtr(
749         IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
750         OrigPtrTy);
751     instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
752     instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
753   }
754 }
755
756 // Validate the result of Module::getOrInsertFunction called for an interface
757 // function of AddressSanitizer. If the instrumented module defines a function
758 // with the same name, their prototypes must match, otherwise
759 // getOrInsertFunction returns a bitcast.
760 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
761   if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
762   FuncOrBitcast->dump();
763   report_fatal_error("trying to redefine an AddressSanitizer "
764                      "interface function");
765 }
766
767 Instruction *AddressSanitizer::generateCrashCode(
768     Instruction *InsertBefore, Value *Addr,
769     bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
770   IRBuilder<> IRB(InsertBefore);
771   CallInst *Call = SizeArgument
772     ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
773     : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
774
775   // We don't do Call->setDoesNotReturn() because the BB already has
776   // UnreachableInst at the end.
777   // This EmptyAsm is required to avoid callback merge.
778   IRB.CreateCall(EmptyAsm);
779   return Call;
780 }
781
782 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
783                                             Value *ShadowValue,
784                                             uint32_t TypeSize) {
785   size_t Granularity = 1 << Mapping.Scale;
786   // Addr & (Granularity - 1)
787   Value *LastAccessedByte = IRB.CreateAnd(
788       AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
789   // (Addr & (Granularity - 1)) + size - 1
790   if (TypeSize / 8 > 1)
791     LastAccessedByte = IRB.CreateAdd(
792         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
793   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
794   LastAccessedByte = IRB.CreateIntCast(
795       LastAccessedByte, ShadowValue->getType(), false);
796   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
797   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
798 }
799
800 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
801                                          Instruction *InsertBefore, Value *Addr,
802                                          uint32_t TypeSize, bool IsWrite,
803                                          Value *SizeArgument, bool UseCalls) {
804   IRBuilder<> IRB(InsertBefore);
805   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
806   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
807
808   if (UseCalls) {
809     IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
810                    AddrLong);
811     return;
812   }
813
814   Type *ShadowTy  = IntegerType::get(
815       *C, std::max(8U, TypeSize >> Mapping.Scale));
816   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
817   Value *ShadowPtr = memToShadow(AddrLong, IRB);
818   Value *CmpVal = Constant::getNullValue(ShadowTy);
819   Value *ShadowValue = IRB.CreateLoad(
820       IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
821
822   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
823   size_t Granularity = 1 << Mapping.Scale;
824   TerminatorInst *CrashTerm = nullptr;
825
826   if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
827     TerminatorInst *CheckTerm =
828         SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
829     assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
830     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
831     IRB.SetInsertPoint(CheckTerm);
832     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
833     BasicBlock *CrashBlock =
834         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
835     CrashTerm = new UnreachableInst(*C, CrashBlock);
836     BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
837     ReplaceInstWithInst(CheckTerm, NewTerm);
838   } else {
839     CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
840   }
841
842   Instruction *Crash = generateCrashCode(
843       CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
844   Crash->setDebugLoc(OrigIns->getDebugLoc());
845 }
846
847 void AddressSanitizerModule::createInitializerPoisonCalls(
848     Module &M, GlobalValue *ModuleName) {
849   // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
850   Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
851   // If that function is not present, this TU contains no globals, or they have
852   // all been optimized away
853   if (!GlobalInit)
854     return;
855
856   // Set up the arguments to our poison/unpoison functions.
857   IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
858
859   // Add a call to poison all external globals before the given function starts.
860   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
861   IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
862
863   // Add calls to unpoison all globals before each return instruction.
864   for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
865       I != E; ++I) {
866     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
867       CallInst::Create(AsanUnpoisonGlobals, "", RI);
868     }
869   }
870 }
871
872 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
873   Type *Ty = cast<PointerType>(G->getType())->getElementType();
874   DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
875
876   if (BL->isIn(*G)) return false;
877   if (!Ty->isSized()) return false;
878   if (!G->hasInitializer()) return false;
879   if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
880   // Touch only those globals that will not be defined in other modules.
881   // Don't handle ODR type linkages since other modules may be built w/o asan.
882   if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
883       G->getLinkage() != GlobalVariable::PrivateLinkage &&
884       G->getLinkage() != GlobalVariable::InternalLinkage)
885     return false;
886   // Two problems with thread-locals:
887   //   - The address of the main thread's copy can't be computed at link-time.
888   //   - Need to poison all copies, not just the main thread's one.
889   if (G->isThreadLocal())
890     return false;
891   // For now, just ignore this Global if the alignment is large.
892   if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
893
894   // Ignore all the globals with the names starting with "\01L_OBJC_".
895   // Many of those are put into the .cstring section. The linker compresses
896   // that section by removing the spare \0s after the string terminator, so
897   // our redzones get broken.
898   if ((G->getName().find("\01L_OBJC_") == 0) ||
899       (G->getName().find("\01l_OBJC_") == 0)) {
900     DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G << "\n");
901     return false;
902   }
903
904   if (G->hasSection()) {
905     StringRef Section(G->getSection());
906     // Ignore the globals from the __OBJC section. The ObjC runtime assumes
907     // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
908     // them.
909     if (Section.startswith("__OBJC,") ||
910         Section.startswith("__DATA, __objc_")) {
911       DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
912       return false;
913     }
914     // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
915     // Constant CFString instances are compiled in the following way:
916     //  -- the string buffer is emitted into
917     //     __TEXT,__cstring,cstring_literals
918     //  -- the constant NSConstantString structure referencing that buffer
919     //     is placed into __DATA,__cfstring
920     // Therefore there's no point in placing redzones into __DATA,__cfstring.
921     // Moreover, it causes the linker to crash on OS X 10.7
922     if (Section.startswith("__DATA,__cfstring")) {
923       DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
924       return false;
925     }
926     // The linker merges the contents of cstring_literals and removes the
927     // trailing zeroes.
928     if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
929       DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
930       return false;
931     }
932
933     // Callbacks put into the CRT initializer/terminator sections
934     // should not be instrumented.
935     // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
936     // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
937     if (Section.startswith(".CRT")) {
938       DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
939       return false;
940     }
941
942     // Globals from llvm.metadata aren't emitted, do not instrument them.
943     if (Section == "llvm.metadata") return false;
944   }
945
946   return true;
947 }
948
949 void AddressSanitizerModule::initializeCallbacks(Module &M) {
950   IRBuilder<> IRB(*C);
951   // Declare our poisoning and unpoisoning functions.
952   AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
953       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
954   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
955   AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
956       kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
957   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
958   // Declare functions that register/unregister globals.
959   AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
960       kAsanRegisterGlobalsName, IRB.getVoidTy(),
961       IntptrTy, IntptrTy, NULL));
962   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
963   AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
964       kAsanUnregisterGlobalsName,
965       IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
966   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
967 }
968
969 // This function replaces all global variables with new variables that have
970 // trailing redzones. It also creates a function that poisons
971 // redzones and inserts this function into llvm.global_ctors.
972 bool AddressSanitizerModule::runOnModule(Module &M) {
973   if (!ClGlobals) return false;
974
975   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
976   if (!DLP)
977     return false;
978   DL = &DLP->getDataLayout();
979
980   BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
981   if (BL->isIn(M)) return false;
982   C = &(M.getContext());
983   int LongSize = DL->getPointerSizeInBits();
984   IntptrTy = Type::getIntNTy(*C, LongSize);
985   Mapping = getShadowMapping(M, LongSize);
986   initializeCallbacks(M);
987   DynamicallyInitializedGlobals.Init(M);
988
989   SmallVector<GlobalVariable *, 16> GlobalsToChange;
990
991   for (Module::GlobalListType::iterator G = M.global_begin(),
992        E = M.global_end(); G != E; ++G) {
993     if (ShouldInstrumentGlobal(G))
994       GlobalsToChange.push_back(G);
995   }
996
997   size_t n = GlobalsToChange.size();
998   if (n == 0) return false;
999
1000   // A global is described by a structure
1001   //   size_t beg;
1002   //   size_t size;
1003   //   size_t size_with_redzone;
1004   //   const char *name;
1005   //   const char *module_name;
1006   //   size_t has_dynamic_init;
1007   // We initialize an array of such structures and pass it to a run-time call.
1008   StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
1009                                                IntptrTy, IntptrTy,
1010                                                IntptrTy, IntptrTy, NULL);
1011   SmallVector<Constant *, 16> Initializers(n);
1012
1013   Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1014   assert(CtorFunc);
1015   IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1016
1017   bool HasDynamicallyInitializedGlobals = false;
1018
1019   // We shouldn't merge same module names, as this string serves as unique
1020   // module ID in runtime.
1021   GlobalVariable *ModuleName = createPrivateGlobalForString(
1022       M, M.getModuleIdentifier(), /*AllowMerging*/false);
1023
1024   for (size_t i = 0; i < n; i++) {
1025     static const uint64_t kMaxGlobalRedzone = 1 << 18;
1026     GlobalVariable *G = GlobalsToChange[i];
1027     PointerType *PtrTy = cast<PointerType>(G->getType());
1028     Type *Ty = PtrTy->getElementType();
1029     uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
1030     uint64_t MinRZ = MinRedzoneSizeForGlobal();
1031     // MinRZ <= RZ <= kMaxGlobalRedzone
1032     // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1033     uint64_t RZ = std::max(MinRZ,
1034                          std::min(kMaxGlobalRedzone,
1035                                   (SizeInBytes / MinRZ / 4) * MinRZ));
1036     uint64_t RightRedzoneSize = RZ;
1037     // Round up to MinRZ
1038     if (SizeInBytes % MinRZ)
1039       RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1040     assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1041     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1042     // Determine whether this global should be poisoned in initialization.
1043     bool GlobalHasDynamicInitializer =
1044         DynamicallyInitializedGlobals.Contains(G);
1045     // Don't check initialization order if this global is blacklisted.
1046     GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
1047
1048     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
1049     Constant *NewInitializer = ConstantStruct::get(
1050         NewTy, G->getInitializer(),
1051         Constant::getNullValue(RightRedZoneTy), NULL);
1052
1053     GlobalVariable *Name =
1054         createPrivateGlobalForString(M, G->getName(), /*AllowMerging*/true);
1055
1056     // Create a new global variable with enough space for a redzone.
1057     GlobalValue::LinkageTypes Linkage = G->getLinkage();
1058     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1059       Linkage = GlobalValue::InternalLinkage;
1060     GlobalVariable *NewGlobal = new GlobalVariable(
1061         M, NewTy, G->isConstant(), Linkage,
1062         NewInitializer, "", G, G->getThreadLocalMode());
1063     NewGlobal->copyAttributesFrom(G);
1064     NewGlobal->setAlignment(MinRZ);
1065
1066     Value *Indices2[2];
1067     Indices2[0] = IRB.getInt32(0);
1068     Indices2[1] = IRB.getInt32(0);
1069
1070     G->replaceAllUsesWith(
1071         ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
1072     NewGlobal->takeName(G);
1073     G->eraseFromParent();
1074
1075     Initializers[i] = ConstantStruct::get(
1076         GlobalStructTy,
1077         ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1078         ConstantInt::get(IntptrTy, SizeInBytes),
1079         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1080         ConstantExpr::getPointerCast(Name, IntptrTy),
1081         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1082         ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
1083         NULL);
1084
1085     // Populate the first and last globals declared in this TU.
1086     if (CheckInitOrder && GlobalHasDynamicInitializer)
1087       HasDynamicallyInitializedGlobals = true;
1088
1089     DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1090   }
1091
1092   ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1093   GlobalVariable *AllGlobals = new GlobalVariable(
1094       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1095       ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1096
1097   // Create calls for poisoning before initializers run and unpoisoning after.
1098   if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1099     createInitializerPoisonCalls(M, ModuleName);
1100   IRB.CreateCall2(AsanRegisterGlobals,
1101                   IRB.CreatePointerCast(AllGlobals, IntptrTy),
1102                   ConstantInt::get(IntptrTy, n));
1103
1104   // We also need to unregister globals at the end, e.g. when a shared library
1105   // gets closed.
1106   Function *AsanDtorFunction = Function::Create(
1107       FunctionType::get(Type::getVoidTy(*C), false),
1108       GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1109   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1110   IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1111   IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1112                        IRB.CreatePointerCast(AllGlobals, IntptrTy),
1113                        ConstantInt::get(IntptrTy, n));
1114   appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1115
1116   DEBUG(dbgs() << M);
1117   return true;
1118 }
1119
1120 void AddressSanitizer::initializeCallbacks(Module &M) {
1121   IRBuilder<> IRB(*C);
1122   // Create __asan_report* callbacks.
1123   for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1124     for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1125          AccessSizeIndex++) {
1126       // IsWrite and TypeSize are encoded in the function name.
1127       std::string Suffix =
1128           (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1129       AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1130           checkInterfaceFunction(
1131               M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
1132                                     IRB.getVoidTy(), IntptrTy, NULL));
1133       AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1134           checkInterfaceFunction(
1135               M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
1136                                     IRB.getVoidTy(), IntptrTy, NULL));
1137     }
1138   }
1139   AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1140               kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1141   AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1142               kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1143
1144   AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1145       M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
1146                             IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1147   AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1148       M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
1149                             IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1150
1151   AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1152       ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1153       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1154   AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1155       ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1156       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1157   AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1158       ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1159       IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, NULL));
1160
1161   AsanHandleNoReturnFunc = checkInterfaceFunction(
1162       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
1163   AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
1164       kAsanCovName, IRB.getVoidTy(), NULL));
1165   AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1166       kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1167   AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1168       kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1169   // We insert an empty inline asm after __asan_report* to avoid callback merge.
1170   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1171                             StringRef(""), StringRef(""),
1172                             /*hasSideEffects=*/true);
1173 }
1174
1175 // virtual
1176 bool AddressSanitizer::doInitialization(Module &M) {
1177   // Initialize the private fields. No one has accessed them before.
1178   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1179   if (!DLP)
1180     report_fatal_error("data layout missing");
1181   DL = &DLP->getDataLayout();
1182
1183   BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
1184   DynamicallyInitializedGlobals.Init(M);
1185
1186   C = &(M.getContext());
1187   LongSize = DL->getPointerSizeInBits();
1188   IntptrTy = Type::getIntNTy(*C, LongSize);
1189
1190   AsanCtorFunction = Function::Create(
1191       FunctionType::get(Type::getVoidTy(*C), false),
1192       GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1193   BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1194   // call __asan_init in the module ctor.
1195   IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1196   AsanInitFunction = checkInterfaceFunction(
1197       M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1198   AsanInitFunction->setLinkage(Function::ExternalLinkage);
1199   IRB.CreateCall(AsanInitFunction);
1200
1201   Mapping = getShadowMapping(M, LongSize);
1202
1203   appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
1204   return true;
1205 }
1206
1207 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1208   // For each NSObject descendant having a +load method, this method is invoked
1209   // by the ObjC runtime before any of the static constructors is called.
1210   // Therefore we need to instrument such methods with a call to __asan_init
1211   // at the beginning in order to initialize our runtime before any access to
1212   // the shadow memory.
1213   // We cannot just ignore these methods, because they may call other
1214   // instrumented functions.
1215   if (F.getName().find(" load]") != std::string::npos) {
1216     IRBuilder<> IRB(F.begin()->begin());
1217     IRB.CreateCall(AsanInitFunction);
1218     return true;
1219   }
1220   return false;
1221 }
1222
1223 void AddressSanitizer::InjectCoverageAtBlock(Function &F, BasicBlock &BB) {
1224   BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
1225   // Skip static allocas at the top of the entry block so they don't become
1226   // dynamic when we split the block.  If we used our optimized stack layout,
1227   // then there will only be one alloca and it will come first.
1228   for (; IP != BE; ++IP) {
1229     AllocaInst *AI = dyn_cast<AllocaInst>(IP);
1230     if (!AI || !AI->isStaticAlloca())
1231       break;
1232   }
1233
1234   IRBuilder<> IRB(IP);
1235   Type *Int8Ty = IRB.getInt8Ty();
1236   GlobalVariable *Guard = new GlobalVariable(
1237       *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
1238       Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
1239   LoadInst *Load = IRB.CreateLoad(Guard);
1240   Load->setAtomic(Monotonic);
1241   Load->setAlignment(1);
1242   Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
1243   Instruction *Ins = SplitBlockAndInsertIfThen(
1244       Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
1245   IRB.SetInsertPoint(Ins);
1246   // We pass &F to __sanitizer_cov. We could avoid this and rely on
1247   // GET_CALLER_PC, but having the PC of the first instruction is just nice.
1248   Instruction *Call = IRB.CreateCall(AsanCovFunction);
1249   Call->setDebugLoc(IP->getDebugLoc());
1250   StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
1251   Store->setAtomic(Monotonic);
1252   Store->setAlignment(1);
1253 }
1254
1255 // Poor man's coverage that works with ASan.
1256 // We create a Guard boolean variable with the same linkage
1257 // as the function and inject this code into the entry block (-asan-coverage=1)
1258 // or all blocks (-asan-coverage=2):
1259 // if (*Guard) {
1260 //    __sanitizer_cov(&F);
1261 //    *Guard = 1;
1262 // }
1263 // The accesses to Guard are atomic. The rest of the logic is
1264 // in __sanitizer_cov (it's fine to call it more than once).
1265 //
1266 // This coverage implementation provides very limited data:
1267 // it only tells if a given function (block) was ever executed.
1268 // No counters, no per-edge data.
1269 // But for many use cases this is what we need and the added slowdown
1270 // is negligible. This simple implementation will probably be obsoleted
1271 // by the upcoming Clang-based coverage implementation.
1272 // By having it here and now we hope to
1273 //  a) get the functionality to users earlier and
1274 //  b) collect usage statistics to help improve Clang coverage design.
1275 bool AddressSanitizer::InjectCoverage(Function &F,
1276                                       const ArrayRef<BasicBlock *> AllBlocks) {
1277   if (!ClCoverage) return false;
1278
1279   if (ClCoverage == 1 ||
1280       (unsigned)ClCoverageBlockThreshold < AllBlocks.size()) {
1281     InjectCoverageAtBlock(F, F.getEntryBlock());
1282   } else {
1283     for (size_t i = 0, n = AllBlocks.size(); i < n; i++)
1284       InjectCoverageAtBlock(F, *AllBlocks[i]);
1285   }
1286   return true;
1287 }
1288
1289 bool AddressSanitizer::runOnFunction(Function &F) {
1290   if (BL->isIn(F)) return false;
1291   if (&F == AsanCtorFunction) return false;
1292   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1293   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1294   initializeCallbacks(*F.getParent());
1295
1296   // If needed, insert __asan_init before checking for SanitizeAddress attr.
1297   maybeInsertAsanInitAtFunctionEntry(F);
1298
1299   if (!F.hasFnAttribute(Attribute::SanitizeAddress))
1300     return false;
1301
1302   if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1303     return false;
1304
1305   // We want to instrument every address only once per basic block (unless there
1306   // are calls between uses).
1307   SmallSet<Value*, 16> TempsToInstrument;
1308   SmallVector<Instruction*, 16> ToInstrument;
1309   SmallVector<Instruction*, 8> NoReturnCalls;
1310   SmallVector<BasicBlock*, 16> AllBlocks;
1311   SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
1312   int NumAllocas = 0;
1313   bool IsWrite;
1314
1315   // Fill the set of memory operations to instrument.
1316   for (Function::iterator FI = F.begin(), FE = F.end();
1317        FI != FE; ++FI) {
1318     AllBlocks.push_back(FI);
1319     TempsToInstrument.clear();
1320     int NumInsnsPerBB = 0;
1321     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1322          BI != BE; ++BI) {
1323       if (LooksLikeCodeInBug11395(BI)) return false;
1324       if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
1325         if (ClOpt && ClOptSameTemp) {
1326           if (!TempsToInstrument.insert(Addr))
1327             continue;  // We've seen this temp in the current BB.
1328         }
1329       } else if (ClInvalidPointerPairs &&
1330                  isInterestingPointerComparisonOrSubtraction(BI)) {
1331         PointerComparisonsOrSubtracts.push_back(BI);
1332         continue;
1333       } else if (isa<MemIntrinsic>(BI)) {
1334         // ok, take it.
1335       } else {
1336         if (isa<AllocaInst>(BI))
1337           NumAllocas++;
1338         CallSite CS(BI);
1339         if (CS) {
1340           // A call inside BB.
1341           TempsToInstrument.clear();
1342           if (CS.doesNotReturn())
1343             NoReturnCalls.push_back(CS.getInstruction());
1344         }
1345         continue;
1346       }
1347       ToInstrument.push_back(BI);
1348       NumInsnsPerBB++;
1349       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1350         break;
1351     }
1352   }
1353
1354   Function *UninstrumentedDuplicate = nullptr;
1355   bool LikelyToInstrument =
1356       !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1357   if (ClKeepUninstrumented && LikelyToInstrument) {
1358     ValueToValueMapTy VMap;
1359     UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1360     UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1361     UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1362     F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1363   }
1364
1365   bool UseCalls = false;
1366   if (ClInstrumentationWithCallsThreshold >= 0 &&
1367       ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1368     UseCalls = true;
1369
1370   // Instrument.
1371   int NumInstrumented = 0;
1372   for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1373     Instruction *Inst = ToInstrument[i];
1374     if (ClDebugMin < 0 || ClDebugMax < 0 ||
1375         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1376       if (isInterestingMemoryAccess(Inst, &IsWrite))
1377         instrumentMop(Inst, UseCalls);
1378       else
1379         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1380     }
1381     NumInstrumented++;
1382   }
1383
1384   FunctionStackPoisoner FSP(F, *this);
1385   bool ChangedStack = FSP.runOnFunction();
1386
1387   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1388   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1389   for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1390     Instruction *CI = NoReturnCalls[i];
1391     IRBuilder<> IRB(CI);
1392     IRB.CreateCall(AsanHandleNoReturnFunc);
1393   }
1394
1395   for (size_t i = 0, n = PointerComparisonsOrSubtracts.size(); i != n; i++) {
1396     instrumentPointerComparisonOrSubtraction(PointerComparisonsOrSubtracts[i]);
1397     NumInstrumented++;
1398   }
1399
1400   bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1401
1402   if (InjectCoverage(F, AllBlocks))
1403     res = true;
1404
1405   DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1406
1407   if (ClKeepUninstrumented) {
1408     if (!res) {
1409       // No instrumentation is done, no need for the duplicate.
1410       if (UninstrumentedDuplicate)
1411         UninstrumentedDuplicate->eraseFromParent();
1412     } else {
1413       // The function was instrumented. We must have the duplicate.
1414       assert(UninstrumentedDuplicate);
1415       UninstrumentedDuplicate->setSection("NOASAN");
1416       assert(!F.hasSection());
1417       F.setSection("ASAN");
1418     }
1419   }
1420
1421   return res;
1422 }
1423
1424 // Workaround for bug 11395: we don't want to instrument stack in functions
1425 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1426 // FIXME: remove once the bug 11395 is fixed.
1427 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1428   if (LongSize != 32) return false;
1429   CallInst *CI = dyn_cast<CallInst>(I);
1430   if (!CI || !CI->isInlineAsm()) return false;
1431   if (CI->getNumArgOperands() <= 5) return false;
1432   // We have inline assembly with quite a few arguments.
1433   return true;
1434 }
1435
1436 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1437   IRBuilder<> IRB(*C);
1438   for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1439     std::string Suffix = itostr(i);
1440     AsanStackMallocFunc[i] = checkInterfaceFunction(
1441         M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1442                               IntptrTy, IntptrTy, NULL));
1443     AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1444         kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1445         IntptrTy, IntptrTy, NULL));
1446   }
1447   AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1448       kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1449   AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1450       kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1451 }
1452
1453 void
1454 FunctionStackPoisoner::poisonRedZones(const ArrayRef<uint8_t> ShadowBytes,
1455                                       IRBuilder<> &IRB, Value *ShadowBase,
1456                                       bool DoPoison) {
1457   size_t n = ShadowBytes.size();
1458   size_t i = 0;
1459   // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1460   // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1461   // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1462   for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1463        LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1464     for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1465       uint64_t Val = 0;
1466       for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1467         if (ASan.DL->isLittleEndian())
1468           Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1469         else
1470           Val = (Val << 8) | ShadowBytes[i + j];
1471       }
1472       if (!Val) continue;
1473       Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1474       Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1475       Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1476       IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1477     }
1478   }
1479 }
1480
1481 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1482 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1483 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1484   assert(LocalStackSize <= kMaxStackMallocSize);
1485   uint64_t MaxSize = kMinStackMallocSize;
1486   for (int i = 0; ; i++, MaxSize *= 2)
1487     if (LocalStackSize <= MaxSize)
1488       return i;
1489   llvm_unreachable("impossible LocalStackSize");
1490 }
1491
1492 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1493 // We can not use MemSet intrinsic because it may end up calling the actual
1494 // memset. Size is a multiple of 8.
1495 // Currently this generates 8-byte stores on x86_64; it may be better to
1496 // generate wider stores.
1497 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1498     IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1499   assert(!(Size % 8));
1500   assert(kAsanStackAfterReturnMagic == 0xf5);
1501   for (int i = 0; i < Size; i += 8) {
1502     Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1503     IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1504                     IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1505   }
1506 }
1507
1508 void FunctionStackPoisoner::poisonStack() {
1509   int StackMallocIdx = -1;
1510
1511   assert(AllocaVec.size() > 0);
1512   Instruction *InsBefore = AllocaVec[0];
1513   IRBuilder<> IRB(InsBefore);
1514
1515   SmallVector<ASanStackVariableDescription, 16> SVD;
1516   SVD.reserve(AllocaVec.size());
1517   for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1518     AllocaInst *AI = AllocaVec[i];
1519     ASanStackVariableDescription D = { AI->getName().data(),
1520                                    getAllocaSizeInBytes(AI),
1521                                    AI->getAlignment(), AI, 0};
1522     SVD.push_back(D);
1523   }
1524   // Minimal header size (left redzone) is 4 pointers,
1525   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1526   size_t MinHeaderSize = ASan.LongSize / 2;
1527   ASanStackFrameLayout L;
1528   ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1529   DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1530   uint64_t LocalStackSize = L.FrameSize;
1531   bool DoStackMalloc =
1532       ASan.CheckUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
1533
1534   Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1535   AllocaInst *MyAlloca =
1536       new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1537   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1538   size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1539   MyAlloca->setAlignment(FrameAlignment);
1540   assert(MyAlloca->isStaticAlloca());
1541   Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1542   Value *LocalStackBase = OrigStackBase;
1543
1544   if (DoStackMalloc) {
1545     // LocalStackBase = OrigStackBase
1546     // if (__asan_option_detect_stack_use_after_return)
1547     //   LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
1548     StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1549     assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1550     Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1551         kAsanOptionDetectUAR, IRB.getInt32Ty());
1552     Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1553                                   Constant::getNullValue(IRB.getInt32Ty()));
1554     Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
1555     BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1556     IRBuilder<> IRBIf(Term);
1557     LocalStackBase = IRBIf.CreateCall2(
1558         AsanStackMallocFunc[StackMallocIdx],
1559         ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1560     BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1561     IRB.SetInsertPoint(InsBefore);
1562     PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1563     Phi->addIncoming(OrigStackBase, CmpBlock);
1564     Phi->addIncoming(LocalStackBase, SetBlock);
1565     LocalStackBase = Phi;
1566   }
1567
1568   // Insert poison calls for lifetime intrinsics for alloca.
1569   bool HavePoisonedAllocas = false;
1570   for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1571     const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1572     assert(APC.InsBefore);
1573     assert(APC.AI);
1574     IRBuilder<> IRB(APC.InsBefore);
1575     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1576     HavePoisonedAllocas |= APC.DoPoison;
1577   }
1578
1579   // Replace Alloca instructions with base+offset.
1580   for (size_t i = 0, n = SVD.size(); i < n; i++) {
1581     AllocaInst *AI = SVD[i].AI;
1582     Value *NewAllocaPtr = IRB.CreateIntToPtr(
1583         IRB.CreateAdd(LocalStackBase,
1584                       ConstantInt::get(IntptrTy, SVD[i].Offset)),
1585         AI->getType());
1586     replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1587     AI->replaceAllUsesWith(NewAllocaPtr);
1588   }
1589
1590   // The left-most redzone has enough space for at least 4 pointers.
1591   // Write the Magic value to redzone[0].
1592   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1593   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1594                   BasePlus0);
1595   // Write the frame description constant to redzone[1].
1596   Value *BasePlus1 = IRB.CreateIntToPtr(
1597     IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1598     IntptrPtrTy);
1599   GlobalVariable *StackDescriptionGlobal =
1600       createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1601                                    /*AllowMerging*/true);
1602   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1603                                              IntptrTy);
1604   IRB.CreateStore(Description, BasePlus1);
1605   // Write the PC to redzone[2].
1606   Value *BasePlus2 = IRB.CreateIntToPtr(
1607     IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1608                                                    2 * ASan.LongSize/8)),
1609     IntptrPtrTy);
1610   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1611
1612   // Poison the stack redzones at the entry.
1613   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1614   poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1615
1616   // (Un)poison the stack before all ret instructions.
1617   for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1618     Instruction *Ret = RetVec[i];
1619     IRBuilder<> IRBRet(Ret);
1620     // Mark the current frame as retired.
1621     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1622                        BasePlus0);
1623     if (DoStackMalloc) {
1624       assert(StackMallocIdx >= 0);
1625       // if LocalStackBase != OrigStackBase:
1626       //     // In use-after-return mode, poison the whole stack frame.
1627       //     if StackMallocIdx <= 4
1628       //         // For small sizes inline the whole thing:
1629       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1630       //         **SavedFlagPtr(LocalStackBase) = 0
1631       //     else
1632       //         __asan_stack_free_N(LocalStackBase, OrigStackBase)
1633       // else
1634       //     <This is not a fake stack; unpoison the redzones>
1635       Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1636       TerminatorInst *ThenTerm, *ElseTerm;
1637       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1638
1639       IRBuilder<> IRBPoison(ThenTerm);
1640       if (StackMallocIdx <= 4) {
1641         int ClassSize = kMinStackMallocSize << StackMallocIdx;
1642         SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1643                                            ClassSize >> Mapping.Scale);
1644         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1645             LocalStackBase,
1646             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1647         Value *SavedFlagPtr = IRBPoison.CreateLoad(
1648             IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1649         IRBPoison.CreateStore(
1650             Constant::getNullValue(IRBPoison.getInt8Ty()),
1651             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1652       } else {
1653         // For larger frames call __asan_stack_free_*.
1654         IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1655                               ConstantInt::get(IntptrTy, LocalStackSize),
1656                               OrigStackBase);
1657       }
1658
1659       IRBuilder<> IRBElse(ElseTerm);
1660       poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1661     } else if (HavePoisonedAllocas) {
1662       // If we poisoned some allocas in llvm.lifetime analysis,
1663       // unpoison whole stack frame now.
1664       assert(LocalStackBase == OrigStackBase);
1665       poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1666     } else {
1667       poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1668     }
1669   }
1670
1671   // We are done. Remove the old unused alloca instructions.
1672   for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1673     AllocaVec[i]->eraseFromParent();
1674 }
1675
1676 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1677                                          IRBuilder<> &IRB, bool DoPoison) {
1678   // For now just insert the call to ASan runtime.
1679   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1680   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1681   IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1682                            : AsanUnpoisonStackMemoryFunc,
1683                   AddrArg, SizeArg);
1684 }
1685
1686 // Handling llvm.lifetime intrinsics for a given %alloca:
1687 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1688 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1689 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1690 //     could be poisoned by previous llvm.lifetime.end instruction, as the
1691 //     variable may go in and out of scope several times, e.g. in loops).
1692 // (3) if we poisoned at least one %alloca in a function,
1693 //     unpoison the whole stack frame at function exit.
1694
1695 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1696   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1697     // We're intested only in allocas we can handle.
1698     return isInterestingAlloca(*AI) ? AI : nullptr;
1699   // See if we've already calculated (or started to calculate) alloca for a
1700   // given value.
1701   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1702   if (I != AllocaForValue.end())
1703     return I->second;
1704   // Store 0 while we're calculating alloca for value V to avoid
1705   // infinite recursion if the value references itself.
1706   AllocaForValue[V] = nullptr;
1707   AllocaInst *Res = nullptr;
1708   if (CastInst *CI = dyn_cast<CastInst>(V))
1709     Res = findAllocaForValue(CI->getOperand(0));
1710   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1711     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1712       Value *IncValue = PN->getIncomingValue(i);
1713       // Allow self-referencing phi-nodes.
1714       if (IncValue == PN) continue;
1715       AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1716       // AI for incoming values should exist and should all be equal.
1717       if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1718         return nullptr;
1719       Res = IncValueAI;
1720     }
1721   }
1722   if (Res)
1723     AllocaForValue[V] = Res;
1724   return Res;
1725 }