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