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