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