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