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