2e088ccb29bb7dd4f683111da6169f4a17de25b2
[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/DenseSet.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/Analysis/MemoryBuiltins.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/DIBuilder.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/InlineAsm.h"
37 #include "llvm/IR/InstVisitor.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/LLVMContext.h"
40 #include "llvm/IR/MDBuilder.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/IR/Type.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/DataTypes.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/Endian.h"
48 #include "llvm/Support/SwapByteOrder.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Transforms/Scalar.h"
51 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
52 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
53 #include "llvm/Transforms/Utils/Cloning.h"
54 #include "llvm/Transforms/Utils/Local.h"
55 #include "llvm/Transforms/Utils/ModuleUtils.h"
56 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
57 #include <algorithm>
58 #include <string>
59 #include <system_error>
60
61 using namespace llvm;
62
63 #define DEBUG_TYPE "asan"
64
65 static const uint64_t kDefaultShadowScale = 3;
66 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
67 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
68 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
69 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000;  // < 2G.
70 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
71 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
72 static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
73 static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
74 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
75 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
76 static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
77
78 static const size_t kMinStackMallocSize = 1 << 6;   // 64B
79 static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
80 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
81 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
82
83 static const char *const kAsanModuleCtorName = "asan.module_ctor";
84 static const char *const kAsanModuleDtorName = "asan.module_dtor";
85 static const uint64_t kAsanCtorAndDtorPriority = 1;
86 static const char *const kAsanReportErrorTemplate = "__asan_report_";
87 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
88 static const char *const kAsanUnregisterGlobalsName =
89     "__asan_unregister_globals";
90 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
91 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
92 static const char *const kAsanInitName = "__asan_init_v5";
93 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
94 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
95 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
96 static const int kMaxAsanStackMallocSizeClass = 10;
97 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
98 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
99 static const char *const kAsanGenPrefix = "__asan_gen_";
100 static const char *const kSanCovGenPrefix = "__sancov_gen_";
101 static const char *const kAsanPoisonStackMemoryName =
102     "__asan_poison_stack_memory";
103 static const char *const kAsanUnpoisonStackMemoryName =
104     "__asan_unpoison_stack_memory";
105
106 static const char *const kAsanOptionDetectUAR =
107     "__asan_option_detect_stack_use_after_return";
108
109 static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
110 static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
111
112 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
113 static const size_t kNumberOfAccessSizes = 5;
114
115 static const unsigned kAllocaRzSize = 32;
116
117 // Command-line flags.
118
119 // This flag may need to be replaced with -f[no-]asan-reads.
120 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
121                                        cl::desc("instrument read instructions"),
122                                        cl::Hidden, cl::init(true));
123 static cl::opt<bool> ClInstrumentWrites(
124     "asan-instrument-writes", cl::desc("instrument write instructions"),
125     cl::Hidden, cl::init(true));
126 static cl::opt<bool> ClInstrumentAtomics(
127     "asan-instrument-atomics",
128     cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
129     cl::init(true));
130 static cl::opt<bool> ClAlwaysSlowPath(
131     "asan-always-slow-path",
132     cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
133     cl::init(false));
134 // This flag limits the number of instructions to be instrumented
135 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
136 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
137 // set it to 10000.
138 static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
139     "asan-max-ins-per-bb", cl::init(10000),
140     cl::desc("maximal number of instructions to instrument in any given BB"),
141     cl::Hidden);
142 // This flag may need to be replaced with -f[no]asan-stack.
143 static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
144                              cl::Hidden, cl::init(true));
145 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
146                                       cl::desc("Check return-after-free"),
147                                       cl::Hidden, cl::init(true));
148 // This flag may need to be replaced with -f[no]asan-globals.
149 static cl::opt<bool> ClGlobals("asan-globals",
150                                cl::desc("Handle global objects"), cl::Hidden,
151                                cl::init(true));
152 static cl::opt<bool> ClInitializers("asan-initialization-order",
153                                     cl::desc("Handle C++ initializer order"),
154                                     cl::Hidden, cl::init(true));
155 static cl::opt<bool> ClInvalidPointerPairs(
156     "asan-detect-invalid-pointer-pair",
157     cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
158     cl::init(false));
159 static cl::opt<unsigned> ClRealignStack(
160     "asan-realign-stack",
161     cl::desc("Realign stack to the value of this flag (power of two)"),
162     cl::Hidden, cl::init(32));
163 static cl::opt<int> ClInstrumentationWithCallsThreshold(
164     "asan-instrumentation-with-call-threshold",
165     cl::desc(
166         "If the function being instrumented contains more than "
167         "this number of memory accesses, use callbacks instead of "
168         "inline checks (-1 means never use callbacks)."),
169     cl::Hidden, cl::init(7000));
170 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
171     "asan-memory-access-callback-prefix",
172     cl::desc("Prefix for memory access callbacks"), cl::Hidden,
173     cl::init("__asan_"));
174 static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
175                                          cl::desc("instrument dynamic allocas"),
176                                          cl::Hidden, cl::init(false));
177 static cl::opt<bool> ClSkipPromotableAllocas(
178     "asan-skip-promotable-allocas",
179     cl::desc("Do not instrument promotable allocas"), cl::Hidden,
180     cl::init(true));
181
182 // These flags allow to change the shadow mapping.
183 // The shadow mapping looks like
184 //    Shadow = (Mem >> scale) + (1 << offset_log)
185 static cl::opt<int> ClMappingScale("asan-mapping-scale",
186                                    cl::desc("scale of asan shadow mapping"),
187                                    cl::Hidden, cl::init(0));
188
189 // Optimization flags. Not user visible, used mostly for testing
190 // and benchmarking the tool.
191 static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
192                            cl::Hidden, cl::init(true));
193 static cl::opt<bool> ClOptSameTemp(
194     "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
195     cl::Hidden, cl::init(true));
196 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
197                                   cl::desc("Don't instrument scalar globals"),
198                                   cl::Hidden, cl::init(true));
199 static cl::opt<bool> ClOptStack(
200     "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
201     cl::Hidden, cl::init(false));
202
203 static cl::opt<bool> ClCheckLifetime(
204     "asan-check-lifetime",
205     cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), cl::Hidden,
206     cl::init(false));
207
208 static cl::opt<bool> ClDynamicAllocaStack(
209     "asan-stack-dynamic-alloca",
210     cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
211     cl::init(true));
212
213 static cl::opt<uint32_t> ClForceExperiment(
214     "asan-force-experiment",
215     cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
216     cl::init(0));
217
218 // Debug flags.
219 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
220                             cl::init(0));
221 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
222                                  cl::Hidden, cl::init(0));
223 static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
224                                         cl::desc("Debug func"));
225 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
226                                cl::Hidden, cl::init(-1));
227 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
228                                cl::Hidden, cl::init(-1));
229
230 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
231 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
232 STATISTIC(NumOptimizedAccessesToGlobalVar,
233           "Number of optimized accesses to global vars");
234 STATISTIC(NumOptimizedAccessesToStackVar,
235           "Number of optimized accesses to stack vars");
236
237 namespace {
238 /// Frontend-provided metadata for source location.
239 struct LocationMetadata {
240   StringRef Filename;
241   int LineNo;
242   int ColumnNo;
243
244   LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
245
246   bool empty() const { return Filename.empty(); }
247
248   void parse(MDNode *MDN) {
249     assert(MDN->getNumOperands() == 3);
250     MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
251     Filename = DIFilename->getString();
252     LineNo =
253         mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
254     ColumnNo =
255         mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
256   }
257 };
258
259 /// Frontend-provided metadata for global variables.
260 class GlobalsMetadata {
261  public:
262   struct Entry {
263     Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
264     LocationMetadata SourceLoc;
265     StringRef Name;
266     bool IsDynInit;
267     bool IsBlacklisted;
268   };
269
270   GlobalsMetadata() : inited_(false) {}
271
272   void init(Module &M) {
273     assert(!inited_);
274     inited_ = true;
275     NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
276     if (!Globals) return;
277     for (auto MDN : Globals->operands()) {
278       // Metadata node contains the global and the fields of "Entry".
279       assert(MDN->getNumOperands() == 5);
280       auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
281       // The optimizer may optimize away a global entirely.
282       if (!GV) continue;
283       // We can already have an entry for GV if it was merged with another
284       // global.
285       Entry &E = Entries[GV];
286       if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
287         E.SourceLoc.parse(Loc);
288       if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
289         E.Name = Name->getString();
290       ConstantInt *IsDynInit =
291           mdconst::extract<ConstantInt>(MDN->getOperand(3));
292       E.IsDynInit |= IsDynInit->isOne();
293       ConstantInt *IsBlacklisted =
294           mdconst::extract<ConstantInt>(MDN->getOperand(4));
295       E.IsBlacklisted |= IsBlacklisted->isOne();
296     }
297   }
298
299   /// Returns metadata entry for a given global.
300   Entry get(GlobalVariable *G) const {
301     auto Pos = Entries.find(G);
302     return (Pos != Entries.end()) ? Pos->second : Entry();
303   }
304
305  private:
306   bool inited_;
307   DenseMap<GlobalVariable *, Entry> Entries;
308 };
309
310 /// This struct defines the shadow mapping using the rule:
311 ///   shadow = (mem >> Scale) ADD-or-OR Offset.
312 struct ShadowMapping {
313   int Scale;
314   uint64_t Offset;
315   bool OrShadowOffset;
316 };
317
318 static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize) {
319   bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
320   bool IsIOS = TargetTriple.isiOS();
321   bool IsFreeBSD = TargetTriple.isOSFreeBSD();
322   bool IsLinux = TargetTriple.isOSLinux();
323   bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
324                  TargetTriple.getArch() == llvm::Triple::ppc64le;
325   bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
326   bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
327                   TargetTriple.getArch() == llvm::Triple::mipsel;
328   bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
329                   TargetTriple.getArch() == llvm::Triple::mips64el;
330   bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
331   bool IsWindows = TargetTriple.isOSWindows();
332
333   ShadowMapping Mapping;
334
335   if (LongSize == 32) {
336     if (IsAndroid)
337       Mapping.Offset = 0;
338     else if (IsMIPS32)
339       Mapping.Offset = kMIPS32_ShadowOffset32;
340     else if (IsFreeBSD)
341       Mapping.Offset = kFreeBSD_ShadowOffset32;
342     else if (IsIOS)
343       Mapping.Offset = kIOSShadowOffset32;
344     else if (IsWindows)
345       Mapping.Offset = kWindowsShadowOffset32;
346     else
347       Mapping.Offset = kDefaultShadowOffset32;
348   } else {  // LongSize == 64
349     if (IsPPC64)
350       Mapping.Offset = kPPC64_ShadowOffset64;
351     else if (IsFreeBSD)
352       Mapping.Offset = kFreeBSD_ShadowOffset64;
353     else if (IsLinux && IsX86_64)
354       Mapping.Offset = kSmallX86_64ShadowOffset;
355     else if (IsMIPS64)
356       Mapping.Offset = kMIPS64_ShadowOffset64;
357     else if (IsAArch64)
358       Mapping.Offset = kAArch64_ShadowOffset64;
359     else
360       Mapping.Offset = kDefaultShadowOffset64;
361   }
362
363   Mapping.Scale = kDefaultShadowScale;
364   if (ClMappingScale) {
365     Mapping.Scale = ClMappingScale;
366   }
367
368   // OR-ing shadow offset if more efficient (at least on x86) if the offset
369   // is a power of two, but on ppc64 we have to use add since the shadow
370   // offset is not necessary 1/8-th of the address space.
371   Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
372
373   return Mapping;
374 }
375
376 static size_t RedzoneSizeForScale(int MappingScale) {
377   // Redzone used for stack and globals is at least 32 bytes.
378   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
379   return std::max(32U, 1U << MappingScale);
380 }
381
382 /// AddressSanitizer: instrument the code in module to find memory bugs.
383 struct AddressSanitizer : public FunctionPass {
384   AddressSanitizer() : FunctionPass(ID) {
385     initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
386   }
387   const char *getPassName() const override {
388     return "AddressSanitizerFunctionPass";
389   }
390   void getAnalysisUsage(AnalysisUsage &AU) const override {
391     AU.addRequired<DominatorTreeWrapperPass>();
392     AU.addRequired<TargetLibraryInfoWrapperPass>();
393   }
394   uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
395     Type *Ty = AI->getAllocatedType();
396     uint64_t SizeInBytes =
397         AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
398     return SizeInBytes;
399   }
400   /// Check if we want (and can) handle this alloca.
401   bool isInterestingAlloca(AllocaInst &AI);
402
403   // Check if we have dynamic alloca.
404   bool isDynamicAlloca(AllocaInst &AI) const {
405     return AI.isArrayAllocation() || !AI.isStaticAlloca();
406   }
407
408   /// If it is an interesting memory access, return the PointerOperand
409   /// and set IsWrite/Alignment. Otherwise return nullptr.
410   Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
411                                    uint64_t *TypeSize, unsigned *Alignment);
412   void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
413                      bool UseCalls, const DataLayout &DL);
414   void instrumentPointerComparisonOrSubtraction(Instruction *I);
415   void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
416                          Value *Addr, uint32_t TypeSize, bool IsWrite,
417                          Value *SizeArgument, bool UseCalls, uint32_t Exp);
418   void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
419                                         uint32_t TypeSize, bool IsWrite,
420                                         Value *SizeArgument, bool UseCalls,
421                                         uint32_t Exp);
422   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
423                            Value *ShadowValue, uint32_t TypeSize);
424   Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
425                                  bool IsWrite, size_t AccessSizeIndex,
426                                  Value *SizeArgument, uint32_t Exp);
427   void instrumentMemIntrinsic(MemIntrinsic *MI);
428   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
429   bool runOnFunction(Function &F) override;
430   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
431   bool doInitialization(Module &M) override;
432   static char ID;  // Pass identification, replacement for typeid
433
434   DominatorTree &getDominatorTree() const { return *DT; }
435
436  private:
437   void initializeCallbacks(Module &M);
438
439   bool LooksLikeCodeInBug11395(Instruction *I);
440   bool GlobalIsLinkerInitialized(GlobalVariable *G);
441   bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
442                     uint64_t TypeSize) const;
443
444   LLVMContext *C;
445   Triple TargetTriple;
446   int LongSize;
447   Type *IntptrTy;
448   ShadowMapping Mapping;
449   DominatorTree *DT;
450   Function *AsanCtorFunction;
451   Function *AsanInitFunction;
452   Function *AsanHandleNoReturnFunc;
453   Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
454   // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
455   Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
456   Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
457   // This array is indexed by AccessIsWrite and Experiment.
458   Function *AsanErrorCallbackSized[2][2];
459   Function *AsanMemoryAccessCallbackSized[2][2];
460   Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
461   InlineAsm *EmptyAsm;
462   GlobalsMetadata GlobalsMD;
463   DenseMap<AllocaInst *, bool> ProcessedAllocas;
464
465   friend struct FunctionStackPoisoner;
466 };
467
468 class AddressSanitizerModule : public ModulePass {
469  public:
470   AddressSanitizerModule() : ModulePass(ID) {}
471   bool runOnModule(Module &M) override;
472   static char ID;  // Pass identification, replacement for typeid
473   const char *getPassName() const override { return "AddressSanitizerModule"; }
474
475  private:
476   void initializeCallbacks(Module &M);
477
478   bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
479   bool ShouldInstrumentGlobal(GlobalVariable *G);
480   void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
481   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
482   size_t MinRedzoneSizeForGlobal() const {
483     return RedzoneSizeForScale(Mapping.Scale);
484   }
485
486   GlobalsMetadata GlobalsMD;
487   Type *IntptrTy;
488   LLVMContext *C;
489   Triple TargetTriple;
490   ShadowMapping Mapping;
491   Function *AsanPoisonGlobals;
492   Function *AsanUnpoisonGlobals;
493   Function *AsanRegisterGlobals;
494   Function *AsanUnregisterGlobals;
495 };
496
497 // Stack poisoning does not play well with exception handling.
498 // When an exception is thrown, we essentially bypass the code
499 // that unpoisones the stack. This is why the run-time library has
500 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
501 // stack in the interceptor. This however does not work inside the
502 // actual function which catches the exception. Most likely because the
503 // compiler hoists the load of the shadow value somewhere too high.
504 // This causes asan to report a non-existing bug on 453.povray.
505 // It sounds like an LLVM bug.
506 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
507   Function &F;
508   AddressSanitizer &ASan;
509   DIBuilder DIB;
510   LLVMContext *C;
511   Type *IntptrTy;
512   Type *IntptrPtrTy;
513   ShadowMapping Mapping;
514
515   SmallVector<AllocaInst *, 16> AllocaVec;
516   SmallVector<Instruction *, 8> RetVec;
517   unsigned StackAlignment;
518
519   Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
520       *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
521   Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
522   Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
523
524   // Stores a place and arguments of poisoning/unpoisoning call for alloca.
525   struct AllocaPoisonCall {
526     IntrinsicInst *InsBefore;
527     AllocaInst *AI;
528     uint64_t Size;
529     bool DoPoison;
530   };
531   SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
532
533   SmallVector<AllocaInst *, 1> DynamicAllocaVec;
534   SmallVector<IntrinsicInst *, 1> StackRestoreVec;
535   AllocaInst *DynamicAllocaLayout = nullptr;
536
537   // Maps Value to an AllocaInst from which the Value is originated.
538   typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
539   AllocaForValueMapTy AllocaForValue;
540
541   bool HasNonEmptyInlineAsm;
542   std::unique_ptr<CallInst> EmptyInlineAsm;
543
544   FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
545       : F(F),
546         ASan(ASan),
547         DIB(*F.getParent(), /*AllowUnresolved*/ false),
548         C(ASan.C),
549         IntptrTy(ASan.IntptrTy),
550         IntptrPtrTy(PointerType::get(IntptrTy, 0)),
551         Mapping(ASan.Mapping),
552         StackAlignment(1 << Mapping.Scale),
553         HasNonEmptyInlineAsm(false),
554         EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
555
556   bool runOnFunction() {
557     if (!ClStack) return false;
558     // Collect alloca, ret, lifetime instructions etc.
559     for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
560
561     if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
562
563     initializeCallbacks(*F.getParent());
564
565     poisonStack();
566
567     if (ClDebugStack) {
568       DEBUG(dbgs() << F);
569     }
570     return true;
571   }
572
573   // Finds all Alloca instructions and puts
574   // poisoned red zones around all of them.
575   // Then unpoison everything back before the function returns.
576   void poisonStack();
577
578   void createDynamicAllocasInitStorage();
579
580   // ----------------------- Visitors.
581   /// \brief Collect all Ret instructions.
582   void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
583
584   void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
585                                         Value *SavedStack) {
586     IRBuilder<> IRB(InstBefore);
587     IRB.CreateCall(AsanAllocasUnpoisonFunc,
588                    {IRB.CreateLoad(DynamicAllocaLayout),
589                     IRB.CreatePtrToInt(SavedStack, IntptrTy)});
590   }
591
592   // Unpoison dynamic allocas redzones.
593   void unpoisonDynamicAllocas() {
594     for (auto &Ret : RetVec)
595       unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
596
597     for (auto &StackRestoreInst : StackRestoreVec)
598       unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
599                                        StackRestoreInst->getOperand(0));
600   }
601
602   // Deploy and poison redzones around dynamic alloca call. To do this, we
603   // should replace this call with another one with changed parameters and
604   // replace all its uses with new address, so
605   //   addr = alloca type, old_size, align
606   // is replaced by
607   //   new_size = (old_size + additional_size) * sizeof(type)
608   //   tmp = alloca i8, new_size, max(align, 32)
609   //   addr = tmp + 32 (first 32 bytes are for the left redzone).
610   // Additional_size is added to make new memory allocation contain not only
611   // requested memory, but also left, partial and right redzones.
612   void handleDynamicAllocaCall(AllocaInst *AI);
613
614   /// \brief Collect Alloca instructions we want (and can) handle.
615   void visitAllocaInst(AllocaInst &AI) {
616     if (!ASan.isInterestingAlloca(AI)) return;
617
618     StackAlignment = std::max(StackAlignment, AI.getAlignment());
619     if (ASan.isDynamicAlloca(AI))
620       DynamicAllocaVec.push_back(&AI);
621     else
622       AllocaVec.push_back(&AI);
623   }
624
625   /// \brief Collect lifetime intrinsic calls to check for use-after-scope
626   /// errors.
627   void visitIntrinsicInst(IntrinsicInst &II) {
628     Intrinsic::ID ID = II.getIntrinsicID();
629     if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
630     if (!ClCheckLifetime) return;
631     if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
632       return;
633     // Found lifetime intrinsic, add ASan instrumentation if necessary.
634     ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
635     // If size argument is undefined, don't do anything.
636     if (Size->isMinusOne()) return;
637     // Check that size doesn't saturate uint64_t and can
638     // be stored in IntptrTy.
639     const uint64_t SizeValue = Size->getValue().getLimitedValue();
640     if (SizeValue == ~0ULL ||
641         !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
642       return;
643     // Find alloca instruction that corresponds to llvm.lifetime argument.
644     AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
645     if (!AI) return;
646     bool DoPoison = (ID == Intrinsic::lifetime_end);
647     AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
648     AllocaPoisonCallVec.push_back(APC);
649   }
650
651   void visitCallInst(CallInst &CI) {
652     HasNonEmptyInlineAsm |=
653         CI.isInlineAsm() && !CI.isIdenticalTo(EmptyInlineAsm.get());
654   }
655
656   // ---------------------- Helpers.
657   void initializeCallbacks(Module &M);
658
659   bool doesDominateAllExits(const Instruction *I) const {
660     for (auto Ret : RetVec) {
661       if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
662     }
663     return true;
664   }
665
666   /// Finds alloca where the value comes from.
667   AllocaInst *findAllocaForValue(Value *V);
668   void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
669                       Value *ShadowBase, bool DoPoison);
670   void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
671
672   void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
673                                           int Size);
674   Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
675                                bool Dynamic);
676   PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
677                      Instruction *ThenTerm, Value *ValueIfFalse);
678 };
679
680 }  // namespace
681
682 char AddressSanitizer::ID = 0;
683 INITIALIZE_PASS_BEGIN(
684     AddressSanitizer, "asan",
685     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
686     false)
687 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
688 INITIALIZE_PASS_END(
689     AddressSanitizer, "asan",
690     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
691     false)
692 FunctionPass *llvm::createAddressSanitizerFunctionPass() {
693   return new AddressSanitizer();
694 }
695
696 char AddressSanitizerModule::ID = 0;
697 INITIALIZE_PASS(
698     AddressSanitizerModule, "asan-module",
699     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
700     "ModulePass",
701     false, false)
702 ModulePass *llvm::createAddressSanitizerModulePass() {
703   return new AddressSanitizerModule();
704 }
705
706 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
707   size_t Res = countTrailingZeros(TypeSize / 8);
708   assert(Res < kNumberOfAccessSizes);
709   return Res;
710 }
711
712 // \brief Create a constant for Str so that we can pass it to the run-time lib.
713 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
714                                                     bool AllowMerging) {
715   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
716   // We use private linkage for module-local strings. If they can be merged
717   // with another one, we set the unnamed_addr attribute.
718   GlobalVariable *GV =
719       new GlobalVariable(M, StrConst->getType(), true,
720                          GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
721   if (AllowMerging) GV->setUnnamedAddr(true);
722   GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
723   return GV;
724 }
725
726 /// \brief Create a global describing a source location.
727 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
728                                                        LocationMetadata MD) {
729   Constant *LocData[] = {
730       createPrivateGlobalForString(M, MD.Filename, true),
731       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
732       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
733   };
734   auto LocStruct = ConstantStruct::getAnon(LocData);
735   auto GV = new GlobalVariable(M, LocStruct->getType(), true,
736                                GlobalValue::PrivateLinkage, LocStruct,
737                                kAsanGenPrefix);
738   GV->setUnnamedAddr(true);
739   return GV;
740 }
741
742 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
743   return G->getName().find(kAsanGenPrefix) == 0 ||
744          G->getName().find(kSanCovGenPrefix) == 0;
745 }
746
747 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
748   // Shadow >> scale
749   Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
750   if (Mapping.Offset == 0) return Shadow;
751   // (Shadow >> scale) | offset
752   if (Mapping.OrShadowOffset)
753     return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
754   else
755     return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
756 }
757
758 // Instrument memset/memmove/memcpy
759 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
760   IRBuilder<> IRB(MI);
761   if (isa<MemTransferInst>(MI)) {
762     IRB.CreateCall(
763         isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
764         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
765          IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
766          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
767   } else if (isa<MemSetInst>(MI)) {
768     IRB.CreateCall(
769         AsanMemset,
770         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
771          IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
772          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
773   }
774   MI->eraseFromParent();
775 }
776
777 /// Check if we want (and can) handle this alloca.
778 bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
779   auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
780
781   if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
782     return PreviouslySeenAllocaInfo->getSecond();
783
784   bool IsInteresting =
785       (AI.getAllocatedType()->isSized() &&
786        // alloca() may be called with 0 size, ignore it.
787        getAllocaSizeInBytes(&AI) > 0 &&
788        // We are only interested in allocas not promotable to registers.
789        // Promotable allocas are common under -O0.
790        (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI) ||
791         isDynamicAlloca(AI)));
792
793   ProcessedAllocas[&AI] = IsInteresting;
794   return IsInteresting;
795 }
796
797 /// If I is an interesting memory access, return the PointerOperand
798 /// and set IsWrite/Alignment. Otherwise return nullptr.
799 Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
800                                                    bool *IsWrite,
801                                                    uint64_t *TypeSize,
802                                                    unsigned *Alignment) {
803   // Skip memory accesses inserted by another instrumentation.
804   if (I->getMetadata("nosanitize")) return nullptr;
805
806   Value *PtrOperand = nullptr;
807   const DataLayout &DL = I->getModule()->getDataLayout();
808   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
809     if (!ClInstrumentReads) return nullptr;
810     *IsWrite = false;
811     *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
812     *Alignment = LI->getAlignment();
813     PtrOperand = LI->getPointerOperand();
814   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
815     if (!ClInstrumentWrites) return nullptr;
816     *IsWrite = true;
817     *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
818     *Alignment = SI->getAlignment();
819     PtrOperand = SI->getPointerOperand();
820   } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
821     if (!ClInstrumentAtomics) return nullptr;
822     *IsWrite = true;
823     *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
824     *Alignment = 0;
825     PtrOperand = RMW->getPointerOperand();
826   } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
827     if (!ClInstrumentAtomics) return nullptr;
828     *IsWrite = true;
829     *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
830     *Alignment = 0;
831     PtrOperand = XCHG->getPointerOperand();
832   }
833
834   // Treat memory accesses to promotable allocas as non-interesting since they
835   // will not cause memory violations. This greatly speeds up the instrumented
836   // executable at -O0.
837   if (ClSkipPromotableAllocas)
838     if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
839       return isInterestingAlloca(*AI) ? AI : nullptr;
840
841   return PtrOperand;
842 }
843
844 static bool isPointerOperand(Value *V) {
845   return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
846 }
847
848 // This is a rough heuristic; it may cause both false positives and
849 // false negatives. The proper implementation requires cooperation with
850 // the frontend.
851 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
852   if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
853     if (!Cmp->isRelational()) return false;
854   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
855     if (BO->getOpcode() != Instruction::Sub) return false;
856   } else {
857     return false;
858   }
859   if (!isPointerOperand(I->getOperand(0)) ||
860       !isPointerOperand(I->getOperand(1)))
861     return false;
862   return true;
863 }
864
865 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
866   // If a global variable does not have dynamic initialization we don't
867   // have to instrument it.  However, if a global does not have initializer
868   // at all, we assume it has dynamic initializer (in other TU).
869   return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
870 }
871
872 void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
873     Instruction *I) {
874   IRBuilder<> IRB(I);
875   Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
876   Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
877   for (int i = 0; i < 2; i++) {
878     if (Param[i]->getType()->isPointerTy())
879       Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
880   }
881   IRB.CreateCall(F, Param);
882 }
883
884 void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
885                                      Instruction *I, bool UseCalls,
886                                      const DataLayout &DL) {
887   bool IsWrite = false;
888   unsigned Alignment = 0;
889   uint64_t TypeSize = 0;
890   Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
891   assert(Addr);
892
893   // Optimization experiments.
894   // The experiments can be used to evaluate potential optimizations that remove
895   // instrumentation (assess false negatives). Instead of completely removing
896   // some instrumentation, you set Exp to a non-zero value (mask of optimization
897   // experiments that want to remove instrumentation of this instruction).
898   // If Exp is non-zero, this pass will emit special calls into runtime
899   // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
900   // make runtime terminate the program in a special way (with a different
901   // exit status). Then you run the new compiler on a buggy corpus, collect
902   // the special terminations (ideally, you don't see them at all -- no false
903   // negatives) and make the decision on the optimization.
904   uint32_t Exp = ClForceExperiment;
905
906   if (ClOpt && ClOptGlobals) {
907     // If initialization order checking is disabled, a simple access to a
908     // dynamically initialized global is always valid.
909     GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
910     if (G != NULL && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
911         isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
912       NumOptimizedAccessesToGlobalVar++;
913       return;
914     }
915   }
916
917   if (ClOpt && ClOptStack) {
918     // A direct inbounds access to a stack variable is always valid.
919     if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
920         isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
921       NumOptimizedAccessesToStackVar++;
922       return;
923     }
924   }
925
926   if (IsWrite)
927     NumInstrumentedWrites++;
928   else
929     NumInstrumentedReads++;
930
931   unsigned Granularity = 1 << Mapping.Scale;
932   // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
933   // if the data is properly aligned.
934   if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
935        TypeSize == 128) &&
936       (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
937     return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
938                              Exp);
939   instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
940                                    UseCalls, Exp);
941 }
942
943 Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
944                                                  Value *Addr, bool IsWrite,
945                                                  size_t AccessSizeIndex,
946                                                  Value *SizeArgument,
947                                                  uint32_t Exp) {
948   IRBuilder<> IRB(InsertBefore);
949   Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
950   CallInst *Call = nullptr;
951   if (SizeArgument) {
952     if (Exp == 0)
953       Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
954                             {Addr, SizeArgument});
955     else
956       Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
957                             {Addr, SizeArgument, ExpVal});
958   } else {
959     if (Exp == 0)
960       Call =
961           IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
962     else
963       Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
964                             {Addr, ExpVal});
965   }
966
967   // We don't do Call->setDoesNotReturn() because the BB already has
968   // UnreachableInst at the end.
969   // This EmptyAsm is required to avoid callback merge.
970   IRB.CreateCall(EmptyAsm, {});
971   return Call;
972 }
973
974 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
975                                            Value *ShadowValue,
976                                            uint32_t TypeSize) {
977   size_t Granularity = 1 << Mapping.Scale;
978   // Addr & (Granularity - 1)
979   Value *LastAccessedByte =
980       IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
981   // (Addr & (Granularity - 1)) + size - 1
982   if (TypeSize / 8 > 1)
983     LastAccessedByte = IRB.CreateAdd(
984         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
985   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
986   LastAccessedByte =
987       IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
988   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
989   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
990 }
991
992 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
993                                          Instruction *InsertBefore, Value *Addr,
994                                          uint32_t TypeSize, bool IsWrite,
995                                          Value *SizeArgument, bool UseCalls,
996                                          uint32_t Exp) {
997   IRBuilder<> IRB(InsertBefore);
998   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
999   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1000
1001   if (UseCalls) {
1002     if (Exp == 0)
1003       IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1004                      AddrLong);
1005     else
1006       IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1007                      {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1008     return;
1009   }
1010
1011   Type *ShadowTy =
1012       IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
1013   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1014   Value *ShadowPtr = memToShadow(AddrLong, IRB);
1015   Value *CmpVal = Constant::getNullValue(ShadowTy);
1016   Value *ShadowValue =
1017       IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
1018
1019   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
1020   size_t Granularity = 1 << Mapping.Scale;
1021   TerminatorInst *CrashTerm = nullptr;
1022
1023   if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
1024     // We use branch weights for the slow path check, to indicate that the slow
1025     // path is rarely taken. This seems to be the case for SPEC benchmarks.
1026     TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1027         Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1028     assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1029     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
1030     IRB.SetInsertPoint(CheckTerm);
1031     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1032     BasicBlock *CrashBlock =
1033         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
1034     CrashTerm = new UnreachableInst(*C, CrashBlock);
1035     BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1036     ReplaceInstWithInst(CheckTerm, NewTerm);
1037   } else {
1038     CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
1039   }
1040
1041   Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1042                                          AccessSizeIndex, SizeArgument, Exp);
1043   Crash->setDebugLoc(OrigIns->getDebugLoc());
1044 }
1045
1046 // Instrument unusual size or unusual alignment.
1047 // We can not do it with a single check, so we do 1-byte check for the first
1048 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1049 // to report the actual access size.
1050 void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1051     Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1052     Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1053   IRBuilder<> IRB(I);
1054   Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1055   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1056   if (UseCalls) {
1057     if (Exp == 0)
1058       IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1059                      {AddrLong, Size});
1060     else
1061       IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1062                      {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1063   } else {
1064     Value *LastByte = IRB.CreateIntToPtr(
1065         IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1066         Addr->getType());
1067     instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1068     instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1069   }
1070 }
1071
1072 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1073                                                   GlobalValue *ModuleName) {
1074   // Set up the arguments to our poison/unpoison functions.
1075   IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
1076
1077   // Add a call to poison all external globals before the given function starts.
1078   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1079   IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1080
1081   // Add calls to unpoison all globals before each return instruction.
1082   for (auto &BB : GlobalInit.getBasicBlockList())
1083     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1084       CallInst::Create(AsanUnpoisonGlobals, "", RI);
1085 }
1086
1087 void AddressSanitizerModule::createInitializerPoisonCalls(
1088     Module &M, GlobalValue *ModuleName) {
1089   GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1090
1091   ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1092   for (Use &OP : CA->operands()) {
1093     if (isa<ConstantAggregateZero>(OP)) continue;
1094     ConstantStruct *CS = cast<ConstantStruct>(OP);
1095
1096     // Must have a function or null ptr.
1097     if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
1098       if (F->getName() == kAsanModuleCtorName) continue;
1099       ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1100       // Don't instrument CTORs that will run before asan.module_ctor.
1101       if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1102       poisonOneInitializer(*F, ModuleName);
1103     }
1104   }
1105 }
1106
1107 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
1108   Type *Ty = cast<PointerType>(G->getType())->getElementType();
1109   DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1110
1111   if (GlobalsMD.get(G).IsBlacklisted) return false;
1112   if (!Ty->isSized()) return false;
1113   if (!G->hasInitializer()) return false;
1114   if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
1115   // Touch only those globals that will not be defined in other modules.
1116   // Don't handle ODR linkage types and COMDATs since other modules may be built
1117   // without ASan.
1118   if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1119       G->getLinkage() != GlobalVariable::PrivateLinkage &&
1120       G->getLinkage() != GlobalVariable::InternalLinkage)
1121     return false;
1122   if (G->hasComdat()) return false;
1123   // Two problems with thread-locals:
1124   //   - The address of the main thread's copy can't be computed at link-time.
1125   //   - Need to poison all copies, not just the main thread's one.
1126   if (G->isThreadLocal()) return false;
1127   // For now, just ignore this Global if the alignment is large.
1128   if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1129
1130   if (G->hasSection()) {
1131     StringRef Section(G->getSection());
1132
1133     // Globals from llvm.metadata aren't emitted, do not instrument them.
1134     if (Section == "llvm.metadata") return false;
1135
1136     // Callbacks put into the CRT initializer/terminator sections
1137     // should not be instrumented.
1138     // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1139     // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1140     if (Section.startswith(".CRT")) {
1141       DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1142       return false;
1143     }
1144
1145     if (TargetTriple.isOSBinFormatMachO()) {
1146       StringRef ParsedSegment, ParsedSection;
1147       unsigned TAA = 0, StubSize = 0;
1148       bool TAAParsed;
1149       std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1150           Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1151       if (!ErrorCode.empty()) {
1152         assert(false && "Invalid section specifier.");
1153         return false;
1154       }
1155
1156       // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1157       // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1158       // them.
1159       if (ParsedSegment == "__OBJC" ||
1160           (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1161         DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1162         return false;
1163       }
1164       // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1165       // Constant CFString instances are compiled in the following way:
1166       //  -- the string buffer is emitted into
1167       //     __TEXT,__cstring,cstring_literals
1168       //  -- the constant NSConstantString structure referencing that buffer
1169       //     is placed into __DATA,__cfstring
1170       // Therefore there's no point in placing redzones into __DATA,__cfstring.
1171       // Moreover, it causes the linker to crash on OS X 10.7
1172       if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1173         DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1174         return false;
1175       }
1176       // The linker merges the contents of cstring_literals and removes the
1177       // trailing zeroes.
1178       if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1179         DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1180         return false;
1181       }
1182     }
1183   }
1184
1185   return true;
1186 }
1187
1188 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1189   IRBuilder<> IRB(*C);
1190   // Declare our poisoning and unpoisoning functions.
1191   AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1192       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
1193   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1194   AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1195       kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
1196   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1197   // Declare functions that register/unregister globals.
1198   AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1199       kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1200   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1201   AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1202       M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1203                             IntptrTy, IntptrTy, nullptr));
1204   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1205 }
1206
1207 // This function replaces all global variables with new variables that have
1208 // trailing redzones. It also creates a function that poisons
1209 // redzones and inserts this function into llvm.global_ctors.
1210 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1211   GlobalsMD.init(M);
1212
1213   SmallVector<GlobalVariable *, 16> GlobalsToChange;
1214
1215   for (auto &G : M.globals()) {
1216     if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
1217   }
1218
1219   size_t n = GlobalsToChange.size();
1220   if (n == 0) return false;
1221
1222   // A global is described by a structure
1223   //   size_t beg;
1224   //   size_t size;
1225   //   size_t size_with_redzone;
1226   //   const char *name;
1227   //   const char *module_name;
1228   //   size_t has_dynamic_init;
1229   //   void *source_location;
1230   // We initialize an array of such structures and pass it to a run-time call.
1231   StructType *GlobalStructTy =
1232       StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1233                       IntptrTy, IntptrTy, nullptr);
1234   SmallVector<Constant *, 16> Initializers(n);
1235
1236   bool HasDynamicallyInitializedGlobals = false;
1237
1238   // We shouldn't merge same module names, as this string serves as unique
1239   // module ID in runtime.
1240   GlobalVariable *ModuleName = createPrivateGlobalForString(
1241       M, M.getModuleIdentifier(), /*AllowMerging*/ false);
1242
1243   auto &DL = M.getDataLayout();
1244   for (size_t i = 0; i < n; i++) {
1245     static const uint64_t kMaxGlobalRedzone = 1 << 18;
1246     GlobalVariable *G = GlobalsToChange[i];
1247
1248     auto MD = GlobalsMD.get(G);
1249     // Create string holding the global name (use global name from metadata
1250     // if it's available, otherwise just write the name of global variable).
1251     GlobalVariable *Name = createPrivateGlobalForString(
1252         M, MD.Name.empty() ? G->getName() : MD.Name,
1253         /*AllowMerging*/ true);
1254
1255     PointerType *PtrTy = cast<PointerType>(G->getType());
1256     Type *Ty = PtrTy->getElementType();
1257     uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
1258     uint64_t MinRZ = MinRedzoneSizeForGlobal();
1259     // MinRZ <= RZ <= kMaxGlobalRedzone
1260     // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1261     uint64_t RZ = std::max(
1262         MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
1263     uint64_t RightRedzoneSize = RZ;
1264     // Round up to MinRZ
1265     if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1266     assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1267     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1268
1269     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
1270     Constant *NewInitializer =
1271         ConstantStruct::get(NewTy, G->getInitializer(),
1272                             Constant::getNullValue(RightRedZoneTy), nullptr);
1273
1274     // Create a new global variable with enough space for a redzone.
1275     GlobalValue::LinkageTypes Linkage = G->getLinkage();
1276     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1277       Linkage = GlobalValue::InternalLinkage;
1278     GlobalVariable *NewGlobal =
1279         new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1280                            "", G, G->getThreadLocalMode());
1281     NewGlobal->copyAttributesFrom(G);
1282     NewGlobal->setAlignment(MinRZ);
1283
1284     Value *Indices2[2];
1285     Indices2[0] = IRB.getInt32(0);
1286     Indices2[1] = IRB.getInt32(0);
1287
1288     G->replaceAllUsesWith(
1289         ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
1290     NewGlobal->takeName(G);
1291     G->eraseFromParent();
1292
1293     Constant *SourceLoc;
1294     if (!MD.SourceLoc.empty()) {
1295       auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1296       SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1297     } else {
1298       SourceLoc = ConstantInt::get(IntptrTy, 0);
1299     }
1300
1301     Initializers[i] = ConstantStruct::get(
1302         GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1303         ConstantInt::get(IntptrTy, SizeInBytes),
1304         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1305         ConstantExpr::getPointerCast(Name, IntptrTy),
1306         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1307         ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
1308
1309     if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
1310
1311     DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1312   }
1313
1314   ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1315   GlobalVariable *AllGlobals = new GlobalVariable(
1316       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1317       ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1318
1319   // Create calls for poisoning before initializers run and unpoisoning after.
1320   if (HasDynamicallyInitializedGlobals)
1321     createInitializerPoisonCalls(M, ModuleName);
1322   IRB.CreateCall(AsanRegisterGlobals,
1323                  {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1324                   ConstantInt::get(IntptrTy, n)});
1325
1326   // We also need to unregister globals at the end, e.g. when a shared library
1327   // gets closed.
1328   Function *AsanDtorFunction =
1329       Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1330                        GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1331   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1332   IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1333   IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1334                       {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1335                        ConstantInt::get(IntptrTy, n)});
1336   appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1337
1338   DEBUG(dbgs() << M);
1339   return true;
1340 }
1341
1342 bool AddressSanitizerModule::runOnModule(Module &M) {
1343   C = &(M.getContext());
1344   int LongSize = M.getDataLayout().getPointerSizeInBits();
1345   IntptrTy = Type::getIntNTy(*C, LongSize);
1346   TargetTriple = Triple(M.getTargetTriple());
1347   Mapping = getShadowMapping(TargetTriple, LongSize);
1348   initializeCallbacks(M);
1349
1350   bool Changed = false;
1351
1352   Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1353   assert(CtorFunc);
1354   IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1355
1356   if (ClGlobals) Changed |= InstrumentGlobals(IRB, M);
1357
1358   return Changed;
1359 }
1360
1361 void AddressSanitizer::initializeCallbacks(Module &M) {
1362   IRBuilder<> IRB(*C);
1363   // Create __asan_report* callbacks.
1364   // IsWrite, TypeSize and Exp are encoded in the function name.
1365   for (int Exp = 0; Exp < 2; Exp++) {
1366     for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1367       const std::string TypeStr = AccessIsWrite ? "store" : "load";
1368       const std::string ExpStr = Exp ? "exp_" : "";
1369       const Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
1370       AsanErrorCallbackSized[AccessIsWrite][Exp] =
1371           checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1372               kAsanReportErrorTemplate + ExpStr + TypeStr + "_n",
1373               IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1374       AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
1375           checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1376               ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N",
1377               IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1378       for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1379            AccessSizeIndex++) {
1380         const std::string Suffix = TypeStr + itostr(1 << AccessSizeIndex);
1381         AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1382             checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1383                 kAsanReportErrorTemplate + ExpStr + Suffix, IRB.getVoidTy(),
1384                 IntptrTy, ExpType, nullptr));
1385         AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1386             checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1387                 ClMemoryAccessCallbackPrefix + ExpStr + Suffix, IRB.getVoidTy(),
1388                 IntptrTy, ExpType, nullptr));
1389       }
1390     }
1391   }
1392
1393   AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1394       ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1395       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1396   AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1397       ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1398       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1399   AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1400       ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1401       IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
1402
1403   AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
1404       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
1405
1406   AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1407       kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1408   AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1409       kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1410   // We insert an empty inline asm after __asan_report* to avoid callback merge.
1411   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1412                             StringRef(""), StringRef(""),
1413                             /*hasSideEffects=*/true);
1414 }
1415
1416 // virtual
1417 bool AddressSanitizer::doInitialization(Module &M) {
1418   // Initialize the private fields. No one has accessed them before.
1419
1420   GlobalsMD.init(M);
1421
1422   C = &(M.getContext());
1423   LongSize = M.getDataLayout().getPointerSizeInBits();
1424   IntptrTy = Type::getIntNTy(*C, LongSize);
1425   TargetTriple = Triple(M.getTargetTriple());
1426
1427   std::tie(AsanCtorFunction, AsanInitFunction) =
1428       createSanitizerCtorAndInitFunctions(M, kAsanModuleCtorName, kAsanInitName,
1429                                           /*InitArgTypes=*/{},
1430                                           /*InitArgs=*/{});
1431
1432   Mapping = getShadowMapping(TargetTriple, LongSize);
1433
1434   appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1435   return true;
1436 }
1437
1438 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1439   // For each NSObject descendant having a +load method, this method is invoked
1440   // by the ObjC runtime before any of the static constructors is called.
1441   // Therefore we need to instrument such methods with a call to __asan_init
1442   // at the beginning in order to initialize our runtime before any access to
1443   // the shadow memory.
1444   // We cannot just ignore these methods, because they may call other
1445   // instrumented functions.
1446   if (F.getName().find(" load]") != std::string::npos) {
1447     IRBuilder<> IRB(F.begin()->begin());
1448     IRB.CreateCall(AsanInitFunction, {});
1449     return true;
1450   }
1451   return false;
1452 }
1453
1454 bool AddressSanitizer::runOnFunction(Function &F) {
1455   if (&F == AsanCtorFunction) return false;
1456   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1457   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1458   initializeCallbacks(*F.getParent());
1459
1460   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1461
1462   // If needed, insert __asan_init before checking for SanitizeAddress attr.
1463   maybeInsertAsanInitAtFunctionEntry(F);
1464
1465   if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
1466
1467   if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
1468
1469   // We want to instrument every address only once per basic block (unless there
1470   // are calls between uses).
1471   SmallSet<Value *, 16> TempsToInstrument;
1472   SmallVector<Instruction *, 16> ToInstrument;
1473   SmallVector<Instruction *, 8> NoReturnCalls;
1474   SmallVector<BasicBlock *, 16> AllBlocks;
1475   SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
1476   int NumAllocas = 0;
1477   bool IsWrite;
1478   unsigned Alignment;
1479   uint64_t TypeSize;
1480
1481   // Fill the set of memory operations to instrument.
1482   for (auto &BB : F) {
1483     AllBlocks.push_back(&BB);
1484     TempsToInstrument.clear();
1485     int NumInsnsPerBB = 0;
1486     for (auto &Inst : BB) {
1487       if (LooksLikeCodeInBug11395(&Inst)) return false;
1488       if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1489                                                   &Alignment)) {
1490         if (ClOpt && ClOptSameTemp) {
1491           if (!TempsToInstrument.insert(Addr).second)
1492             continue;  // We've seen this temp in the current BB.
1493         }
1494       } else if (ClInvalidPointerPairs &&
1495                  isInterestingPointerComparisonOrSubtraction(&Inst)) {
1496         PointerComparisonsOrSubtracts.push_back(&Inst);
1497         continue;
1498       } else if (isa<MemIntrinsic>(Inst)) {
1499         // ok, take it.
1500       } else {
1501         if (isa<AllocaInst>(Inst)) NumAllocas++;
1502         CallSite CS(&Inst);
1503         if (CS) {
1504           // A call inside BB.
1505           TempsToInstrument.clear();
1506           if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
1507         }
1508         continue;
1509       }
1510       ToInstrument.push_back(&Inst);
1511       NumInsnsPerBB++;
1512       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
1513     }
1514   }
1515
1516   bool UseCalls = false;
1517   if (ClInstrumentationWithCallsThreshold >= 0 &&
1518       ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1519     UseCalls = true;
1520
1521   const TargetLibraryInfo *TLI =
1522       &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1523   const DataLayout &DL = F.getParent()->getDataLayout();
1524   ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1525                                      /*RoundToAlign=*/true);
1526
1527   // Instrument.
1528   int NumInstrumented = 0;
1529   for (auto Inst : ToInstrument) {
1530     if (ClDebugMin < 0 || ClDebugMax < 0 ||
1531         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1532       if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
1533         instrumentMop(ObjSizeVis, Inst, UseCalls,
1534                       F.getParent()->getDataLayout());
1535       else
1536         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1537     }
1538     NumInstrumented++;
1539   }
1540
1541   FunctionStackPoisoner FSP(F, *this);
1542   bool ChangedStack = FSP.runOnFunction();
1543
1544   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1545   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1546   for (auto CI : NoReturnCalls) {
1547     IRBuilder<> IRB(CI);
1548     IRB.CreateCall(AsanHandleNoReturnFunc, {});
1549   }
1550
1551   for (auto Inst : PointerComparisonsOrSubtracts) {
1552     instrumentPointerComparisonOrSubtraction(Inst);
1553     NumInstrumented++;
1554   }
1555
1556   bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1557
1558   DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1559
1560   return res;
1561 }
1562
1563 // Workaround for bug 11395: we don't want to instrument stack in functions
1564 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1565 // FIXME: remove once the bug 11395 is fixed.
1566 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1567   if (LongSize != 32) return false;
1568   CallInst *CI = dyn_cast<CallInst>(I);
1569   if (!CI || !CI->isInlineAsm()) return false;
1570   if (CI->getNumArgOperands() <= 5) return false;
1571   // We have inline assembly with quite a few arguments.
1572   return true;
1573 }
1574
1575 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1576   IRBuilder<> IRB(*C);
1577   for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1578     std::string Suffix = itostr(i);
1579     AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1580         M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1581                               IntptrTy, nullptr));
1582     AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
1583         M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1584                               IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1585   }
1586   AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1587       M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1588                             IntptrTy, IntptrTy, nullptr));
1589   AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1590       M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1591                             IntptrTy, IntptrTy, nullptr));
1592   AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1593       kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1594   AsanAllocasUnpoisonFunc =
1595       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1596           kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1597 }
1598
1599 void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1600                                            IRBuilder<> &IRB, Value *ShadowBase,
1601                                            bool DoPoison) {
1602   size_t n = ShadowBytes.size();
1603   size_t i = 0;
1604   // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1605   // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1606   // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1607   for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1608        LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1609     for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1610       uint64_t Val = 0;
1611       for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1612         if (F.getParent()->getDataLayout().isLittleEndian())
1613           Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1614         else
1615           Val = (Val << 8) | ShadowBytes[i + j];
1616       }
1617       if (!Val) continue;
1618       Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1619       Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1620       Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1621       IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1622     }
1623   }
1624 }
1625
1626 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1627 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1628 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1629   assert(LocalStackSize <= kMaxStackMallocSize);
1630   uint64_t MaxSize = kMinStackMallocSize;
1631   for (int i = 0;; i++, MaxSize *= 2)
1632     if (LocalStackSize <= MaxSize) return i;
1633   llvm_unreachable("impossible LocalStackSize");
1634 }
1635
1636 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1637 // We can not use MemSet intrinsic because it may end up calling the actual
1638 // memset. Size is a multiple of 8.
1639 // Currently this generates 8-byte stores on x86_64; it may be better to
1640 // generate wider stores.
1641 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1642     IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1643   assert(!(Size % 8));
1644
1645   // kAsanStackAfterReturnMagic is 0xf5.
1646   const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
1647
1648   for (int i = 0; i < Size; i += 8) {
1649     Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1650     IRB.CreateStore(
1651         ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1652         IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1653   }
1654 }
1655
1656 static DebugLoc getFunctionEntryDebugLocation(Function &F) {
1657   for (const auto &Inst : F.getEntryBlock())
1658     if (!isa<AllocaInst>(Inst)) return Inst.getDebugLoc();
1659   return DebugLoc();
1660 }
1661
1662 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1663                                           Value *ValueIfTrue,
1664                                           Instruction *ThenTerm,
1665                                           Value *ValueIfFalse) {
1666   PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1667   BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1668   PHI->addIncoming(ValueIfFalse, CondBlock);
1669   BasicBlock *ThenBlock = ThenTerm->getParent();
1670   PHI->addIncoming(ValueIfTrue, ThenBlock);
1671   return PHI;
1672 }
1673
1674 Value *FunctionStackPoisoner::createAllocaForLayout(
1675     IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1676   AllocaInst *Alloca;
1677   if (Dynamic) {
1678     Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1679                               ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1680                               "MyAlloca");
1681   } else {
1682     Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1683                               nullptr, "MyAlloca");
1684     assert(Alloca->isStaticAlloca());
1685   }
1686   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1687   size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1688   Alloca->setAlignment(FrameAlignment);
1689   return IRB.CreatePointerCast(Alloca, IntptrTy);
1690 }
1691
1692 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1693   BasicBlock &FirstBB = *F.begin();
1694   IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1695   DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1696   IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1697   DynamicAllocaLayout->setAlignment(32);
1698 }
1699
1700 void FunctionStackPoisoner::poisonStack() {
1701   assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1702
1703   if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
1704     // Handle dynamic allocas.
1705     createDynamicAllocasInitStorage();
1706     for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
1707
1708     unpoisonDynamicAllocas();
1709   }
1710
1711   if (AllocaVec.size() == 0) return;
1712
1713   int StackMallocIdx = -1;
1714   DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
1715
1716   Instruction *InsBefore = AllocaVec[0];
1717   IRBuilder<> IRB(InsBefore);
1718   IRB.SetCurrentDebugLocation(EntryDebugLocation);
1719
1720   SmallVector<ASanStackVariableDescription, 16> SVD;
1721   SVD.reserve(AllocaVec.size());
1722   for (AllocaInst *AI : AllocaVec) {
1723     ASanStackVariableDescription D = {AI->getName().data(),
1724                                       ASan.getAllocaSizeInBytes(AI),
1725                                       AI->getAlignment(), AI, 0};
1726     SVD.push_back(D);
1727   }
1728   // Minimal header size (left redzone) is 4 pointers,
1729   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1730   size_t MinHeaderSize = ASan.LongSize / 2;
1731   ASanStackFrameLayout L;
1732   ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1733   DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1734   uint64_t LocalStackSize = L.FrameSize;
1735   bool DoStackMalloc =
1736       ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
1737   // Don't do dynamic alloca in presence of inline asm: too often it makes
1738   // assumptions on which registers are available. Don't do stack malloc in the
1739   // presence of inline asm on 32-bit platforms for the same reason.
1740   bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm;
1741   DoStackMalloc &= !HasNonEmptyInlineAsm || ASan.LongSize != 32;
1742
1743   Value *StaticAlloca =
1744       DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1745
1746   Value *FakeStack;
1747   Value *LocalStackBase;
1748
1749   if (DoStackMalloc) {
1750     // void *FakeStack = __asan_option_detect_stack_use_after_return
1751     //     ? __asan_stack_malloc_N(LocalStackSize)
1752     //     : nullptr;
1753     // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
1754     Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1755         kAsanOptionDetectUAR, IRB.getInt32Ty());
1756     Value *UARIsEnabled =
1757         IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1758                          Constant::getNullValue(IRB.getInt32Ty()));
1759     Instruction *Term =
1760         SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
1761     IRBuilder<> IRBIf(Term);
1762     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1763     StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1764     assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1765     Value *FakeStackValue =
1766         IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1767                          ConstantInt::get(IntptrTy, LocalStackSize));
1768     IRB.SetInsertPoint(InsBefore);
1769     IRB.SetCurrentDebugLocation(EntryDebugLocation);
1770     FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1771                           ConstantInt::get(IntptrTy, 0));
1772
1773     Value *NoFakeStack =
1774         IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1775     Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1776     IRBIf.SetInsertPoint(Term);
1777     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1778     Value *AllocaValue =
1779         DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1780     IRB.SetInsertPoint(InsBefore);
1781     IRB.SetCurrentDebugLocation(EntryDebugLocation);
1782     LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1783   } else {
1784     // void *FakeStack = nullptr;
1785     // void *LocalStackBase = alloca(LocalStackSize);
1786     FakeStack = ConstantInt::get(IntptrTy, 0);
1787     LocalStackBase =
1788         DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
1789   }
1790
1791   // Insert poison calls for lifetime intrinsics for alloca.
1792   bool HavePoisonedAllocas = false;
1793   for (const auto &APC : AllocaPoisonCallVec) {
1794     assert(APC.InsBefore);
1795     assert(APC.AI);
1796     IRBuilder<> IRB(APC.InsBefore);
1797     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1798     HavePoisonedAllocas |= APC.DoPoison;
1799   }
1800
1801   // Replace Alloca instructions with base+offset.
1802   for (const auto &Desc : SVD) {
1803     AllocaInst *AI = Desc.AI;
1804     Value *NewAllocaPtr = IRB.CreateIntToPtr(
1805         IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
1806         AI->getType());
1807     replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
1808     AI->replaceAllUsesWith(NewAllocaPtr);
1809   }
1810
1811   // The left-most redzone has enough space for at least 4 pointers.
1812   // Write the Magic value to redzone[0].
1813   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1814   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1815                   BasePlus0);
1816   // Write the frame description constant to redzone[1].
1817   Value *BasePlus1 = IRB.CreateIntToPtr(
1818       IRB.CreateAdd(LocalStackBase,
1819                     ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
1820       IntptrPtrTy);
1821   GlobalVariable *StackDescriptionGlobal =
1822       createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1823                                    /*AllowMerging*/ true);
1824   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
1825   IRB.CreateStore(Description, BasePlus1);
1826   // Write the PC to redzone[2].
1827   Value *BasePlus2 = IRB.CreateIntToPtr(
1828       IRB.CreateAdd(LocalStackBase,
1829                     ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
1830       IntptrPtrTy);
1831   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1832
1833   // Poison the stack redzones at the entry.
1834   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1835   poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1836
1837   // (Un)poison the stack before all ret instructions.
1838   for (auto Ret : RetVec) {
1839     IRBuilder<> IRBRet(Ret);
1840     // Mark the current frame as retired.
1841     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1842                        BasePlus0);
1843     if (DoStackMalloc) {
1844       assert(StackMallocIdx >= 0);
1845       // if FakeStack != 0  // LocalStackBase == FakeStack
1846       //     // In use-after-return mode, poison the whole stack frame.
1847       //     if StackMallocIdx <= 4
1848       //         // For small sizes inline the whole thing:
1849       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1850       //         **SavedFlagPtr(FakeStack) = 0
1851       //     else
1852       //         __asan_stack_free_N(FakeStack, LocalStackSize)
1853       // else
1854       //     <This is not a fake stack; unpoison the redzones>
1855       Value *Cmp =
1856           IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
1857       TerminatorInst *ThenTerm, *ElseTerm;
1858       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1859
1860       IRBuilder<> IRBPoison(ThenTerm);
1861       if (StackMallocIdx <= 4) {
1862         int ClassSize = kMinStackMallocSize << StackMallocIdx;
1863         SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1864                                            ClassSize >> Mapping.Scale);
1865         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1866             FakeStack,
1867             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1868         Value *SavedFlagPtr = IRBPoison.CreateLoad(
1869             IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1870         IRBPoison.CreateStore(
1871             Constant::getNullValue(IRBPoison.getInt8Ty()),
1872             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1873       } else {
1874         // For larger frames call __asan_stack_free_*.
1875         IRBPoison.CreateCall(
1876             AsanStackFreeFunc[StackMallocIdx],
1877             {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
1878       }
1879
1880       IRBuilder<> IRBElse(ElseTerm);
1881       poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1882     } else if (HavePoisonedAllocas) {
1883       // If we poisoned some allocas in llvm.lifetime analysis,
1884       // unpoison whole stack frame now.
1885       poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1886     } else {
1887       poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1888     }
1889   }
1890
1891   // We are done. Remove the old unused alloca instructions.
1892   for (auto AI : AllocaVec) AI->eraseFromParent();
1893 }
1894
1895 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1896                                          IRBuilder<> &IRB, bool DoPoison) {
1897   // For now just insert the call to ASan runtime.
1898   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1899   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1900   IRB.CreateCall(
1901       DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
1902       {AddrArg, SizeArg});
1903 }
1904
1905 // Handling llvm.lifetime intrinsics for a given %alloca:
1906 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1907 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1908 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1909 //     could be poisoned by previous llvm.lifetime.end instruction, as the
1910 //     variable may go in and out of scope several times, e.g. in loops).
1911 // (3) if we poisoned at least one %alloca in a function,
1912 //     unpoison the whole stack frame at function exit.
1913
1914 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1915   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1916     // We're intested only in allocas we can handle.
1917     return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
1918   // See if we've already calculated (or started to calculate) alloca for a
1919   // given value.
1920   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1921   if (I != AllocaForValue.end()) return I->second;
1922   // Store 0 while we're calculating alloca for value V to avoid
1923   // infinite recursion if the value references itself.
1924   AllocaForValue[V] = nullptr;
1925   AllocaInst *Res = nullptr;
1926   if (CastInst *CI = dyn_cast<CastInst>(V))
1927     Res = findAllocaForValue(CI->getOperand(0));
1928   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1929     for (Value *IncValue : PN->incoming_values()) {
1930       // Allow self-referencing phi-nodes.
1931       if (IncValue == PN) continue;
1932       AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1933       // AI for incoming values should exist and should all be equal.
1934       if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1935         return nullptr;
1936       Res = IncValueAI;
1937     }
1938   }
1939   if (Res) AllocaForValue[V] = Res;
1940   return Res;
1941 }
1942
1943 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
1944   IRBuilder<> IRB(AI);
1945
1946   const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1947   const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1948
1949   Value *Zero = Constant::getNullValue(IntptrTy);
1950   Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1951   Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
1952
1953   // Since we need to extend alloca with additional memory to locate
1954   // redzones, and OldSize is number of allocated blocks with
1955   // ElementSize size, get allocated memory size in bytes by
1956   // OldSize * ElementSize.
1957   const unsigned ElementSize =
1958       F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
1959   Value *OldSize =
1960       IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
1961                     ConstantInt::get(IntptrTy, ElementSize));
1962
1963   // PartialSize = OldSize % 32
1964   Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1965
1966   // Misalign = kAllocaRzSize - PartialSize;
1967   Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1968
1969   // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1970   Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1971   Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1972
1973   // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
1974   // Align is added to locate left redzone, PartialPadding for possible
1975   // partial redzone and kAllocaRzSize for right redzone respectively.
1976   Value *AdditionalChunkSize = IRB.CreateAdd(
1977       ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
1978
1979   Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
1980
1981   // Insert new alloca with new NewSize and Align params.
1982   AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
1983   NewAlloca->setAlignment(Align);
1984
1985   // NewAddress = Address + Align
1986   Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
1987                                     ConstantInt::get(IntptrTy, Align));
1988
1989   // Insert __asan_alloca_poison call for new created alloca.
1990   IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
1991
1992   // Store the last alloca's address to DynamicAllocaLayout. We'll need this
1993   // for unpoisoning stuff.
1994   IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
1995
1996   Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
1997
1998   // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
1999   AI->replaceAllUsesWith(NewAddressPtr);
2000
2001   // We are done. Erase old alloca from parent.
2002   AI->eraseFromParent();
2003 }
2004
2005 // isSafeAccess returns true if Addr is always inbounds with respect to its
2006 // base object. For example, it is a field access or an array access with
2007 // constant inbounds index.
2008 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2009                                     Value *Addr, uint64_t TypeSize) const {
2010   SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2011   if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
2012   uint64_t Size = SizeOffset.first.getZExtValue();
2013   int64_t Offset = SizeOffset.second.getSExtValue();
2014   // Three checks are required to ensure safety:
2015   // . Offset >= 0  (since the offset is given from the base ptr)
2016   // . Size >= Offset  (unsigned)
2017   // . Size - Offset >= NeededSize  (unsigned)
2018   return Offset >= 0 && Size >= uint64_t(Offset) &&
2019          Size - uint64_t(Offset) >= TypeSize / 8;
2020 }