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