e7ef9f96edc220011e02e2390db0c2ce44701b3e
[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     // Do not instrument globals from special LLVM sections.
1148     if (Section.find("__llvm") != StringRef::npos) return false;
1149
1150     // Callbacks put into the CRT initializer/terminator sections
1151     // should not be instrumented.
1152     // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1153     // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1154     if (Section.startswith(".CRT")) {
1155       DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1156       return false;
1157     }
1158
1159     if (TargetTriple.isOSBinFormatMachO()) {
1160       StringRef ParsedSegment, ParsedSection;
1161       unsigned TAA = 0, StubSize = 0;
1162       bool TAAParsed;
1163       std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1164           Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1165       if (!ErrorCode.empty()) {
1166         assert(false && "Invalid section specifier.");
1167         return false;
1168       }
1169
1170       // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1171       // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1172       // them.
1173       if (ParsedSegment == "__OBJC" ||
1174           (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1175         DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1176         return false;
1177       }
1178       // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1179       // Constant CFString instances are compiled in the following way:
1180       //  -- the string buffer is emitted into
1181       //     __TEXT,__cstring,cstring_literals
1182       //  -- the constant NSConstantString structure referencing that buffer
1183       //     is placed into __DATA,__cfstring
1184       // Therefore there's no point in placing redzones into __DATA,__cfstring.
1185       // Moreover, it causes the linker to crash on OS X 10.7
1186       if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1187         DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1188         return false;
1189       }
1190       // The linker merges the contents of cstring_literals and removes the
1191       // trailing zeroes.
1192       if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1193         DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1194         return false;
1195       }
1196     }
1197   }
1198
1199   return true;
1200 }
1201
1202 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1203   IRBuilder<> IRB(*C);
1204   // Declare our poisoning and unpoisoning functions.
1205   AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1206       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
1207   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1208   AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1209       kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
1210   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1211   // Declare functions that register/unregister globals.
1212   AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1213       kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1214   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1215   AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1216       M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1217                             IntptrTy, IntptrTy, nullptr));
1218   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1219 }
1220
1221 // This function replaces all global variables with new variables that have
1222 // trailing redzones. It also creates a function that poisons
1223 // redzones and inserts this function into llvm.global_ctors.
1224 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1225   GlobalsMD.init(M);
1226
1227   SmallVector<GlobalVariable *, 16> GlobalsToChange;
1228
1229   for (auto &G : M.globals()) {
1230     if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
1231   }
1232
1233   size_t n = GlobalsToChange.size();
1234   if (n == 0) return false;
1235
1236   // A global is described by a structure
1237   //   size_t beg;
1238   //   size_t size;
1239   //   size_t size_with_redzone;
1240   //   const char *name;
1241   //   const char *module_name;
1242   //   size_t has_dynamic_init;
1243   //   void *source_location;
1244   // We initialize an array of such structures and pass it to a run-time call.
1245   StructType *GlobalStructTy =
1246       StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1247                       IntptrTy, IntptrTy, nullptr);
1248   SmallVector<Constant *, 16> Initializers(n);
1249
1250   bool HasDynamicallyInitializedGlobals = false;
1251
1252   // We shouldn't merge same module names, as this string serves as unique
1253   // module ID in runtime.
1254   GlobalVariable *ModuleName = createPrivateGlobalForString(
1255       M, M.getModuleIdentifier(), /*AllowMerging*/ false);
1256
1257   auto &DL = M.getDataLayout();
1258   for (size_t i = 0; i < n; i++) {
1259     static const uint64_t kMaxGlobalRedzone = 1 << 18;
1260     GlobalVariable *G = GlobalsToChange[i];
1261
1262     auto MD = GlobalsMD.get(G);
1263     // Create string holding the global name (use global name from metadata
1264     // if it's available, otherwise just write the name of global variable).
1265     GlobalVariable *Name = createPrivateGlobalForString(
1266         M, MD.Name.empty() ? G->getName() : MD.Name,
1267         /*AllowMerging*/ true);
1268
1269     PointerType *PtrTy = cast<PointerType>(G->getType());
1270     Type *Ty = PtrTy->getElementType();
1271     uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
1272     uint64_t MinRZ = MinRedzoneSizeForGlobal();
1273     // MinRZ <= RZ <= kMaxGlobalRedzone
1274     // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1275     uint64_t RZ = std::max(
1276         MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
1277     uint64_t RightRedzoneSize = RZ;
1278     // Round up to MinRZ
1279     if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1280     assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1281     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1282
1283     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
1284     Constant *NewInitializer =
1285         ConstantStruct::get(NewTy, G->getInitializer(),
1286                             Constant::getNullValue(RightRedZoneTy), nullptr);
1287
1288     // Create a new global variable with enough space for a redzone.
1289     GlobalValue::LinkageTypes Linkage = G->getLinkage();
1290     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1291       Linkage = GlobalValue::InternalLinkage;
1292     GlobalVariable *NewGlobal =
1293         new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1294                            "", G, G->getThreadLocalMode());
1295     NewGlobal->copyAttributesFrom(G);
1296     NewGlobal->setAlignment(MinRZ);
1297
1298     Value *Indices2[2];
1299     Indices2[0] = IRB.getInt32(0);
1300     Indices2[1] = IRB.getInt32(0);
1301
1302     G->replaceAllUsesWith(
1303         ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
1304     NewGlobal->takeName(G);
1305     G->eraseFromParent();
1306
1307     Constant *SourceLoc;
1308     if (!MD.SourceLoc.empty()) {
1309       auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1310       SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1311     } else {
1312       SourceLoc = ConstantInt::get(IntptrTy, 0);
1313     }
1314
1315     Initializers[i] = ConstantStruct::get(
1316         GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1317         ConstantInt::get(IntptrTy, SizeInBytes),
1318         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1319         ConstantExpr::getPointerCast(Name, IntptrTy),
1320         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1321         ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
1322
1323     if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
1324
1325     DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1326   }
1327
1328   ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1329   GlobalVariable *AllGlobals = new GlobalVariable(
1330       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1331       ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1332
1333   // Create calls for poisoning before initializers run and unpoisoning after.
1334   if (HasDynamicallyInitializedGlobals)
1335     createInitializerPoisonCalls(M, ModuleName);
1336   IRB.CreateCall(AsanRegisterGlobals,
1337                  {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1338                   ConstantInt::get(IntptrTy, n)});
1339
1340   // We also need to unregister globals at the end, e.g. when a shared library
1341   // gets closed.
1342   Function *AsanDtorFunction =
1343       Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1344                        GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1345   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1346   IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1347   IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1348                       {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1349                        ConstantInt::get(IntptrTy, n)});
1350   appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1351
1352   DEBUG(dbgs() << M);
1353   return true;
1354 }
1355
1356 bool AddressSanitizerModule::runOnModule(Module &M) {
1357   C = &(M.getContext());
1358   int LongSize = M.getDataLayout().getPointerSizeInBits();
1359   IntptrTy = Type::getIntNTy(*C, LongSize);
1360   TargetTriple = Triple(M.getTargetTriple());
1361   Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
1362   initializeCallbacks(M);
1363
1364   bool Changed = false;
1365
1366   // TODO(glider): temporarily disabled globals instrumentation for KASan.
1367   if (ClGlobals && !CompileKernel) {
1368     Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1369     assert(CtorFunc);
1370     IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1371     Changed |= InstrumentGlobals(IRB, M);
1372   }
1373
1374   return Changed;
1375 }
1376
1377 void AddressSanitizer::initializeCallbacks(Module &M) {
1378   IRBuilder<> IRB(*C);
1379   // Create __asan_report* callbacks.
1380   // IsWrite, TypeSize and Exp are encoded in the function name.
1381   for (int Exp = 0; Exp < 2; Exp++) {
1382     for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1383       const std::string TypeStr = AccessIsWrite ? "store" : "load";
1384       const std::string ExpStr = Exp ? "exp_" : "";
1385       const std::string SuffixStr = CompileKernel ? "N" : "_n";
1386       const std::string EndingStr = CompileKernel ? "_noabort" : "";
1387       const Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
1388       // TODO(glider): for KASan builds add _noabort to error reporting
1389       // functions and make them actually noabort (remove the UnreachableInst).
1390       AsanErrorCallbackSized[AccessIsWrite][Exp] =
1391           checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1392               kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr,
1393               IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1394       AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
1395           checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1396               ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
1397               IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1398       for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1399            AccessSizeIndex++) {
1400         const std::string Suffix = TypeStr + itostr(1 << AccessSizeIndex);
1401         AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1402             checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1403                 kAsanReportErrorTemplate + ExpStr + Suffix,
1404                 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
1405         AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1406             checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1407                 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1408                 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
1409       }
1410     }
1411   }
1412
1413   const std::string MemIntrinCallbackPrefix =
1414       CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
1415   AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1416       MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1417       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1418   AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1419       MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1420       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1421   AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1422       MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1423       IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
1424
1425   AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
1426       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
1427
1428   AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1429       kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1430   AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1431       kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1432   // We insert an empty inline asm after __asan_report* to avoid callback merge.
1433   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1434                             StringRef(""), StringRef(""),
1435                             /*hasSideEffects=*/true);
1436 }
1437
1438 // virtual
1439 bool AddressSanitizer::doInitialization(Module &M) {
1440   // Initialize the private fields. No one has accessed them before.
1441
1442   GlobalsMD.init(M);
1443
1444   C = &(M.getContext());
1445   LongSize = M.getDataLayout().getPointerSizeInBits();
1446   IntptrTy = Type::getIntNTy(*C, LongSize);
1447   TargetTriple = Triple(M.getTargetTriple());
1448
1449   if (!CompileKernel) {
1450     std::tie(AsanCtorFunction, AsanInitFunction) =
1451         createSanitizerCtorAndInitFunctions(M, kAsanModuleCtorName, kAsanInitName,
1452                                             /*InitArgTypes=*/{},
1453                                             /*InitArgs=*/{});
1454     appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1455   }
1456   Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
1457   return true;
1458 }
1459
1460 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1461   // For each NSObject descendant having a +load method, this method is invoked
1462   // by the ObjC runtime before any of the static constructors is called.
1463   // Therefore we need to instrument such methods with a call to __asan_init
1464   // at the beginning in order to initialize our runtime before any access to
1465   // the shadow memory.
1466   // We cannot just ignore these methods, because they may call other
1467   // instrumented functions.
1468   if (F.getName().find(" load]") != std::string::npos) {
1469     IRBuilder<> IRB(F.begin()->begin());
1470     IRB.CreateCall(AsanInitFunction, {});
1471     return true;
1472   }
1473   return false;
1474 }
1475
1476 bool AddressSanitizer::runOnFunction(Function &F) {
1477   if (&F == AsanCtorFunction) return false;
1478   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1479   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1480   initializeCallbacks(*F.getParent());
1481
1482   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1483
1484   // If needed, insert __asan_init before checking for SanitizeAddress attr.
1485   maybeInsertAsanInitAtFunctionEntry(F);
1486
1487   if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
1488
1489   if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
1490
1491   // We want to instrument every address only once per basic block (unless there
1492   // are calls between uses).
1493   SmallSet<Value *, 16> TempsToInstrument;
1494   SmallVector<Instruction *, 16> ToInstrument;
1495   SmallVector<Instruction *, 8> NoReturnCalls;
1496   SmallVector<BasicBlock *, 16> AllBlocks;
1497   SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
1498   int NumAllocas = 0;
1499   bool IsWrite;
1500   unsigned Alignment;
1501   uint64_t TypeSize;
1502
1503   // Fill the set of memory operations to instrument.
1504   for (auto &BB : F) {
1505     AllBlocks.push_back(&BB);
1506     TempsToInstrument.clear();
1507     int NumInsnsPerBB = 0;
1508     for (auto &Inst : BB) {
1509       if (LooksLikeCodeInBug11395(&Inst)) return false;
1510       if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1511                                                   &Alignment)) {
1512         if (ClOpt && ClOptSameTemp) {
1513           if (!TempsToInstrument.insert(Addr).second)
1514             continue;  // We've seen this temp in the current BB.
1515         }
1516       } else if (ClInvalidPointerPairs &&
1517                  isInterestingPointerComparisonOrSubtraction(&Inst)) {
1518         PointerComparisonsOrSubtracts.push_back(&Inst);
1519         continue;
1520       } else if (isa<MemIntrinsic>(Inst)) {
1521         // ok, take it.
1522       } else {
1523         if (isa<AllocaInst>(Inst)) NumAllocas++;
1524         CallSite CS(&Inst);
1525         if (CS) {
1526           // A call inside BB.
1527           TempsToInstrument.clear();
1528           if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
1529         }
1530         continue;
1531       }
1532       ToInstrument.push_back(&Inst);
1533       NumInsnsPerBB++;
1534       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
1535     }
1536   }
1537
1538   bool UseCalls =
1539       CompileKernel ||
1540       (ClInstrumentationWithCallsThreshold >= 0 &&
1541        ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
1542   const TargetLibraryInfo *TLI =
1543       &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1544   const DataLayout &DL = F.getParent()->getDataLayout();
1545   ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1546                                      /*RoundToAlign=*/true);
1547
1548   // Instrument.
1549   int NumInstrumented = 0;
1550   for (auto Inst : ToInstrument) {
1551     if (ClDebugMin < 0 || ClDebugMax < 0 ||
1552         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1553       if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
1554         instrumentMop(ObjSizeVis, Inst, UseCalls,
1555                       F.getParent()->getDataLayout());
1556       else
1557         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1558     }
1559     NumInstrumented++;
1560   }
1561
1562   FunctionStackPoisoner FSP(F, *this);
1563   bool ChangedStack = FSP.runOnFunction();
1564
1565   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1566   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1567   for (auto CI : NoReturnCalls) {
1568     IRBuilder<> IRB(CI);
1569     IRB.CreateCall(AsanHandleNoReturnFunc, {});
1570   }
1571
1572   for (auto Inst : PointerComparisonsOrSubtracts) {
1573     instrumentPointerComparisonOrSubtraction(Inst);
1574     NumInstrumented++;
1575   }
1576
1577   bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1578
1579   DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1580
1581   return res;
1582 }
1583
1584 // Workaround for bug 11395: we don't want to instrument stack in functions
1585 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1586 // FIXME: remove once the bug 11395 is fixed.
1587 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1588   if (LongSize != 32) return false;
1589   CallInst *CI = dyn_cast<CallInst>(I);
1590   if (!CI || !CI->isInlineAsm()) return false;
1591   if (CI->getNumArgOperands() <= 5) return false;
1592   // We have inline assembly with quite a few arguments.
1593   return true;
1594 }
1595
1596 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1597   IRBuilder<> IRB(*C);
1598   for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1599     std::string Suffix = itostr(i);
1600     AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1601         M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1602                               IntptrTy, nullptr));
1603     AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
1604         M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1605                               IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1606   }
1607   AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1608       M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1609                             IntptrTy, IntptrTy, nullptr));
1610   AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1611       M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1612                             IntptrTy, IntptrTy, nullptr));
1613   AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1614       kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1615   AsanAllocasUnpoisonFunc =
1616       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1617           kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1618 }
1619
1620 void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1621                                            IRBuilder<> &IRB, Value *ShadowBase,
1622                                            bool DoPoison) {
1623   size_t n = ShadowBytes.size();
1624   size_t i = 0;
1625   // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1626   // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1627   // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1628   for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1629        LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1630     for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1631       uint64_t Val = 0;
1632       for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1633         if (F.getParent()->getDataLayout().isLittleEndian())
1634           Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1635         else
1636           Val = (Val << 8) | ShadowBytes[i + j];
1637       }
1638       if (!Val) continue;
1639       Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1640       Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1641       Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1642       IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1643     }
1644   }
1645 }
1646
1647 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1648 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1649 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1650   assert(LocalStackSize <= kMaxStackMallocSize);
1651   uint64_t MaxSize = kMinStackMallocSize;
1652   for (int i = 0;; i++, MaxSize *= 2)
1653     if (LocalStackSize <= MaxSize) return i;
1654   llvm_unreachable("impossible LocalStackSize");
1655 }
1656
1657 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1658 // We can not use MemSet intrinsic because it may end up calling the actual
1659 // memset. Size is a multiple of 8.
1660 // Currently this generates 8-byte stores on x86_64; it may be better to
1661 // generate wider stores.
1662 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1663     IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1664   assert(!(Size % 8));
1665
1666   // kAsanStackAfterReturnMagic is 0xf5.
1667   const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
1668
1669   for (int i = 0; i < Size; i += 8) {
1670     Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1671     IRB.CreateStore(
1672         ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1673         IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1674   }
1675 }
1676
1677 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1678                                           Value *ValueIfTrue,
1679                                           Instruction *ThenTerm,
1680                                           Value *ValueIfFalse) {
1681   PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1682   BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1683   PHI->addIncoming(ValueIfFalse, CondBlock);
1684   BasicBlock *ThenBlock = ThenTerm->getParent();
1685   PHI->addIncoming(ValueIfTrue, ThenBlock);
1686   return PHI;
1687 }
1688
1689 Value *FunctionStackPoisoner::createAllocaForLayout(
1690     IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1691   AllocaInst *Alloca;
1692   if (Dynamic) {
1693     Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1694                               ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1695                               "MyAlloca");
1696   } else {
1697     Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1698                               nullptr, "MyAlloca");
1699     assert(Alloca->isStaticAlloca());
1700   }
1701   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1702   size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1703   Alloca->setAlignment(FrameAlignment);
1704   return IRB.CreatePointerCast(Alloca, IntptrTy);
1705 }
1706
1707 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1708   BasicBlock &FirstBB = *F.begin();
1709   IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1710   DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1711   IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1712   DynamicAllocaLayout->setAlignment(32);
1713 }
1714
1715 void FunctionStackPoisoner::poisonStack() {
1716   assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1717
1718   if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
1719     // Handle dynamic allocas.
1720     createDynamicAllocasInitStorage();
1721     for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
1722
1723     unpoisonDynamicAllocas();
1724   }
1725
1726   if (AllocaVec.size() == 0) return;
1727
1728   int StackMallocIdx = -1;
1729   DebugLoc EntryDebugLocation;
1730   if (auto SP = getDISubprogram(&F))
1731     EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
1732
1733   Instruction *InsBefore = AllocaVec[0];
1734   IRBuilder<> IRB(InsBefore);
1735   IRB.SetCurrentDebugLocation(EntryDebugLocation);
1736
1737   SmallVector<ASanStackVariableDescription, 16> SVD;
1738   SVD.reserve(AllocaVec.size());
1739   for (AllocaInst *AI : AllocaVec) {
1740     ASanStackVariableDescription D = {AI->getName().data(),
1741                                       ASan.getAllocaSizeInBytes(AI),
1742                                       AI->getAlignment(), AI, 0};
1743     SVD.push_back(D);
1744   }
1745   // Minimal header size (left redzone) is 4 pointers,
1746   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1747   size_t MinHeaderSize = ASan.LongSize / 2;
1748   ASanStackFrameLayout L;
1749   ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1750   DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1751   uint64_t LocalStackSize = L.FrameSize;
1752   bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
1753                        LocalStackSize <= kMaxStackMallocSize;
1754   // Don't do dynamic alloca or stack malloc in presence of inline asm:
1755   // too often it makes assumptions on which registers are available.
1756   bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm;
1757   DoStackMalloc &= !HasNonEmptyInlineAsm;
1758
1759   Value *StaticAlloca =
1760       DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1761
1762   Value *FakeStack;
1763   Value *LocalStackBase;
1764
1765   if (DoStackMalloc) {
1766     // void *FakeStack = __asan_option_detect_stack_use_after_return
1767     //     ? __asan_stack_malloc_N(LocalStackSize)
1768     //     : nullptr;
1769     // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
1770     Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1771         kAsanOptionDetectUAR, IRB.getInt32Ty());
1772     Value *UARIsEnabled =
1773         IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1774                          Constant::getNullValue(IRB.getInt32Ty()));
1775     Instruction *Term =
1776         SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
1777     IRBuilder<> IRBIf(Term);
1778     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1779     StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1780     assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1781     Value *FakeStackValue =
1782         IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1783                          ConstantInt::get(IntptrTy, LocalStackSize));
1784     IRB.SetInsertPoint(InsBefore);
1785     IRB.SetCurrentDebugLocation(EntryDebugLocation);
1786     FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1787                           ConstantInt::get(IntptrTy, 0));
1788
1789     Value *NoFakeStack =
1790         IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1791     Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1792     IRBIf.SetInsertPoint(Term);
1793     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1794     Value *AllocaValue =
1795         DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1796     IRB.SetInsertPoint(InsBefore);
1797     IRB.SetCurrentDebugLocation(EntryDebugLocation);
1798     LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1799   } else {
1800     // void *FakeStack = nullptr;
1801     // void *LocalStackBase = alloca(LocalStackSize);
1802     FakeStack = ConstantInt::get(IntptrTy, 0);
1803     LocalStackBase =
1804         DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
1805   }
1806
1807   // Insert poison calls for lifetime intrinsics for alloca.
1808   bool HavePoisonedAllocas = false;
1809   for (const auto &APC : AllocaPoisonCallVec) {
1810     assert(APC.InsBefore);
1811     assert(APC.AI);
1812     IRBuilder<> IRB(APC.InsBefore);
1813     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1814     HavePoisonedAllocas |= APC.DoPoison;
1815   }
1816
1817   // Replace Alloca instructions with base+offset.
1818   for (const auto &Desc : SVD) {
1819     AllocaInst *AI = Desc.AI;
1820     Value *NewAllocaPtr = IRB.CreateIntToPtr(
1821         IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
1822         AI->getType());
1823     replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
1824     AI->replaceAllUsesWith(NewAllocaPtr);
1825   }
1826
1827   // The left-most redzone has enough space for at least 4 pointers.
1828   // Write the Magic value to redzone[0].
1829   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1830   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1831                   BasePlus0);
1832   // Write the frame description constant to redzone[1].
1833   Value *BasePlus1 = IRB.CreateIntToPtr(
1834       IRB.CreateAdd(LocalStackBase,
1835                     ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
1836       IntptrPtrTy);
1837   GlobalVariable *StackDescriptionGlobal =
1838       createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1839                                    /*AllowMerging*/ true);
1840   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
1841   IRB.CreateStore(Description, BasePlus1);
1842   // Write the PC to redzone[2].
1843   Value *BasePlus2 = IRB.CreateIntToPtr(
1844       IRB.CreateAdd(LocalStackBase,
1845                     ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
1846       IntptrPtrTy);
1847   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1848
1849   // Poison the stack redzones at the entry.
1850   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1851   poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1852
1853   // (Un)poison the stack before all ret instructions.
1854   for (auto Ret : RetVec) {
1855     IRBuilder<> IRBRet(Ret);
1856     // Mark the current frame as retired.
1857     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1858                        BasePlus0);
1859     if (DoStackMalloc) {
1860       assert(StackMallocIdx >= 0);
1861       // if FakeStack != 0  // LocalStackBase == FakeStack
1862       //     // In use-after-return mode, poison the whole stack frame.
1863       //     if StackMallocIdx <= 4
1864       //         // For small sizes inline the whole thing:
1865       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1866       //         **SavedFlagPtr(FakeStack) = 0
1867       //     else
1868       //         __asan_stack_free_N(FakeStack, LocalStackSize)
1869       // else
1870       //     <This is not a fake stack; unpoison the redzones>
1871       Value *Cmp =
1872           IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
1873       TerminatorInst *ThenTerm, *ElseTerm;
1874       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1875
1876       IRBuilder<> IRBPoison(ThenTerm);
1877       if (StackMallocIdx <= 4) {
1878         int ClassSize = kMinStackMallocSize << StackMallocIdx;
1879         SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1880                                            ClassSize >> Mapping.Scale);
1881         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1882             FakeStack,
1883             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1884         Value *SavedFlagPtr = IRBPoison.CreateLoad(
1885             IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1886         IRBPoison.CreateStore(
1887             Constant::getNullValue(IRBPoison.getInt8Ty()),
1888             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1889       } else {
1890         // For larger frames call __asan_stack_free_*.
1891         IRBPoison.CreateCall(
1892             AsanStackFreeFunc[StackMallocIdx],
1893             {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
1894       }
1895
1896       IRBuilder<> IRBElse(ElseTerm);
1897       poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1898     } else if (HavePoisonedAllocas) {
1899       // If we poisoned some allocas in llvm.lifetime analysis,
1900       // unpoison whole stack frame now.
1901       poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1902     } else {
1903       poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1904     }
1905   }
1906
1907   // We are done. Remove the old unused alloca instructions.
1908   for (auto AI : AllocaVec) AI->eraseFromParent();
1909 }
1910
1911 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1912                                          IRBuilder<> &IRB, bool DoPoison) {
1913   // For now just insert the call to ASan runtime.
1914   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1915   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1916   IRB.CreateCall(
1917       DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
1918       {AddrArg, SizeArg});
1919 }
1920
1921 // Handling llvm.lifetime intrinsics for a given %alloca:
1922 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1923 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1924 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1925 //     could be poisoned by previous llvm.lifetime.end instruction, as the
1926 //     variable may go in and out of scope several times, e.g. in loops).
1927 // (3) if we poisoned at least one %alloca in a function,
1928 //     unpoison the whole stack frame at function exit.
1929
1930 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1931   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1932     // We're intested only in allocas we can handle.
1933     return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
1934   // See if we've already calculated (or started to calculate) alloca for a
1935   // given value.
1936   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1937   if (I != AllocaForValue.end()) return I->second;
1938   // Store 0 while we're calculating alloca for value V to avoid
1939   // infinite recursion if the value references itself.
1940   AllocaForValue[V] = nullptr;
1941   AllocaInst *Res = nullptr;
1942   if (CastInst *CI = dyn_cast<CastInst>(V))
1943     Res = findAllocaForValue(CI->getOperand(0));
1944   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1945     for (Value *IncValue : PN->incoming_values()) {
1946       // Allow self-referencing phi-nodes.
1947       if (IncValue == PN) continue;
1948       AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1949       // AI for incoming values should exist and should all be equal.
1950       if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1951         return nullptr;
1952       Res = IncValueAI;
1953     }
1954   }
1955   if (Res) AllocaForValue[V] = Res;
1956   return Res;
1957 }
1958
1959 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
1960   IRBuilder<> IRB(AI);
1961
1962   const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1963   const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1964
1965   Value *Zero = Constant::getNullValue(IntptrTy);
1966   Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1967   Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
1968
1969   // Since we need to extend alloca with additional memory to locate
1970   // redzones, and OldSize is number of allocated blocks with
1971   // ElementSize size, get allocated memory size in bytes by
1972   // OldSize * ElementSize.
1973   const unsigned ElementSize =
1974       F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
1975   Value *OldSize =
1976       IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
1977                     ConstantInt::get(IntptrTy, ElementSize));
1978
1979   // PartialSize = OldSize % 32
1980   Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1981
1982   // Misalign = kAllocaRzSize - PartialSize;
1983   Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1984
1985   // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1986   Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1987   Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1988
1989   // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
1990   // Align is added to locate left redzone, PartialPadding for possible
1991   // partial redzone and kAllocaRzSize for right redzone respectively.
1992   Value *AdditionalChunkSize = IRB.CreateAdd(
1993       ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
1994
1995   Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
1996
1997   // Insert new alloca with new NewSize and Align params.
1998   AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
1999   NewAlloca->setAlignment(Align);
2000
2001   // NewAddress = Address + Align
2002   Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2003                                     ConstantInt::get(IntptrTy, Align));
2004
2005   // Insert __asan_alloca_poison call for new created alloca.
2006   IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
2007
2008   // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2009   // for unpoisoning stuff.
2010   IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2011
2012   Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2013
2014   // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
2015   AI->replaceAllUsesWith(NewAddressPtr);
2016
2017   // We are done. Erase old alloca from parent.
2018   AI->eraseFromParent();
2019 }
2020
2021 // isSafeAccess returns true if Addr is always inbounds with respect to its
2022 // base object. For example, it is a field access or an array access with
2023 // constant inbounds index.
2024 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2025                                     Value *Addr, uint64_t TypeSize) const {
2026   SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2027   if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
2028   uint64_t Size = SizeOffset.first.getZExtValue();
2029   int64_t Offset = SizeOffset.second.getSExtValue();
2030   // Three checks are required to ensure safety:
2031   // . Offset >= 0  (since the offset is given from the base ptr)
2032   // . Size >= Offset  (unsigned)
2033   // . Size - Offset >= NeededSize  (unsigned)
2034   return Offset >= 0 && Size >= uint64_t(Offset) &&
2035          Size - uint64_t(Offset) >= TypeSize / 8;
2036 }