LLVM API Documentation

AddressSanitizer.cpp
Go to the documentation of this file.
00001 //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file is a part of AddressSanitizer, an address sanity checker.
00011 // Details of the algorithm:
00012 //  http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/Transforms/Instrumentation.h"
00017 #include "llvm/ADT/ArrayRef.h"
00018 #include "llvm/ADT/DenseMap.h"
00019 #include "llvm/ADT/DenseSet.h"
00020 #include "llvm/ADT/DepthFirstIterator.h"
00021 #include "llvm/ADT/SmallSet.h"
00022 #include "llvm/ADT/SmallString.h"
00023 #include "llvm/ADT/SmallVector.h"
00024 #include "llvm/ADT/Statistic.h"
00025 #include "llvm/ADT/StringExtras.h"
00026 #include "llvm/ADT/Triple.h"
00027 #include "llvm/IR/CallSite.h"
00028 #include "llvm/IR/DIBuilder.h"
00029 #include "llvm/IR/DataLayout.h"
00030 #include "llvm/IR/Function.h"
00031 #include "llvm/IR/IRBuilder.h"
00032 #include "llvm/IR/InlineAsm.h"
00033 #include "llvm/IR/InstVisitor.h"
00034 #include "llvm/IR/IntrinsicInst.h"
00035 #include "llvm/IR/LLVMContext.h"
00036 #include "llvm/IR/MDBuilder.h"
00037 #include "llvm/IR/Module.h"
00038 #include "llvm/IR/Type.h"
00039 #include "llvm/Support/CommandLine.h"
00040 #include "llvm/Support/DataTypes.h"
00041 #include "llvm/Support/Debug.h"
00042 #include "llvm/Support/Endian.h"
00043 #include "llvm/Transforms/Scalar.h"
00044 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
00045 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00046 #include "llvm/Transforms/Utils/Cloning.h"
00047 #include "llvm/Transforms/Utils/Local.h"
00048 #include "llvm/Transforms/Utils/ModuleUtils.h"
00049 #include <algorithm>
00050 #include <string>
00051 #include <system_error>
00052 
00053 using namespace llvm;
00054 
00055 #define DEBUG_TYPE "asan"
00056 
00057 static const uint64_t kDefaultShadowScale = 3;
00058 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
00059 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
00060 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
00061 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000;  // < 2G.
00062 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
00063 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
00064 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
00065 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
00066 
00067 static const size_t kMinStackMallocSize = 1 << 6;  // 64B
00068 static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
00069 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
00070 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
00071 
00072 static const char *const kAsanModuleCtorName = "asan.module_ctor";
00073 static const char *const kAsanModuleDtorName = "asan.module_dtor";
00074 static const int         kAsanCtorAndDtorPriority = 1;
00075 static const char *const kAsanReportErrorTemplate = "__asan_report_";
00076 static const char *const kAsanReportLoadN = "__asan_report_load_n";
00077 static const char *const kAsanReportStoreN = "__asan_report_store_n";
00078 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
00079 static const char *const kAsanUnregisterGlobalsName =
00080     "__asan_unregister_globals";
00081 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
00082 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
00083 static const char *const kAsanInitName = "__asan_init_v4";
00084 static const char *const kAsanCovModuleInitName = "__sanitizer_cov_module_init";
00085 static const char *const kAsanCovName = "__sanitizer_cov";
00086 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
00087 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
00088 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
00089 static const int         kMaxAsanStackMallocSizeClass = 10;
00090 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
00091 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
00092 static const char *const kAsanGenPrefix = "__asan_gen_";
00093 static const char *const kAsanPoisonStackMemoryName =
00094     "__asan_poison_stack_memory";
00095 static const char *const kAsanUnpoisonStackMemoryName =
00096     "__asan_unpoison_stack_memory";
00097 
00098 static const char *const kAsanOptionDetectUAR =
00099     "__asan_option_detect_stack_use_after_return";
00100 
00101 #ifndef NDEBUG
00102 static const int kAsanStackAfterReturnMagic = 0xf5;
00103 #endif
00104 
00105 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
00106 static const size_t kNumberOfAccessSizes = 5;
00107 
00108 // Command-line flags.
00109 
00110 // This flag may need to be replaced with -f[no-]asan-reads.
00111 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
00112        cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
00113 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
00114        cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
00115 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
00116        cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
00117        cl::Hidden, cl::init(true));
00118 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
00119        cl::desc("use instrumentation with slow path for all accesses"),
00120        cl::Hidden, cl::init(false));
00121 // This flag limits the number of instructions to be instrumented
00122 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
00123 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
00124 // set it to 10000.
00125 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
00126        cl::init(10000),
00127        cl::desc("maximal number of instructions to instrument in any given BB"),
00128        cl::Hidden);
00129 // This flag may need to be replaced with -f[no]asan-stack.
00130 static cl::opt<bool> ClStack("asan-stack",
00131        cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
00132 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
00133        cl::desc("Check return-after-free"), cl::Hidden, cl::init(true));
00134 // This flag may need to be replaced with -f[no]asan-globals.
00135 static cl::opt<bool> ClGlobals("asan-globals",
00136        cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
00137 static cl::opt<int> ClCoverage("asan-coverage",
00138        cl::desc("ASan coverage. 0: none, 1: entry block, 2: all blocks, "
00139                 "3: all blocks and critical edges"),
00140        cl::Hidden, cl::init(false));
00141 static cl::opt<int> ClCoverageBlockThreshold("asan-coverage-block-threshold",
00142        cl::desc("Add coverage instrumentation only to the entry block if there "
00143                 "are more than this number of blocks."),
00144        cl::Hidden, cl::init(1500));
00145 static cl::opt<bool> ClInitializers("asan-initialization-order",
00146        cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
00147 static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
00148        cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
00149        cl::Hidden, cl::init(false));
00150 static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
00151        cl::desc("Realign stack to the value of this flag (power of two)"),
00152        cl::Hidden, cl::init(32));
00153 static cl::opt<int> ClInstrumentationWithCallsThreshold(
00154     "asan-instrumentation-with-call-threshold",
00155        cl::desc("If the function being instrumented contains more than "
00156                 "this number of memory accesses, use callbacks instead of "
00157                 "inline checks (-1 means never use callbacks)."),
00158        cl::Hidden, cl::init(7000));
00159 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
00160        "asan-memory-access-callback-prefix",
00161        cl::desc("Prefix for memory access callbacks"), cl::Hidden,
00162        cl::init("__asan_"));
00163 
00164 // This is an experimental feature that will allow to choose between
00165 // instrumented and non-instrumented code at link-time.
00166 // If this option is on, just before instrumenting a function we create its
00167 // clone; if the function is not changed by asan the clone is deleted.
00168 // If we end up with a clone, we put the instrumented function into a section
00169 // called "ASAN" and the uninstrumented function into a section called "NOASAN".
00170 //
00171 // This is still a prototype, we need to figure out a way to keep two copies of
00172 // a function so that the linker can easily choose one of them.
00173 static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
00174        cl::desc("Keep uninstrumented copies of functions"),
00175        cl::Hidden, cl::init(false));
00176 
00177 // These flags allow to change the shadow mapping.
00178 // The shadow mapping looks like
00179 //    Shadow = (Mem >> scale) + (1 << offset_log)
00180 static cl::opt<int> ClMappingScale("asan-mapping-scale",
00181        cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
00182 
00183 // Optimization flags. Not user visible, used mostly for testing
00184 // and benchmarking the tool.
00185 static cl::opt<bool> ClOpt("asan-opt",
00186        cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
00187 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
00188        cl::desc("Instrument the same temp just once"), cl::Hidden,
00189        cl::init(true));
00190 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
00191        cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
00192 
00193 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
00194        cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
00195        cl::Hidden, cl::init(false));
00196 
00197 // Debug flags.
00198 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
00199                             cl::init(0));
00200 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
00201                                  cl::Hidden, cl::init(0));
00202 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
00203                                         cl::Hidden, cl::desc("Debug func"));
00204 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
00205                                cl::Hidden, cl::init(-1));
00206 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
00207                                cl::Hidden, cl::init(-1));
00208 
00209 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
00210 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
00211 STATISTIC(NumOptimizedAccessesToGlobalArray,
00212           "Number of optimized accesses to global arrays");
00213 STATISTIC(NumOptimizedAccessesToGlobalVar,
00214           "Number of optimized accesses to global vars");
00215 
00216 namespace {
00217 /// Frontend-provided metadata for source location.
00218 struct LocationMetadata {
00219   StringRef Filename;
00220   int LineNo;
00221   int ColumnNo;
00222 
00223   LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
00224 
00225   bool empty() const { return Filename.empty(); }
00226 
00227   void parse(MDNode *MDN) {
00228     assert(MDN->getNumOperands() == 3);
00229     MDString *MDFilename = cast<MDString>(MDN->getOperand(0));
00230     Filename = MDFilename->getString();
00231     LineNo = cast<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
00232     ColumnNo = cast<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
00233   }
00234 };
00235 
00236 /// Frontend-provided metadata for global variables.
00237 class GlobalsMetadata {
00238  public:
00239   struct Entry {
00240     Entry()
00241         : SourceLoc(), Name(), IsDynInit(false),
00242           IsBlacklisted(false) {}
00243     LocationMetadata SourceLoc;
00244     StringRef Name;
00245     bool IsDynInit;
00246     bool IsBlacklisted;
00247   };
00248 
00249   GlobalsMetadata() : inited_(false) {}
00250 
00251   void init(Module& M) {
00252     assert(!inited_);
00253     inited_ = true;
00254     NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
00255     if (!Globals)
00256       return;
00257     for (auto MDN : Globals->operands()) {
00258       // Metadata node contains the global and the fields of "Entry".
00259       assert(MDN->getNumOperands() == 5);
00260       Value *V = MDN->getOperand(0);
00261       // The optimizer may optimize away a global entirely.
00262       if (!V)
00263         continue;
00264       GlobalVariable *GV = cast<GlobalVariable>(V);
00265       // We can already have an entry for GV if it was merged with another
00266       // global.
00267       Entry &E = Entries[GV];
00268       if (Value *Loc = MDN->getOperand(1))
00269         E.SourceLoc.parse(cast<MDNode>(Loc));
00270       if (Value *Name = MDN->getOperand(2)) {
00271         MDString *MDName = cast<MDString>(Name);
00272         E.Name = MDName->getString();
00273       }
00274       ConstantInt *IsDynInit = cast<ConstantInt>(MDN->getOperand(3));
00275       E.IsDynInit |= IsDynInit->isOne();
00276       ConstantInt *IsBlacklisted = cast<ConstantInt>(MDN->getOperand(4));
00277       E.IsBlacklisted |= IsBlacklisted->isOne();
00278     }
00279   }
00280 
00281   /// Returns metadata entry for a given global.
00282   Entry get(GlobalVariable *G) const {
00283     auto Pos = Entries.find(G);
00284     return (Pos != Entries.end()) ? Pos->second : Entry();
00285   }
00286 
00287  private:
00288   bool inited_;
00289   DenseMap<GlobalVariable*, Entry> Entries;
00290 };
00291 
00292 /// This struct defines the shadow mapping using the rule:
00293 ///   shadow = (mem >> Scale) ADD-or-OR Offset.
00294 struct ShadowMapping {
00295   int Scale;
00296   uint64_t Offset;
00297   bool OrShadowOffset;
00298 };
00299 
00300 static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
00301   llvm::Triple TargetTriple(M.getTargetTriple());
00302   bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
00303   bool IsIOS = TargetTriple.getOS() == llvm::Triple::IOS;
00304   bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
00305   bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
00306   bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
00307                  TargetTriple.getArch() == llvm::Triple::ppc64le;
00308   bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
00309   bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
00310                   TargetTriple.getArch() == llvm::Triple::mipsel;
00311 
00312   ShadowMapping Mapping;
00313 
00314   if (LongSize == 32) {
00315     if (IsAndroid)
00316       Mapping.Offset = 0;
00317     else if (IsMIPS32)
00318       Mapping.Offset = kMIPS32_ShadowOffset32;
00319     else if (IsFreeBSD)
00320       Mapping.Offset = kFreeBSD_ShadowOffset32;
00321     else if (IsIOS)
00322       Mapping.Offset = kIOSShadowOffset32;
00323     else
00324       Mapping.Offset = kDefaultShadowOffset32;
00325   } else {  // LongSize == 64
00326     if (IsPPC64)
00327       Mapping.Offset = kPPC64_ShadowOffset64;
00328     else if (IsFreeBSD)
00329       Mapping.Offset = kFreeBSD_ShadowOffset64;
00330     else if (IsLinux && IsX86_64)
00331       Mapping.Offset = kSmallX86_64ShadowOffset;
00332     else
00333       Mapping.Offset = kDefaultShadowOffset64;
00334   }
00335 
00336   Mapping.Scale = kDefaultShadowScale;
00337   if (ClMappingScale) {
00338     Mapping.Scale = ClMappingScale;
00339   }
00340 
00341   // OR-ing shadow offset if more efficient (at least on x86) if the offset
00342   // is a power of two, but on ppc64 we have to use add since the shadow
00343   // offset is not necessary 1/8-th of the address space.
00344   Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
00345 
00346   return Mapping;
00347 }
00348 
00349 static size_t RedzoneSizeForScale(int MappingScale) {
00350   // Redzone used for stack and globals is at least 32 bytes.
00351   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
00352   return std::max(32U, 1U << MappingScale);
00353 }
00354 
00355 /// AddressSanitizer: instrument the code in module to find memory bugs.
00356 struct AddressSanitizer : public FunctionPass {
00357   AddressSanitizer() : FunctionPass(ID) {
00358     initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
00359   }
00360   const char *getPassName() const override {
00361     return "AddressSanitizerFunctionPass";
00362   }
00363   void instrumentMop(Instruction *I, bool UseCalls);
00364   void instrumentPointerComparisonOrSubtraction(Instruction *I);
00365   void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
00366                          Value *Addr, uint32_t TypeSize, bool IsWrite,
00367                          Value *SizeArgument, bool UseCalls);
00368   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
00369                            Value *ShadowValue, uint32_t TypeSize);
00370   Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
00371                                  bool IsWrite, size_t AccessSizeIndex,
00372                                  Value *SizeArgument);
00373   void instrumentMemIntrinsic(MemIntrinsic *MI);
00374   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
00375   bool runOnFunction(Function &F) override;
00376   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
00377   bool doInitialization(Module &M) override;
00378   static char ID;  // Pass identification, replacement for typeid
00379 
00380   void getAnalysisUsage(AnalysisUsage &AU) const override {
00381     if (ClCoverage >= 3)
00382       AU.addRequiredID(BreakCriticalEdgesID);
00383   }
00384 
00385  private:
00386   void initializeCallbacks(Module &M);
00387 
00388   bool LooksLikeCodeInBug11395(Instruction *I);
00389   bool GlobalIsLinkerInitialized(GlobalVariable *G);
00390   bool InjectCoverage(Function &F, ArrayRef<BasicBlock*> AllBlocks);
00391   void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
00392 
00393   LLVMContext *C;
00394   const DataLayout *DL;
00395   int LongSize;
00396   Type *IntptrTy;
00397   ShadowMapping Mapping;
00398   Function *AsanCtorFunction;
00399   Function *AsanInitFunction;
00400   Function *AsanHandleNoReturnFunc;
00401   Function *AsanCovFunction;
00402   Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
00403   // This array is indexed by AccessIsWrite and log2(AccessSize).
00404   Function *AsanErrorCallback[2][kNumberOfAccessSizes];
00405   Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
00406   // This array is indexed by AccessIsWrite.
00407   Function *AsanErrorCallbackSized[2],
00408            *AsanMemoryAccessCallbackSized[2];
00409   Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
00410   InlineAsm *EmptyAsm;
00411   GlobalsMetadata GlobalsMD;
00412 
00413   friend struct FunctionStackPoisoner;
00414 };
00415 
00416 class AddressSanitizerModule : public ModulePass {
00417  public:
00418   AddressSanitizerModule() : ModulePass(ID) {}
00419   bool runOnModule(Module &M) override;
00420   static char ID;  // Pass identification, replacement for typeid
00421   const char *getPassName() const override {
00422     return "AddressSanitizerModule";
00423   }
00424 
00425  private:
00426   void initializeCallbacks(Module &M);
00427 
00428   bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
00429   bool ShouldInstrumentGlobal(GlobalVariable *G);
00430   void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
00431   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
00432   size_t MinRedzoneSizeForGlobal() const {
00433     return RedzoneSizeForScale(Mapping.Scale);
00434   }
00435 
00436   GlobalsMetadata GlobalsMD;
00437   Type *IntptrTy;
00438   LLVMContext *C;
00439   const DataLayout *DL;
00440   ShadowMapping Mapping;
00441   Function *AsanPoisonGlobals;
00442   Function *AsanUnpoisonGlobals;
00443   Function *AsanRegisterGlobals;
00444   Function *AsanUnregisterGlobals;
00445   Function *AsanCovModuleInit;
00446 };
00447 
00448 // Stack poisoning does not play well with exception handling.
00449 // When an exception is thrown, we essentially bypass the code
00450 // that unpoisones the stack. This is why the run-time library has
00451 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
00452 // stack in the interceptor. This however does not work inside the
00453 // actual function which catches the exception. Most likely because the
00454 // compiler hoists the load of the shadow value somewhere too high.
00455 // This causes asan to report a non-existing bug on 453.povray.
00456 // It sounds like an LLVM bug.
00457 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
00458   Function &F;
00459   AddressSanitizer &ASan;
00460   DIBuilder DIB;
00461   LLVMContext *C;
00462   Type *IntptrTy;
00463   Type *IntptrPtrTy;
00464   ShadowMapping Mapping;
00465 
00466   SmallVector<AllocaInst*, 16> AllocaVec;
00467   SmallVector<Instruction*, 8> RetVec;
00468   unsigned StackAlignment;
00469 
00470   Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
00471            *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
00472   Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
00473 
00474   // Stores a place and arguments of poisoning/unpoisoning call for alloca.
00475   struct AllocaPoisonCall {
00476     IntrinsicInst *InsBefore;
00477     AllocaInst *AI;
00478     uint64_t Size;
00479     bool DoPoison;
00480   };
00481   SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
00482 
00483   // Maps Value to an AllocaInst from which the Value is originated.
00484   typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
00485   AllocaForValueMapTy AllocaForValue;
00486 
00487   FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
00488       : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
00489         IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
00490         Mapping(ASan.Mapping),
00491         StackAlignment(1 << Mapping.Scale) {}
00492 
00493   bool runOnFunction() {
00494     if (!ClStack) return false;
00495     // Collect alloca, ret, lifetime instructions etc.
00496     for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
00497       visit(*BB);
00498 
00499     if (AllocaVec.empty()) return false;
00500 
00501     initializeCallbacks(*F.getParent());
00502 
00503     poisonStack();
00504 
00505     if (ClDebugStack) {
00506       DEBUG(dbgs() << F);
00507     }
00508     return true;
00509   }
00510 
00511   // Finds all static Alloca instructions and puts
00512   // poisoned red zones around all of them.
00513   // Then unpoison everything back before the function returns.
00514   void poisonStack();
00515 
00516   // ----------------------- Visitors.
00517   /// \brief Collect all Ret instructions.
00518   void visitReturnInst(ReturnInst &RI) {
00519     RetVec.push_back(&RI);
00520   }
00521 
00522   /// \brief Collect Alloca instructions we want (and can) handle.
00523   void visitAllocaInst(AllocaInst &AI) {
00524     if (!isInterestingAlloca(AI)) return;
00525 
00526     StackAlignment = std::max(StackAlignment, AI.getAlignment());
00527     AllocaVec.push_back(&AI);
00528   }
00529 
00530   /// \brief Collect lifetime intrinsic calls to check for use-after-scope
00531   /// errors.
00532   void visitIntrinsicInst(IntrinsicInst &II) {
00533     if (!ClCheckLifetime) return;
00534     Intrinsic::ID ID = II.getIntrinsicID();
00535     if (ID != Intrinsic::lifetime_start &&
00536         ID != Intrinsic::lifetime_end)
00537       return;
00538     // Found lifetime intrinsic, add ASan instrumentation if necessary.
00539     ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
00540     // If size argument is undefined, don't do anything.
00541     if (Size->isMinusOne()) return;
00542     // Check that size doesn't saturate uint64_t and can
00543     // be stored in IntptrTy.
00544     const uint64_t SizeValue = Size->getValue().getLimitedValue();
00545     if (SizeValue == ~0ULL ||
00546         !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
00547       return;
00548     // Find alloca instruction that corresponds to llvm.lifetime argument.
00549     AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
00550     if (!AI) return;
00551     bool DoPoison = (ID == Intrinsic::lifetime_end);
00552     AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
00553     AllocaPoisonCallVec.push_back(APC);
00554   }
00555 
00556   // ---------------------- Helpers.
00557   void initializeCallbacks(Module &M);
00558 
00559   // Check if we want (and can) handle this alloca.
00560   bool isInterestingAlloca(AllocaInst &AI) const {
00561     return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
00562             AI.getAllocatedType()->isSized() &&
00563             // alloca() may be called with 0 size, ignore it.
00564             getAllocaSizeInBytes(&AI) > 0);
00565   }
00566 
00567   uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
00568     Type *Ty = AI->getAllocatedType();
00569     uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
00570     return SizeInBytes;
00571   }
00572   /// Finds alloca where the value comes from.
00573   AllocaInst *findAllocaForValue(Value *V);
00574   void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
00575                       Value *ShadowBase, bool DoPoison);
00576   void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
00577 
00578   void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
00579                                           int Size);
00580 };
00581 
00582 }  // namespace
00583 
00584 char AddressSanitizer::ID = 0;
00585 INITIALIZE_PASS(AddressSanitizer, "asan",
00586     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
00587     false, false)
00588 FunctionPass *llvm::createAddressSanitizerFunctionPass() {
00589   return new AddressSanitizer();
00590 }
00591 
00592 char AddressSanitizerModule::ID = 0;
00593 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
00594     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
00595     "ModulePass", false, false)
00596 ModulePass *llvm::createAddressSanitizerModulePass() {
00597   return new AddressSanitizerModule();
00598 }
00599 
00600 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
00601   size_t Res = countTrailingZeros(TypeSize / 8);
00602   assert(Res < kNumberOfAccessSizes);
00603   return Res;
00604 }
00605 
00606 // \brief Create a constant for Str so that we can pass it to the run-time lib.
00607 static GlobalVariable *createPrivateGlobalForString(
00608     Module &M, StringRef Str, bool AllowMerging) {
00609   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
00610   // We use private linkage for module-local strings. If they can be merged
00611   // with another one, we set the unnamed_addr attribute.
00612   GlobalVariable *GV =
00613       new GlobalVariable(M, StrConst->getType(), true,
00614                          GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
00615   if (AllowMerging)
00616     GV->setUnnamedAddr(true);
00617   GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
00618   return GV;
00619 }
00620 
00621 /// \brief Create a global describing a source location.
00622 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
00623                                                        LocationMetadata MD) {
00624   Constant *LocData[] = {
00625       createPrivateGlobalForString(M, MD.Filename, true),
00626       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
00627       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
00628   };
00629   auto LocStruct = ConstantStruct::getAnon(LocData);
00630   auto GV = new GlobalVariable(M, LocStruct->getType(), true,
00631                                GlobalValue::PrivateLinkage, LocStruct,
00632                                kAsanGenPrefix);
00633   GV->setUnnamedAddr(true);
00634   return GV;
00635 }
00636 
00637 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
00638   return G->getName().find(kAsanGenPrefix) == 0;
00639 }
00640 
00641 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
00642   // Shadow >> scale
00643   Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
00644   if (Mapping.Offset == 0)
00645     return Shadow;
00646   // (Shadow >> scale) | offset
00647   if (Mapping.OrShadowOffset)
00648     return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
00649   else
00650     return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
00651 }
00652 
00653 // Instrument memset/memmove/memcpy
00654 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
00655   IRBuilder<> IRB(MI);
00656   if (isa<MemTransferInst>(MI)) {
00657     IRB.CreateCall3(
00658         isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
00659         IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
00660         IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
00661         IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
00662   } else if (isa<MemSetInst>(MI)) {
00663     IRB.CreateCall3(
00664         AsanMemset,
00665         IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
00666         IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
00667         IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
00668   }
00669   MI->eraseFromParent();
00670 }
00671 
00672 // If I is an interesting memory access, return the PointerOperand
00673 // and set IsWrite/Alignment. Otherwise return NULL.
00674 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
00675                                         unsigned *Alignment) {
00676   // Skip memory accesses inserted by another instrumentation.
00677   if (I->getMetadata("nosanitize"))
00678     return nullptr;
00679   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00680     if (!ClInstrumentReads) return nullptr;
00681     *IsWrite = false;
00682     *Alignment = LI->getAlignment();
00683     return LI->getPointerOperand();
00684   }
00685   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
00686     if (!ClInstrumentWrites) return nullptr;
00687     *IsWrite = true;
00688     *Alignment = SI->getAlignment();
00689     return SI->getPointerOperand();
00690   }
00691   if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
00692     if (!ClInstrumentAtomics) return nullptr;
00693     *IsWrite = true;
00694     *Alignment = 0;
00695     return RMW->getPointerOperand();
00696   }
00697   if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
00698     if (!ClInstrumentAtomics) return nullptr;
00699     *IsWrite = true;
00700     *Alignment = 0;
00701     return XCHG->getPointerOperand();
00702   }
00703   return nullptr;
00704 }
00705 
00706 static bool isPointerOperand(Value *V) {
00707   return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
00708 }
00709 
00710 // This is a rough heuristic; it may cause both false positives and
00711 // false negatives. The proper implementation requires cooperation with
00712 // the frontend.
00713 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
00714   if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
00715     if (!Cmp->isRelational())
00716       return false;
00717   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
00718     if (BO->getOpcode() != Instruction::Sub)
00719       return false;
00720   } else {
00721     return false;
00722   }
00723   if (!isPointerOperand(I->getOperand(0)) ||
00724       !isPointerOperand(I->getOperand(1)))
00725       return false;
00726   return true;
00727 }
00728 
00729 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
00730   // If a global variable does not have dynamic initialization we don't
00731   // have to instrument it.  However, if a global does not have initializer
00732   // at all, we assume it has dynamic initializer (in other TU).
00733   return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
00734 }
00735 
00736 void
00737 AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
00738   IRBuilder<> IRB(I);
00739   Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
00740   Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
00741   for (int i = 0; i < 2; i++) {
00742     if (Param[i]->getType()->isPointerTy())
00743       Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
00744   }
00745   IRB.CreateCall2(F, Param[0], Param[1]);
00746 }
00747 
00748 void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
00749   bool IsWrite = false;
00750   unsigned Alignment = 0;
00751   Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
00752   assert(Addr);
00753   if (ClOpt && ClOptGlobals) {
00754     if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
00755       // If initialization order checking is disabled, a simple access to a
00756       // dynamically initialized global is always valid.
00757       if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
00758         NumOptimizedAccessesToGlobalVar++;
00759         return;
00760       }
00761     }
00762     ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
00763     if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
00764       if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
00765         if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
00766           NumOptimizedAccessesToGlobalArray++;
00767           return;
00768         }
00769       }
00770     }
00771   }
00772 
00773   Type *OrigPtrTy = Addr->getType();
00774   Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
00775 
00776   assert(OrigTy->isSized());
00777   uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
00778 
00779   assert((TypeSize % 8) == 0);
00780 
00781   if (IsWrite)
00782     NumInstrumentedWrites++;
00783   else
00784     NumInstrumentedReads++;
00785 
00786   unsigned Granularity = 1 << Mapping.Scale;
00787   // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
00788   // if the data is properly aligned.
00789   if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
00790        TypeSize == 128) &&
00791       (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
00792     return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
00793   // Instrument unusual size or unusual alignment.
00794   // We can not do it with a single check, so we do 1-byte check for the first
00795   // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
00796   // to report the actual access size.
00797   IRBuilder<> IRB(I);
00798   Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
00799   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
00800   if (UseCalls) {
00801     IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
00802   } else {
00803     Value *LastByte = IRB.CreateIntToPtr(
00804         IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
00805         OrigPtrTy);
00806     instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
00807     instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
00808   }
00809 }
00810 
00811 // Validate the result of Module::getOrInsertFunction called for an interface
00812 // function of AddressSanitizer. If the instrumented module defines a function
00813 // with the same name, their prototypes must match, otherwise
00814 // getOrInsertFunction returns a bitcast.
00815 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
00816   if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
00817   FuncOrBitcast->dump();
00818   report_fatal_error("trying to redefine an AddressSanitizer "
00819                      "interface function");
00820 }
00821 
00822 Instruction *AddressSanitizer::generateCrashCode(
00823     Instruction *InsertBefore, Value *Addr,
00824     bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
00825   IRBuilder<> IRB(InsertBefore);
00826   CallInst *Call = SizeArgument
00827     ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
00828     : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
00829 
00830   // We don't do Call->setDoesNotReturn() because the BB already has
00831   // UnreachableInst at the end.
00832   // This EmptyAsm is required to avoid callback merge.
00833   IRB.CreateCall(EmptyAsm);
00834   return Call;
00835 }
00836 
00837 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
00838                                             Value *ShadowValue,
00839                                             uint32_t TypeSize) {
00840   size_t Granularity = 1 << Mapping.Scale;
00841   // Addr & (Granularity - 1)
00842   Value *LastAccessedByte = IRB.CreateAnd(
00843       AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
00844   // (Addr & (Granularity - 1)) + size - 1
00845   if (TypeSize / 8 > 1)
00846     LastAccessedByte = IRB.CreateAdd(
00847         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
00848   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
00849   LastAccessedByte = IRB.CreateIntCast(
00850       LastAccessedByte, ShadowValue->getType(), false);
00851   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
00852   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
00853 }
00854 
00855 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
00856                                          Instruction *InsertBefore, Value *Addr,
00857                                          uint32_t TypeSize, bool IsWrite,
00858                                          Value *SizeArgument, bool UseCalls) {
00859   IRBuilder<> IRB(InsertBefore);
00860   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
00861   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
00862 
00863   if (UseCalls) {
00864     IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
00865                    AddrLong);
00866     return;
00867   }
00868 
00869   Type *ShadowTy  = IntegerType::get(
00870       *C, std::max(8U, TypeSize >> Mapping.Scale));
00871   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
00872   Value *ShadowPtr = memToShadow(AddrLong, IRB);
00873   Value *CmpVal = Constant::getNullValue(ShadowTy);
00874   Value *ShadowValue = IRB.CreateLoad(
00875       IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
00876 
00877   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
00878   size_t Granularity = 1 << Mapping.Scale;
00879   TerminatorInst *CrashTerm = nullptr;
00880 
00881   if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
00882     // We use branch weights for the slow path check, to indicate that the slow
00883     // path is rarely taken. This seems to be the case for SPEC benchmarks.
00884     TerminatorInst *CheckTerm =
00885         SplitBlockAndInsertIfThen(Cmp, InsertBefore, false,
00886             MDBuilder(*C).createBranchWeights(1, 100000));
00887     assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
00888     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
00889     IRB.SetInsertPoint(CheckTerm);
00890     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
00891     BasicBlock *CrashBlock =
00892         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
00893     CrashTerm = new UnreachableInst(*C, CrashBlock);
00894     BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
00895     ReplaceInstWithInst(CheckTerm, NewTerm);
00896   } else {
00897     CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
00898   }
00899 
00900   Instruction *Crash = generateCrashCode(
00901       CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
00902   Crash->setDebugLoc(OrigIns->getDebugLoc());
00903 }
00904 
00905 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
00906                                                   GlobalValue *ModuleName) {
00907   // Set up the arguments to our poison/unpoison functions.
00908   IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
00909 
00910   // Add a call to poison all external globals before the given function starts.
00911   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
00912   IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
00913 
00914   // Add calls to unpoison all globals before each return instruction.
00915   for (auto &BB : GlobalInit.getBasicBlockList())
00916     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
00917       CallInst::Create(AsanUnpoisonGlobals, "", RI);
00918 }
00919 
00920 void AddressSanitizerModule::createInitializerPoisonCalls(
00921     Module &M, GlobalValue *ModuleName) {
00922   GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
00923 
00924   ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
00925   for (Use &OP : CA->operands()) {
00926     if (isa<ConstantAggregateZero>(OP))
00927       continue;
00928     ConstantStruct *CS = cast<ConstantStruct>(OP);
00929 
00930     // Must have a function or null ptr.
00931     // (CS->getOperand(0) is the init priority.)
00932     if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
00933       if (F->getName() != kAsanModuleCtorName)
00934         poisonOneInitializer(*F, ModuleName);
00935     }
00936   }
00937 }
00938 
00939 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
00940   Type *Ty = cast<PointerType>(G->getType())->getElementType();
00941   DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
00942 
00943   if (GlobalsMD.get(G).IsBlacklisted) return false;
00944   if (!Ty->isSized()) return false;
00945   if (!G->hasInitializer()) return false;
00946   if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
00947   // Touch only those globals that will not be defined in other modules.
00948   // Don't handle ODR linkage types and COMDATs since other modules may be built
00949   // without ASan.
00950   if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
00951       G->getLinkage() != GlobalVariable::PrivateLinkage &&
00952       G->getLinkage() != GlobalVariable::InternalLinkage)
00953     return false;
00954   if (G->hasComdat())
00955     return false;
00956   // Two problems with thread-locals:
00957   //   - The address of the main thread's copy can't be computed at link-time.
00958   //   - Need to poison all copies, not just the main thread's one.
00959   if (G->isThreadLocal())
00960     return false;
00961   // For now, just ignore this Global if the alignment is large.
00962   if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
00963 
00964   // Ignore all the globals with the names starting with "\01L_OBJC_".
00965   // Many of those are put into the .cstring section. The linker compresses
00966   // that section by removing the spare \0s after the string terminator, so
00967   // our redzones get broken.
00968   if ((G->getName().find("\01L_OBJC_") == 0) ||
00969       (G->getName().find("\01l_OBJC_") == 0)) {
00970     DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G << "\n");
00971     return false;
00972   }
00973 
00974   if (G->hasSection()) {
00975     StringRef Section(G->getSection());
00976     // Ignore the globals from the __OBJC section. The ObjC runtime assumes
00977     // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
00978     // them.
00979     if (Section.startswith("__OBJC,") ||
00980         Section.startswith("__DATA, __objc_")) {
00981       DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
00982       return false;
00983     }
00984     // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
00985     // Constant CFString instances are compiled in the following way:
00986     //  -- the string buffer is emitted into
00987     //     __TEXT,__cstring,cstring_literals
00988     //  -- the constant NSConstantString structure referencing that buffer
00989     //     is placed into __DATA,__cfstring
00990     // Therefore there's no point in placing redzones into __DATA,__cfstring.
00991     // Moreover, it causes the linker to crash on OS X 10.7
00992     if (Section.startswith("__DATA,__cfstring")) {
00993       DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
00994       return false;
00995     }
00996     // The linker merges the contents of cstring_literals and removes the
00997     // trailing zeroes.
00998     if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
00999       DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
01000       return false;
01001     }
01002 
01003     // Callbacks put into the CRT initializer/terminator sections
01004     // should not be instrumented.
01005     // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
01006     // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
01007     if (Section.startswith(".CRT")) {
01008       DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
01009       return false;
01010     }
01011 
01012     // Globals from llvm.metadata aren't emitted, do not instrument them.
01013     if (Section == "llvm.metadata") return false;
01014   }
01015 
01016   return true;
01017 }
01018 
01019 void AddressSanitizerModule::initializeCallbacks(Module &M) {
01020   IRBuilder<> IRB(*C);
01021   // Declare our poisoning and unpoisoning functions.
01022   AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
01023       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
01024   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
01025   AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
01026       kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
01027   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
01028   // Declare functions that register/unregister globals.
01029   AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
01030       kAsanRegisterGlobalsName, IRB.getVoidTy(),
01031       IntptrTy, IntptrTy, NULL));
01032   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
01033   AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
01034       kAsanUnregisterGlobalsName,
01035       IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01036   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
01037   AsanCovModuleInit = checkInterfaceFunction(M.getOrInsertFunction(
01038       kAsanCovModuleInitName,
01039       IRB.getVoidTy(), IntptrTy, NULL));
01040   AsanCovModuleInit->setLinkage(Function::ExternalLinkage);
01041 }
01042 
01043 // This function replaces all global variables with new variables that have
01044 // trailing redzones. It also creates a function that poisons
01045 // redzones and inserts this function into llvm.global_ctors.
01046 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
01047   GlobalsMD.init(M);
01048 
01049   SmallVector<GlobalVariable *, 16> GlobalsToChange;
01050 
01051   for (auto &G : M.globals()) {
01052     if (ShouldInstrumentGlobal(&G))
01053       GlobalsToChange.push_back(&G);
01054   }
01055 
01056   size_t n = GlobalsToChange.size();
01057   if (n == 0) return false;
01058 
01059   // A global is described by a structure
01060   //   size_t beg;
01061   //   size_t size;
01062   //   size_t size_with_redzone;
01063   //   const char *name;
01064   //   const char *module_name;
01065   //   size_t has_dynamic_init;
01066   //   void *source_location;
01067   // We initialize an array of such structures and pass it to a run-time call.
01068   StructType *GlobalStructTy =
01069       StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
01070                       IntptrTy, IntptrTy, NULL);
01071   SmallVector<Constant *, 16> Initializers(n);
01072 
01073   bool HasDynamicallyInitializedGlobals = false;
01074 
01075   // We shouldn't merge same module names, as this string serves as unique
01076   // module ID in runtime.
01077   GlobalVariable *ModuleName = createPrivateGlobalForString(
01078       M, M.getModuleIdentifier(), /*AllowMerging*/false);
01079 
01080   for (size_t i = 0; i < n; i++) {
01081     static const uint64_t kMaxGlobalRedzone = 1 << 18;
01082     GlobalVariable *G = GlobalsToChange[i];
01083 
01084     auto MD = GlobalsMD.get(G);
01085     // Create string holding the global name (use global name from metadata
01086     // if it's available, otherwise just write the name of global variable).
01087     GlobalVariable *Name = createPrivateGlobalForString(
01088         M, MD.Name.empty() ? G->getName() : MD.Name,
01089         /*AllowMerging*/ true);
01090 
01091     PointerType *PtrTy = cast<PointerType>(G->getType());
01092     Type *Ty = PtrTy->getElementType();
01093     uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
01094     uint64_t MinRZ = MinRedzoneSizeForGlobal();
01095     // MinRZ <= RZ <= kMaxGlobalRedzone
01096     // and trying to make RZ to be ~ 1/4 of SizeInBytes.
01097     uint64_t RZ = std::max(MinRZ,
01098                          std::min(kMaxGlobalRedzone,
01099                                   (SizeInBytes / MinRZ / 4) * MinRZ));
01100     uint64_t RightRedzoneSize = RZ;
01101     // Round up to MinRZ
01102     if (SizeInBytes % MinRZ)
01103       RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
01104     assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
01105     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
01106 
01107     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
01108     Constant *NewInitializer = ConstantStruct::get(
01109         NewTy, G->getInitializer(),
01110         Constant::getNullValue(RightRedZoneTy), NULL);
01111 
01112     // Create a new global variable with enough space for a redzone.
01113     GlobalValue::LinkageTypes Linkage = G->getLinkage();
01114     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
01115       Linkage = GlobalValue::InternalLinkage;
01116     GlobalVariable *NewGlobal = new GlobalVariable(
01117         M, NewTy, G->isConstant(), Linkage,
01118         NewInitializer, "", G, G->getThreadLocalMode());
01119     NewGlobal->copyAttributesFrom(G);
01120     NewGlobal->setAlignment(MinRZ);
01121 
01122     Value *Indices2[2];
01123     Indices2[0] = IRB.getInt32(0);
01124     Indices2[1] = IRB.getInt32(0);
01125 
01126     G->replaceAllUsesWith(
01127         ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
01128     NewGlobal->takeName(G);
01129     G->eraseFromParent();
01130 
01131     Constant *SourceLoc;
01132     if (!MD.SourceLoc.empty()) {
01133       auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
01134       SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
01135     } else {
01136       SourceLoc = ConstantInt::get(IntptrTy, 0);
01137     }
01138 
01139     Initializers[i] = ConstantStruct::get(
01140         GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
01141         ConstantInt::get(IntptrTy, SizeInBytes),
01142         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
01143         ConstantExpr::getPointerCast(Name, IntptrTy),
01144         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
01145         ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, NULL);
01146 
01147     if (ClInitializers && MD.IsDynInit)
01148       HasDynamicallyInitializedGlobals = true;
01149 
01150     DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
01151   }
01152 
01153   ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
01154   GlobalVariable *AllGlobals = new GlobalVariable(
01155       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
01156       ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
01157 
01158   // Create calls for poisoning before initializers run and unpoisoning after.
01159   if (HasDynamicallyInitializedGlobals)
01160     createInitializerPoisonCalls(M, ModuleName);
01161   IRB.CreateCall2(AsanRegisterGlobals,
01162                   IRB.CreatePointerCast(AllGlobals, IntptrTy),
01163                   ConstantInt::get(IntptrTy, n));
01164 
01165   // We also need to unregister globals at the end, e.g. when a shared library
01166   // gets closed.
01167   Function *AsanDtorFunction = Function::Create(
01168       FunctionType::get(Type::getVoidTy(*C), false),
01169       GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
01170   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
01171   IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
01172   IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
01173                        IRB.CreatePointerCast(AllGlobals, IntptrTy),
01174                        ConstantInt::get(IntptrTy, n));
01175   appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
01176 
01177   DEBUG(dbgs() << M);
01178   return true;
01179 }
01180 
01181 bool AddressSanitizerModule::runOnModule(Module &M) {
01182   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01183   if (!DLP)
01184     return false;
01185   DL = &DLP->getDataLayout();
01186   C = &(M.getContext());
01187   int LongSize = DL->getPointerSizeInBits();
01188   IntptrTy = Type::getIntNTy(*C, LongSize);
01189   Mapping = getShadowMapping(M, LongSize);
01190   initializeCallbacks(M);
01191 
01192   bool Changed = false;
01193 
01194   Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
01195   assert(CtorFunc);
01196   IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
01197 
01198   if (ClCoverage > 0) {
01199     Function *CovFunc = M.getFunction(kAsanCovName);
01200     int nCov = CovFunc ? CovFunc->getNumUses() : 0;
01201     IRB.CreateCall(AsanCovModuleInit, ConstantInt::get(IntptrTy, nCov));
01202     Changed = true;
01203   }
01204 
01205   if (ClGlobals)
01206     Changed |= InstrumentGlobals(IRB, M);
01207 
01208   return Changed;
01209 }
01210 
01211 void AddressSanitizer::initializeCallbacks(Module &M) {
01212   IRBuilder<> IRB(*C);
01213   // Create __asan_report* callbacks.
01214   for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
01215     for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
01216          AccessSizeIndex++) {
01217       // IsWrite and TypeSize are encoded in the function name.
01218       std::string Suffix =
01219           (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
01220       AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
01221           checkInterfaceFunction(
01222               M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
01223                                     IRB.getVoidTy(), IntptrTy, NULL));
01224       AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
01225           checkInterfaceFunction(
01226               M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
01227                                     IRB.getVoidTy(), IntptrTy, NULL));
01228     }
01229   }
01230   AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
01231               kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01232   AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
01233               kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01234 
01235   AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
01236       M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
01237                             IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01238   AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
01239       M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
01240                             IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01241 
01242   AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
01243       ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
01244       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
01245   AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
01246       ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
01247       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
01248   AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
01249       ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
01250       IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, NULL));
01251 
01252   AsanHandleNoReturnFunc = checkInterfaceFunction(
01253       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
01254   AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
01255       kAsanCovName, IRB.getVoidTy(), NULL));
01256   AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
01257       kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01258   AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
01259       kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01260   // We insert an empty inline asm after __asan_report* to avoid callback merge.
01261   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
01262                             StringRef(""), StringRef(""),
01263                             /*hasSideEffects=*/true);
01264 }
01265 
01266 // virtual
01267 bool AddressSanitizer::doInitialization(Module &M) {
01268   // Initialize the private fields. No one has accessed them before.
01269   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01270   if (!DLP)
01271     report_fatal_error("data layout missing");
01272   DL = &DLP->getDataLayout();
01273 
01274   GlobalsMD.init(M);
01275 
01276   C = &(M.getContext());
01277   LongSize = DL->getPointerSizeInBits();
01278   IntptrTy = Type::getIntNTy(*C, LongSize);
01279 
01280   AsanCtorFunction = Function::Create(
01281       FunctionType::get(Type::getVoidTy(*C), false),
01282       GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
01283   BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
01284   // call __asan_init in the module ctor.
01285   IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
01286   AsanInitFunction = checkInterfaceFunction(
01287       M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
01288   AsanInitFunction->setLinkage(Function::ExternalLinkage);
01289   IRB.CreateCall(AsanInitFunction);
01290 
01291   Mapping = getShadowMapping(M, LongSize);
01292 
01293   appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
01294   return true;
01295 }
01296 
01297 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
01298   // For each NSObject descendant having a +load method, this method is invoked
01299   // by the ObjC runtime before any of the static constructors is called.
01300   // Therefore we need to instrument such methods with a call to __asan_init
01301   // at the beginning in order to initialize our runtime before any access to
01302   // the shadow memory.
01303   // We cannot just ignore these methods, because they may call other
01304   // instrumented functions.
01305   if (F.getName().find(" load]") != std::string::npos) {
01306     IRBuilder<> IRB(F.begin()->begin());
01307     IRB.CreateCall(AsanInitFunction);
01308     return true;
01309   }
01310   return false;
01311 }
01312 
01313 void AddressSanitizer::InjectCoverageAtBlock(Function &F, BasicBlock &BB) {
01314   BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
01315   // Skip static allocas at the top of the entry block so they don't become
01316   // dynamic when we split the block.  If we used our optimized stack layout,
01317   // then there will only be one alloca and it will come first.
01318   for (; IP != BE; ++IP) {
01319     AllocaInst *AI = dyn_cast<AllocaInst>(IP);
01320     if (!AI || !AI->isStaticAlloca())
01321       break;
01322   }
01323 
01324   DebugLoc EntryLoc = &BB == &F.getEntryBlock()
01325                           ? IP->getDebugLoc().getFnDebugLoc(*C)
01326                           : IP->getDebugLoc();
01327   IRBuilder<> IRB(IP);
01328   IRB.SetCurrentDebugLocation(EntryLoc);
01329   Type *Int8Ty = IRB.getInt8Ty();
01330   GlobalVariable *Guard = new GlobalVariable(
01331       *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
01332       Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
01333   LoadInst *Load = IRB.CreateLoad(Guard);
01334   Load->setAtomic(Monotonic);
01335   Load->setAlignment(1);
01336   Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
01337   Instruction *Ins = SplitBlockAndInsertIfThen(
01338       Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
01339   IRB.SetInsertPoint(Ins);
01340   IRB.SetCurrentDebugLocation(EntryLoc);
01341   // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
01342   IRB.CreateCall(AsanCovFunction);
01343   StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
01344   Store->setAtomic(Monotonic);
01345   Store->setAlignment(1);
01346 }
01347 
01348 // Poor man's coverage that works with ASan.
01349 // We create a Guard boolean variable with the same linkage
01350 // as the function and inject this code into the entry block (-asan-coverage=1)
01351 // or all blocks (-asan-coverage=2):
01352 // if (*Guard) {
01353 //    __sanitizer_cov();
01354 //    *Guard = 1;
01355 // }
01356 // The accesses to Guard are atomic. The rest of the logic is
01357 // in __sanitizer_cov (it's fine to call it more than once).
01358 //
01359 // This coverage implementation provides very limited data:
01360 // it only tells if a given function (block) was ever executed.
01361 // No counters, no per-edge data.
01362 // But for many use cases this is what we need and the added slowdown
01363 // is negligible. This simple implementation will probably be obsoleted
01364 // by the upcoming Clang-based coverage implementation.
01365 // By having it here and now we hope to
01366 //  a) get the functionality to users earlier and
01367 //  b) collect usage statistics to help improve Clang coverage design.
01368 bool AddressSanitizer::InjectCoverage(Function &F,
01369                                       ArrayRef<BasicBlock *> AllBlocks) {
01370   if (!ClCoverage) return false;
01371 
01372   if (ClCoverage == 1 ||
01373       (unsigned)ClCoverageBlockThreshold < AllBlocks.size()) {
01374     InjectCoverageAtBlock(F, F.getEntryBlock());
01375   } else {
01376     for (auto BB : AllBlocks)
01377       InjectCoverageAtBlock(F, *BB);
01378   }
01379   return true;
01380 }
01381 
01382 bool AddressSanitizer::runOnFunction(Function &F) {
01383   if (&F == AsanCtorFunction) return false;
01384   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
01385   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
01386   initializeCallbacks(*F.getParent());
01387 
01388   // If needed, insert __asan_init before checking for SanitizeAddress attr.
01389   maybeInsertAsanInitAtFunctionEntry(F);
01390 
01391   if (!F.hasFnAttribute(Attribute::SanitizeAddress))
01392     return false;
01393 
01394   if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
01395     return false;
01396 
01397   // We want to instrument every address only once per basic block (unless there
01398   // are calls between uses).
01399   SmallSet<Value*, 16> TempsToInstrument;
01400   SmallVector<Instruction*, 16> ToInstrument;
01401   SmallVector<Instruction*, 8> NoReturnCalls;
01402   SmallVector<BasicBlock*, 16> AllBlocks;
01403   SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
01404   int NumAllocas = 0;
01405   bool IsWrite;
01406   unsigned Alignment;
01407 
01408   // Fill the set of memory operations to instrument.
01409   for (auto &BB : F) {
01410     AllBlocks.push_back(&BB);
01411     TempsToInstrument.clear();
01412     int NumInsnsPerBB = 0;
01413     for (auto &Inst : BB) {
01414       if (LooksLikeCodeInBug11395(&Inst)) return false;
01415       if (Value *Addr =
01416               isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
01417         if (ClOpt && ClOptSameTemp) {
01418           if (!TempsToInstrument.insert(Addr))
01419             continue;  // We've seen this temp in the current BB.
01420         }
01421       } else if (ClInvalidPointerPairs &&
01422                  isInterestingPointerComparisonOrSubtraction(&Inst)) {
01423         PointerComparisonsOrSubtracts.push_back(&Inst);
01424         continue;
01425       } else if (isa<MemIntrinsic>(Inst)) {
01426         // ok, take it.
01427       } else {
01428         if (isa<AllocaInst>(Inst))
01429           NumAllocas++;
01430         CallSite CS(&Inst);
01431         if (CS) {
01432           // A call inside BB.
01433           TempsToInstrument.clear();
01434           if (CS.doesNotReturn())
01435             NoReturnCalls.push_back(CS.getInstruction());
01436         }
01437         continue;
01438       }
01439       ToInstrument.push_back(&Inst);
01440       NumInsnsPerBB++;
01441       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
01442         break;
01443     }
01444   }
01445 
01446   Function *UninstrumentedDuplicate = nullptr;
01447   bool LikelyToInstrument =
01448       !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
01449   if (ClKeepUninstrumented && LikelyToInstrument) {
01450     ValueToValueMapTy VMap;
01451     UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
01452     UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
01453     UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
01454     F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
01455   }
01456 
01457   bool UseCalls = false;
01458   if (ClInstrumentationWithCallsThreshold >= 0 &&
01459       ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
01460     UseCalls = true;
01461 
01462   // Instrument.
01463   int NumInstrumented = 0;
01464   for (auto Inst : ToInstrument) {
01465     if (ClDebugMin < 0 || ClDebugMax < 0 ||
01466         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
01467       if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
01468         instrumentMop(Inst, UseCalls);
01469       else
01470         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
01471     }
01472     NumInstrumented++;
01473   }
01474 
01475   FunctionStackPoisoner FSP(F, *this);
01476   bool ChangedStack = FSP.runOnFunction();
01477 
01478   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
01479   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
01480   for (auto CI : NoReturnCalls) {
01481     IRBuilder<> IRB(CI);
01482     IRB.CreateCall(AsanHandleNoReturnFunc);
01483   }
01484 
01485   for (auto Inst : PointerComparisonsOrSubtracts) {
01486     instrumentPointerComparisonOrSubtraction(Inst);
01487     NumInstrumented++;
01488   }
01489 
01490   bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
01491 
01492   if (InjectCoverage(F, AllBlocks))
01493     res = true;
01494 
01495   DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
01496 
01497   if (ClKeepUninstrumented) {
01498     if (!res) {
01499       // No instrumentation is done, no need for the duplicate.
01500       if (UninstrumentedDuplicate)
01501         UninstrumentedDuplicate->eraseFromParent();
01502     } else {
01503       // The function was instrumented. We must have the duplicate.
01504       assert(UninstrumentedDuplicate);
01505       UninstrumentedDuplicate->setSection("NOASAN");
01506       assert(!F.hasSection());
01507       F.setSection("ASAN");
01508     }
01509   }
01510 
01511   return res;
01512 }
01513 
01514 // Workaround for bug 11395: we don't want to instrument stack in functions
01515 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
01516 // FIXME: remove once the bug 11395 is fixed.
01517 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
01518   if (LongSize != 32) return false;
01519   CallInst *CI = dyn_cast<CallInst>(I);
01520   if (!CI || !CI->isInlineAsm()) return false;
01521   if (CI->getNumArgOperands() <= 5) return false;
01522   // We have inline assembly with quite a few arguments.
01523   return true;
01524 }
01525 
01526 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
01527   IRBuilder<> IRB(*C);
01528   for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
01529     std::string Suffix = itostr(i);
01530     AsanStackMallocFunc[i] = checkInterfaceFunction(
01531         M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
01532                               IntptrTy, IntptrTy, NULL));
01533     AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
01534         kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
01535         IntptrTy, IntptrTy, NULL));
01536   }
01537   AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
01538       kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01539   AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
01540       kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01541 }
01542 
01543 void
01544 FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
01545                                       IRBuilder<> &IRB, Value *ShadowBase,
01546                                       bool DoPoison) {
01547   size_t n = ShadowBytes.size();
01548   size_t i = 0;
01549   // We need to (un)poison n bytes of stack shadow. Poison as many as we can
01550   // using 64-bit stores (if we are on 64-bit arch), then poison the rest
01551   // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
01552   for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
01553        LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
01554     for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
01555       uint64_t Val = 0;
01556       for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
01557         if (ASan.DL->isLittleEndian())
01558           Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
01559         else
01560           Val = (Val << 8) | ShadowBytes[i + j];
01561       }
01562       if (!Val) continue;
01563       Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
01564       Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
01565       Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
01566       IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
01567     }
01568   }
01569 }
01570 
01571 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
01572 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
01573 static int StackMallocSizeClass(uint64_t LocalStackSize) {
01574   assert(LocalStackSize <= kMaxStackMallocSize);
01575   uint64_t MaxSize = kMinStackMallocSize;
01576   for (int i = 0; ; i++, MaxSize *= 2)
01577     if (LocalStackSize <= MaxSize)
01578       return i;
01579   llvm_unreachable("impossible LocalStackSize");
01580 }
01581 
01582 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
01583 // We can not use MemSet intrinsic because it may end up calling the actual
01584 // memset. Size is a multiple of 8.
01585 // Currently this generates 8-byte stores on x86_64; it may be better to
01586 // generate wider stores.
01587 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
01588     IRBuilder<> &IRB, Value *ShadowBase, int Size) {
01589   assert(!(Size % 8));
01590   assert(kAsanStackAfterReturnMagic == 0xf5);
01591   for (int i = 0; i < Size; i += 8) {
01592     Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
01593     IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
01594                     IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
01595   }
01596 }
01597 
01598 static DebugLoc getFunctionEntryDebugLocation(Function &F) {
01599   for (const auto &Inst : F.getEntryBlock())
01600     if (!isa<AllocaInst>(Inst))
01601       return Inst.getDebugLoc();
01602   return DebugLoc();
01603 }
01604 
01605 void FunctionStackPoisoner::poisonStack() {
01606   int StackMallocIdx = -1;
01607   DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
01608 
01609   assert(AllocaVec.size() > 0);
01610   Instruction *InsBefore = AllocaVec[0];
01611   IRBuilder<> IRB(InsBefore);
01612   IRB.SetCurrentDebugLocation(EntryDebugLocation);
01613 
01614   SmallVector<ASanStackVariableDescription, 16> SVD;
01615   SVD.reserve(AllocaVec.size());
01616   for (AllocaInst *AI : AllocaVec) {
01617     ASanStackVariableDescription D = { AI->getName().data(),
01618                                    getAllocaSizeInBytes(AI),
01619                                    AI->getAlignment(), AI, 0};
01620     SVD.push_back(D);
01621   }
01622   // Minimal header size (left redzone) is 4 pointers,
01623   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
01624   size_t MinHeaderSize = ASan.LongSize / 2;
01625   ASanStackFrameLayout L;
01626   ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
01627   DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
01628   uint64_t LocalStackSize = L.FrameSize;
01629   bool DoStackMalloc =
01630       ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
01631 
01632   Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
01633   AllocaInst *MyAlloca =
01634       new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
01635   MyAlloca->setDebugLoc(EntryDebugLocation);
01636   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
01637   size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
01638   MyAlloca->setAlignment(FrameAlignment);
01639   assert(MyAlloca->isStaticAlloca());
01640   Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
01641   Value *LocalStackBase = OrigStackBase;
01642 
01643   if (DoStackMalloc) {
01644     // LocalStackBase = OrigStackBase
01645     // if (__asan_option_detect_stack_use_after_return)
01646     //   LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
01647     StackMallocIdx = StackMallocSizeClass(LocalStackSize);
01648     assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
01649     Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
01650         kAsanOptionDetectUAR, IRB.getInt32Ty());
01651     Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
01652                                   Constant::getNullValue(IRB.getInt32Ty()));
01653     Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
01654     BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
01655     IRBuilder<> IRBIf(Term);
01656     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
01657     LocalStackBase = IRBIf.CreateCall2(
01658         AsanStackMallocFunc[StackMallocIdx],
01659         ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
01660     BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
01661     IRB.SetInsertPoint(InsBefore);
01662     IRB.SetCurrentDebugLocation(EntryDebugLocation);
01663     PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
01664     Phi->addIncoming(OrigStackBase, CmpBlock);
01665     Phi->addIncoming(LocalStackBase, SetBlock);
01666     LocalStackBase = Phi;
01667   }
01668 
01669   // Insert poison calls for lifetime intrinsics for alloca.
01670   bool HavePoisonedAllocas = false;
01671   for (const auto &APC : AllocaPoisonCallVec) {
01672     assert(APC.InsBefore);
01673     assert(APC.AI);
01674     IRBuilder<> IRB(APC.InsBefore);
01675     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
01676     HavePoisonedAllocas |= APC.DoPoison;
01677   }
01678 
01679   // Replace Alloca instructions with base+offset.
01680   for (const auto &Desc : SVD) {
01681     AllocaInst *AI = Desc.AI;
01682     Value *NewAllocaPtr = IRB.CreateIntToPtr(
01683         IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
01684         AI->getType());
01685     replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
01686     AI->replaceAllUsesWith(NewAllocaPtr);
01687   }
01688 
01689   // The left-most redzone has enough space for at least 4 pointers.
01690   // Write the Magic value to redzone[0].
01691   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
01692   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
01693                   BasePlus0);
01694   // Write the frame description constant to redzone[1].
01695   Value *BasePlus1 = IRB.CreateIntToPtr(
01696     IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
01697     IntptrPtrTy);
01698   GlobalVariable *StackDescriptionGlobal =
01699       createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
01700                                    /*AllowMerging*/true);
01701   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
01702                                              IntptrTy);
01703   IRB.CreateStore(Description, BasePlus1);
01704   // Write the PC to redzone[2].
01705   Value *BasePlus2 = IRB.CreateIntToPtr(
01706     IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
01707                                                    2 * ASan.LongSize/8)),
01708     IntptrPtrTy);
01709   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
01710 
01711   // Poison the stack redzones at the entry.
01712   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
01713   poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
01714 
01715   // (Un)poison the stack before all ret instructions.
01716   for (auto Ret : RetVec) {
01717     IRBuilder<> IRBRet(Ret);
01718     // Mark the current frame as retired.
01719     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
01720                        BasePlus0);
01721     if (DoStackMalloc) {
01722       assert(StackMallocIdx >= 0);
01723       // if LocalStackBase != OrigStackBase:
01724       //     // In use-after-return mode, poison the whole stack frame.
01725       //     if StackMallocIdx <= 4
01726       //         // For small sizes inline the whole thing:
01727       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
01728       //         **SavedFlagPtr(LocalStackBase) = 0
01729       //     else
01730       //         __asan_stack_free_N(LocalStackBase, OrigStackBase)
01731       // else
01732       //     <This is not a fake stack; unpoison the redzones>
01733       Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
01734       TerminatorInst *ThenTerm, *ElseTerm;
01735       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
01736 
01737       IRBuilder<> IRBPoison(ThenTerm);
01738       if (StackMallocIdx <= 4) {
01739         int ClassSize = kMinStackMallocSize << StackMallocIdx;
01740         SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
01741                                            ClassSize >> Mapping.Scale);
01742         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
01743             LocalStackBase,
01744             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
01745         Value *SavedFlagPtr = IRBPoison.CreateLoad(
01746             IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
01747         IRBPoison.CreateStore(
01748             Constant::getNullValue(IRBPoison.getInt8Ty()),
01749             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
01750       } else {
01751         // For larger frames call __asan_stack_free_*.
01752         IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
01753                               ConstantInt::get(IntptrTy, LocalStackSize),
01754                               OrigStackBase);
01755       }
01756 
01757       IRBuilder<> IRBElse(ElseTerm);
01758       poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
01759     } else if (HavePoisonedAllocas) {
01760       // If we poisoned some allocas in llvm.lifetime analysis,
01761       // unpoison whole stack frame now.
01762       assert(LocalStackBase == OrigStackBase);
01763       poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
01764     } else {
01765       poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
01766     }
01767   }
01768 
01769   // We are done. Remove the old unused alloca instructions.
01770   for (auto AI : AllocaVec)
01771     AI->eraseFromParent();
01772 }
01773 
01774 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
01775                                          IRBuilder<> &IRB, bool DoPoison) {
01776   // For now just insert the call to ASan runtime.
01777   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
01778   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
01779   IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
01780                            : AsanUnpoisonStackMemoryFunc,
01781                   AddrArg, SizeArg);
01782 }
01783 
01784 // Handling llvm.lifetime intrinsics for a given %alloca:
01785 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
01786 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
01787 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
01788 //     could be poisoned by previous llvm.lifetime.end instruction, as the
01789 //     variable may go in and out of scope several times, e.g. in loops).
01790 // (3) if we poisoned at least one %alloca in a function,
01791 //     unpoison the whole stack frame at function exit.
01792 
01793 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
01794   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
01795     // We're intested only in allocas we can handle.
01796     return isInterestingAlloca(*AI) ? AI : nullptr;
01797   // See if we've already calculated (or started to calculate) alloca for a
01798   // given value.
01799   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
01800   if (I != AllocaForValue.end())
01801     return I->second;
01802   // Store 0 while we're calculating alloca for value V to avoid
01803   // infinite recursion if the value references itself.
01804   AllocaForValue[V] = nullptr;
01805   AllocaInst *Res = nullptr;
01806   if (CastInst *CI = dyn_cast<CastInst>(V))
01807     Res = findAllocaForValue(CI->getOperand(0));
01808   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
01809     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01810       Value *IncValue = PN->getIncomingValue(i);
01811       // Allow self-referencing phi-nodes.
01812       if (IncValue == PN) continue;
01813       AllocaInst *IncValueAI = findAllocaForValue(IncValue);
01814       // AI for incoming values should exist and should all be equal.
01815       if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
01816         return nullptr;
01817       Res = IncValueAI;
01818     }
01819   }
01820   if (Res)
01821     AllocaForValue[V] = Res;
01822   return Res;
01823 }