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