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