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