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 uint64_t    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.isiOS();
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     if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
00932       if (F->getName() == kAsanModuleCtorName) continue;
00933       ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
00934       // Don't instrument CTORs that will run before asan.module_ctor.
00935       if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
00936       poisonOneInitializer(*F, ModuleName);
00937     }
00938   }
00939 }
00940 
00941 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
00942   Type *Ty = cast<PointerType>(G->getType())->getElementType();
00943   DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
00944 
00945   if (GlobalsMD.get(G).IsBlacklisted) return false;
00946   if (!Ty->isSized()) return false;
00947   if (!G->hasInitializer()) return false;
00948   if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
00949   // Touch only those globals that will not be defined in other modules.
00950   // Don't handle ODR linkage types and COMDATs since other modules may be built
00951   // without ASan.
00952   if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
00953       G->getLinkage() != GlobalVariable::PrivateLinkage &&
00954       G->getLinkage() != GlobalVariable::InternalLinkage)
00955     return false;
00956   if (G->hasComdat())
00957     return false;
00958   // Two problems with thread-locals:
00959   //   - The address of the main thread's copy can't be computed at link-time.
00960   //   - Need to poison all copies, not just the main thread's one.
00961   if (G->isThreadLocal())
00962     return false;
00963   // For now, just ignore this Global if the alignment is large.
00964   if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
00965 
00966   // Ignore all the globals with the names starting with "\01L_OBJC_".
00967   // Many of those are put into the .cstring section. The linker compresses
00968   // that section by removing the spare \0s after the string terminator, so
00969   // our redzones get broken.
00970   if ((G->getName().find("\01L_OBJC_") == 0) ||
00971       (G->getName().find("\01l_OBJC_") == 0)) {
00972     DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G << "\n");
00973     return false;
00974   }
00975 
00976   if (G->hasSection()) {
00977     StringRef Section(G->getSection());
00978     // Ignore the globals from the __OBJC section. The ObjC runtime assumes
00979     // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
00980     // them.
00981     if (Section.startswith("__OBJC,") ||
00982         Section.startswith("__DATA, __objc_")) {
00983       DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
00984       return false;
00985     }
00986     // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
00987     // Constant CFString instances are compiled in the following way:
00988     //  -- the string buffer is emitted into
00989     //     __TEXT,__cstring,cstring_literals
00990     //  -- the constant NSConstantString structure referencing that buffer
00991     //     is placed into __DATA,__cfstring
00992     // Therefore there's no point in placing redzones into __DATA,__cfstring.
00993     // Moreover, it causes the linker to crash on OS X 10.7
00994     if (Section.startswith("__DATA,__cfstring")) {
00995       DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
00996       return false;
00997     }
00998     // The linker merges the contents of cstring_literals and removes the
00999     // trailing zeroes.
01000     if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
01001       DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
01002       return false;
01003     }
01004 
01005     // Callbacks put into the CRT initializer/terminator sections
01006     // should not be instrumented.
01007     // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
01008     // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
01009     if (Section.startswith(".CRT")) {
01010       DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
01011       return false;
01012     }
01013 
01014     // Globals from llvm.metadata aren't emitted, do not instrument them.
01015     if (Section == "llvm.metadata") return false;
01016   }
01017 
01018   return true;
01019 }
01020 
01021 void AddressSanitizerModule::initializeCallbacks(Module &M) {
01022   IRBuilder<> IRB(*C);
01023   // Declare our poisoning and unpoisoning functions.
01024   AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
01025       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
01026   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
01027   AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
01028       kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
01029   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
01030   // Declare functions that register/unregister globals.
01031   AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
01032       kAsanRegisterGlobalsName, IRB.getVoidTy(),
01033       IntptrTy, IntptrTy, NULL));
01034   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
01035   AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
01036       kAsanUnregisterGlobalsName,
01037       IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01038   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
01039   AsanCovModuleInit = checkInterfaceFunction(M.getOrInsertFunction(
01040       kAsanCovModuleInitName,
01041       IRB.getVoidTy(), IntptrTy, NULL));
01042   AsanCovModuleInit->setLinkage(Function::ExternalLinkage);
01043 }
01044 
01045 // This function replaces all global variables with new variables that have
01046 // trailing redzones. It also creates a function that poisons
01047 // redzones and inserts this function into llvm.global_ctors.
01048 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
01049   GlobalsMD.init(M);
01050 
01051   SmallVector<GlobalVariable *, 16> GlobalsToChange;
01052 
01053   for (auto &G : M.globals()) {
01054     if (ShouldInstrumentGlobal(&G))
01055       GlobalsToChange.push_back(&G);
01056   }
01057 
01058   size_t n = GlobalsToChange.size();
01059   if (n == 0) return false;
01060 
01061   // A global is described by a structure
01062   //   size_t beg;
01063   //   size_t size;
01064   //   size_t size_with_redzone;
01065   //   const char *name;
01066   //   const char *module_name;
01067   //   size_t has_dynamic_init;
01068   //   void *source_location;
01069   // We initialize an array of such structures and pass it to a run-time call.
01070   StructType *GlobalStructTy =
01071       StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
01072                       IntptrTy, IntptrTy, NULL);
01073   SmallVector<Constant *, 16> Initializers(n);
01074 
01075   bool HasDynamicallyInitializedGlobals = false;
01076 
01077   // We shouldn't merge same module names, as this string serves as unique
01078   // module ID in runtime.
01079   GlobalVariable *ModuleName = createPrivateGlobalForString(
01080       M, M.getModuleIdentifier(), /*AllowMerging*/false);
01081 
01082   for (size_t i = 0; i < n; i++) {
01083     static const uint64_t kMaxGlobalRedzone = 1 << 18;
01084     GlobalVariable *G = GlobalsToChange[i];
01085 
01086     auto MD = GlobalsMD.get(G);
01087     // Create string holding the global name (use global name from metadata
01088     // if it's available, otherwise just write the name of global variable).
01089     GlobalVariable *Name = createPrivateGlobalForString(
01090         M, MD.Name.empty() ? G->getName() : MD.Name,
01091         /*AllowMerging*/ true);
01092 
01093     PointerType *PtrTy = cast<PointerType>(G->getType());
01094     Type *Ty = PtrTy->getElementType();
01095     uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
01096     uint64_t MinRZ = MinRedzoneSizeForGlobal();
01097     // MinRZ <= RZ <= kMaxGlobalRedzone
01098     // and trying to make RZ to be ~ 1/4 of SizeInBytes.
01099     uint64_t RZ = std::max(MinRZ,
01100                          std::min(kMaxGlobalRedzone,
01101                                   (SizeInBytes / MinRZ / 4) * MinRZ));
01102     uint64_t RightRedzoneSize = RZ;
01103     // Round up to MinRZ
01104     if (SizeInBytes % MinRZ)
01105       RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
01106     assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
01107     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
01108 
01109     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
01110     Constant *NewInitializer = ConstantStruct::get(
01111         NewTy, G->getInitializer(),
01112         Constant::getNullValue(RightRedZoneTy), NULL);
01113 
01114     // Create a new global variable with enough space for a redzone.
01115     GlobalValue::LinkageTypes Linkage = G->getLinkage();
01116     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
01117       Linkage = GlobalValue::InternalLinkage;
01118     GlobalVariable *NewGlobal = new GlobalVariable(
01119         M, NewTy, G->isConstant(), Linkage,
01120         NewInitializer, "", G, G->getThreadLocalMode());
01121     NewGlobal->copyAttributesFrom(G);
01122     NewGlobal->setAlignment(MinRZ);
01123 
01124     Value *Indices2[2];
01125     Indices2[0] = IRB.getInt32(0);
01126     Indices2[1] = IRB.getInt32(0);
01127 
01128     G->replaceAllUsesWith(
01129         ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
01130     NewGlobal->takeName(G);
01131     G->eraseFromParent();
01132 
01133     Constant *SourceLoc;
01134     if (!MD.SourceLoc.empty()) {
01135       auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
01136       SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
01137     } else {
01138       SourceLoc = ConstantInt::get(IntptrTy, 0);
01139     }
01140 
01141     Initializers[i] = ConstantStruct::get(
01142         GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
01143         ConstantInt::get(IntptrTy, SizeInBytes),
01144         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
01145         ConstantExpr::getPointerCast(Name, IntptrTy),
01146         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
01147         ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, NULL);
01148 
01149     if (ClInitializers && MD.IsDynInit)
01150       HasDynamicallyInitializedGlobals = true;
01151 
01152     DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
01153   }
01154 
01155   ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
01156   GlobalVariable *AllGlobals = new GlobalVariable(
01157       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
01158       ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
01159 
01160   // Create calls for poisoning before initializers run and unpoisoning after.
01161   if (HasDynamicallyInitializedGlobals)
01162     createInitializerPoisonCalls(M, ModuleName);
01163   IRB.CreateCall2(AsanRegisterGlobals,
01164                   IRB.CreatePointerCast(AllGlobals, IntptrTy),
01165                   ConstantInt::get(IntptrTy, n));
01166 
01167   // We also need to unregister globals at the end, e.g. when a shared library
01168   // gets closed.
01169   Function *AsanDtorFunction = Function::Create(
01170       FunctionType::get(Type::getVoidTy(*C), false),
01171       GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
01172   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
01173   IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
01174   IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
01175                        IRB.CreatePointerCast(AllGlobals, IntptrTy),
01176                        ConstantInt::get(IntptrTy, n));
01177   appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
01178 
01179   DEBUG(dbgs() << M);
01180   return true;
01181 }
01182 
01183 bool AddressSanitizerModule::runOnModule(Module &M) {
01184   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01185   if (!DLP)
01186     return false;
01187   DL = &DLP->getDataLayout();
01188   C = &(M.getContext());
01189   int LongSize = DL->getPointerSizeInBits();
01190   IntptrTy = Type::getIntNTy(*C, LongSize);
01191   Mapping = getShadowMapping(M, LongSize);
01192   initializeCallbacks(M);
01193 
01194   bool Changed = false;
01195 
01196   Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
01197   assert(CtorFunc);
01198   IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
01199 
01200   if (ClCoverage > 0) {
01201     Function *CovFunc = M.getFunction(kAsanCovName);
01202     int nCov = CovFunc ? CovFunc->getNumUses() : 0;
01203     IRB.CreateCall(AsanCovModuleInit, ConstantInt::get(IntptrTy, nCov));
01204     Changed = true;
01205   }
01206 
01207   if (ClGlobals)
01208     Changed |= InstrumentGlobals(IRB, M);
01209 
01210   return Changed;
01211 }
01212 
01213 void AddressSanitizer::initializeCallbacks(Module &M) {
01214   IRBuilder<> IRB(*C);
01215   // Create __asan_report* callbacks.
01216   for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
01217     for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
01218          AccessSizeIndex++) {
01219       // IsWrite and TypeSize are encoded in the function name.
01220       std::string Suffix =
01221           (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
01222       AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
01223           checkInterfaceFunction(
01224               M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
01225                                     IRB.getVoidTy(), IntptrTy, NULL));
01226       AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
01227           checkInterfaceFunction(
01228               M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
01229                                     IRB.getVoidTy(), IntptrTy, NULL));
01230     }
01231   }
01232   AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
01233               kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01234   AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
01235               kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01236 
01237   AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
01238       M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
01239                             IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01240   AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
01241       M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
01242                             IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01243 
01244   AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
01245       ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
01246       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
01247   AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
01248       ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
01249       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
01250   AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
01251       ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
01252       IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, NULL));
01253 
01254   AsanHandleNoReturnFunc = checkInterfaceFunction(
01255       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
01256   AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
01257       kAsanCovName, IRB.getVoidTy(), NULL));
01258   AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
01259       kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01260   AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
01261       kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01262   // We insert an empty inline asm after __asan_report* to avoid callback merge.
01263   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
01264                             StringRef(""), StringRef(""),
01265                             /*hasSideEffects=*/true);
01266 }
01267 
01268 // virtual
01269 bool AddressSanitizer::doInitialization(Module &M) {
01270   // Initialize the private fields. No one has accessed them before.
01271   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01272   if (!DLP)
01273     report_fatal_error("data layout missing");
01274   DL = &DLP->getDataLayout();
01275 
01276   GlobalsMD.init(M);
01277 
01278   C = &(M.getContext());
01279   LongSize = DL->getPointerSizeInBits();
01280   IntptrTy = Type::getIntNTy(*C, LongSize);
01281 
01282   AsanCtorFunction = Function::Create(
01283       FunctionType::get(Type::getVoidTy(*C), false),
01284       GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
01285   BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
01286   // call __asan_init in the module ctor.
01287   IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
01288   AsanInitFunction = checkInterfaceFunction(
01289       M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
01290   AsanInitFunction->setLinkage(Function::ExternalLinkage);
01291   IRB.CreateCall(AsanInitFunction);
01292 
01293   Mapping = getShadowMapping(M, LongSize);
01294 
01295   appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
01296   return true;
01297 }
01298 
01299 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
01300   // For each NSObject descendant having a +load method, this method is invoked
01301   // by the ObjC runtime before any of the static constructors is called.
01302   // Therefore we need to instrument such methods with a call to __asan_init
01303   // at the beginning in order to initialize our runtime before any access to
01304   // the shadow memory.
01305   // We cannot just ignore these methods, because they may call other
01306   // instrumented functions.
01307   if (F.getName().find(" load]") != std::string::npos) {
01308     IRBuilder<> IRB(F.begin()->begin());
01309     IRB.CreateCall(AsanInitFunction);
01310     return true;
01311   }
01312   return false;
01313 }
01314 
01315 void AddressSanitizer::InjectCoverageAtBlock(Function &F, BasicBlock &BB) {
01316   BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
01317   // Skip static allocas at the top of the entry block so they don't become
01318   // dynamic when we split the block.  If we used our optimized stack layout,
01319   // then there will only be one alloca and it will come first.
01320   for (; IP != BE; ++IP) {
01321     AllocaInst *AI = dyn_cast<AllocaInst>(IP);
01322     if (!AI || !AI->isStaticAlloca())
01323       break;
01324   }
01325 
01326   DebugLoc EntryLoc = &BB == &F.getEntryBlock()
01327                           ? IP->getDebugLoc().getFnDebugLoc(*C)
01328                           : IP->getDebugLoc();
01329   IRBuilder<> IRB(IP);
01330   IRB.SetCurrentDebugLocation(EntryLoc);
01331   Type *Int8Ty = IRB.getInt8Ty();
01332   GlobalVariable *Guard = new GlobalVariable(
01333       *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
01334       Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
01335   LoadInst *Load = IRB.CreateLoad(Guard);
01336   Load->setAtomic(Monotonic);
01337   Load->setAlignment(1);
01338   Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
01339   Instruction *Ins = SplitBlockAndInsertIfThen(
01340       Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
01341   IRB.SetInsertPoint(Ins);
01342   IRB.SetCurrentDebugLocation(EntryLoc);
01343   // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
01344   IRB.CreateCall(AsanCovFunction);
01345   StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
01346   Store->setAtomic(Monotonic);
01347   Store->setAlignment(1);
01348 }
01349 
01350 // Poor man's coverage that works with ASan.
01351 // We create a Guard boolean variable with the same linkage
01352 // as the function and inject this code into the entry block (-asan-coverage=1)
01353 // or all blocks (-asan-coverage=2):
01354 // if (*Guard) {
01355 //    __sanitizer_cov();
01356 //    *Guard = 1;
01357 // }
01358 // The accesses to Guard are atomic. The rest of the logic is
01359 // in __sanitizer_cov (it's fine to call it more than once).
01360 //
01361 // This coverage implementation provides very limited data:
01362 // it only tells if a given function (block) was ever executed.
01363 // No counters, no per-edge data.
01364 // But for many use cases this is what we need and the added slowdown
01365 // is negligible. This simple implementation will probably be obsoleted
01366 // by the upcoming Clang-based coverage implementation.
01367 // By having it here and now we hope to
01368 //  a) get the functionality to users earlier and
01369 //  b) collect usage statistics to help improve Clang coverage design.
01370 bool AddressSanitizer::InjectCoverage(Function &F,
01371                                       ArrayRef<BasicBlock *> AllBlocks) {
01372   if (!ClCoverage) return false;
01373 
01374   if (ClCoverage == 1 ||
01375       (unsigned)ClCoverageBlockThreshold < AllBlocks.size()) {
01376     InjectCoverageAtBlock(F, F.getEntryBlock());
01377   } else {
01378     for (auto BB : AllBlocks)
01379       InjectCoverageAtBlock(F, *BB);
01380   }
01381   return true;
01382 }
01383 
01384 bool AddressSanitizer::runOnFunction(Function &F) {
01385   if (&F == AsanCtorFunction) return false;
01386   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
01387   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
01388   initializeCallbacks(*F.getParent());
01389 
01390   // If needed, insert __asan_init before checking for SanitizeAddress attr.
01391   maybeInsertAsanInitAtFunctionEntry(F);
01392 
01393   if (!F.hasFnAttribute(Attribute::SanitizeAddress))
01394     return false;
01395 
01396   if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
01397     return false;
01398 
01399   // We want to instrument every address only once per basic block (unless there
01400   // are calls between uses).
01401   SmallSet<Value*, 16> TempsToInstrument;
01402   SmallVector<Instruction*, 16> ToInstrument;
01403   SmallVector<Instruction*, 8> NoReturnCalls;
01404   SmallVector<BasicBlock*, 16> AllBlocks;
01405   SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
01406   int NumAllocas = 0;
01407   bool IsWrite;
01408   unsigned Alignment;
01409 
01410   // Fill the set of memory operations to instrument.
01411   for (auto &BB : F) {
01412     AllBlocks.push_back(&BB);
01413     TempsToInstrument.clear();
01414     int NumInsnsPerBB = 0;
01415     for (auto &Inst : BB) {
01416       if (LooksLikeCodeInBug11395(&Inst)) return false;
01417       if (Value *Addr =
01418               isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
01419         if (ClOpt && ClOptSameTemp) {
01420           if (!TempsToInstrument.insert(Addr))
01421             continue;  // We've seen this temp in the current BB.
01422         }
01423       } else if (ClInvalidPointerPairs &&
01424                  isInterestingPointerComparisonOrSubtraction(&Inst)) {
01425         PointerComparisonsOrSubtracts.push_back(&Inst);
01426         continue;
01427       } else if (isa<MemIntrinsic>(Inst)) {
01428         // ok, take it.
01429       } else {
01430         if (isa<AllocaInst>(Inst))
01431           NumAllocas++;
01432         CallSite CS(&Inst);
01433         if (CS) {
01434           // A call inside BB.
01435           TempsToInstrument.clear();
01436           if (CS.doesNotReturn())
01437             NoReturnCalls.push_back(CS.getInstruction());
01438         }
01439         continue;
01440       }
01441       ToInstrument.push_back(&Inst);
01442       NumInsnsPerBB++;
01443       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
01444         break;
01445     }
01446   }
01447 
01448   Function *UninstrumentedDuplicate = nullptr;
01449   bool LikelyToInstrument =
01450       !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
01451   if (ClKeepUninstrumented && LikelyToInstrument) {
01452     ValueToValueMapTy VMap;
01453     UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
01454     UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
01455     UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
01456     F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
01457   }
01458 
01459   bool UseCalls = false;
01460   if (ClInstrumentationWithCallsThreshold >= 0 &&
01461       ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
01462     UseCalls = true;
01463 
01464   // Instrument.
01465   int NumInstrumented = 0;
01466   for (auto Inst : ToInstrument) {
01467     if (ClDebugMin < 0 || ClDebugMax < 0 ||
01468         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
01469       if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
01470         instrumentMop(Inst, UseCalls);
01471       else
01472         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
01473     }
01474     NumInstrumented++;
01475   }
01476 
01477   FunctionStackPoisoner FSP(F, *this);
01478   bool ChangedStack = FSP.runOnFunction();
01479 
01480   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
01481   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
01482   for (auto CI : NoReturnCalls) {
01483     IRBuilder<> IRB(CI);
01484     IRB.CreateCall(AsanHandleNoReturnFunc);
01485   }
01486 
01487   for (auto Inst : PointerComparisonsOrSubtracts) {
01488     instrumentPointerComparisonOrSubtraction(Inst);
01489     NumInstrumented++;
01490   }
01491 
01492   bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
01493 
01494   if (InjectCoverage(F, AllBlocks))
01495     res = true;
01496 
01497   DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
01498 
01499   if (ClKeepUninstrumented) {
01500     if (!res) {
01501       // No instrumentation is done, no need for the duplicate.
01502       if (UninstrumentedDuplicate)
01503         UninstrumentedDuplicate->eraseFromParent();
01504     } else {
01505       // The function was instrumented. We must have the duplicate.
01506       assert(UninstrumentedDuplicate);
01507       UninstrumentedDuplicate->setSection("NOASAN");
01508       assert(!F.hasSection());
01509       F.setSection("ASAN");
01510     }
01511   }
01512 
01513   return res;
01514 }
01515 
01516 // Workaround for bug 11395: we don't want to instrument stack in functions
01517 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
01518 // FIXME: remove once the bug 11395 is fixed.
01519 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
01520   if (LongSize != 32) return false;
01521   CallInst *CI = dyn_cast<CallInst>(I);
01522   if (!CI || !CI->isInlineAsm()) return false;
01523   if (CI->getNumArgOperands() <= 5) return false;
01524   // We have inline assembly with quite a few arguments.
01525   return true;
01526 }
01527 
01528 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
01529   IRBuilder<> IRB(*C);
01530   for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
01531     std::string Suffix = itostr(i);
01532     AsanStackMallocFunc[i] = checkInterfaceFunction(
01533         M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
01534                               IntptrTy, IntptrTy, NULL));
01535     AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
01536         kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
01537         IntptrTy, IntptrTy, NULL));
01538   }
01539   AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
01540       kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01541   AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
01542       kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01543 }
01544 
01545 void
01546 FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
01547                                       IRBuilder<> &IRB, Value *ShadowBase,
01548                                       bool DoPoison) {
01549   size_t n = ShadowBytes.size();
01550   size_t i = 0;
01551   // We need to (un)poison n bytes of stack shadow. Poison as many as we can
01552   // using 64-bit stores (if we are on 64-bit arch), then poison the rest
01553   // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
01554   for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
01555        LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
01556     for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
01557       uint64_t Val = 0;
01558       for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
01559         if (ASan.DL->isLittleEndian())
01560           Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
01561         else
01562           Val = (Val << 8) | ShadowBytes[i + j];
01563       }
01564       if (!Val) continue;
01565       Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
01566       Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
01567       Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
01568       IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
01569     }
01570   }
01571 }
01572 
01573 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
01574 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
01575 static int StackMallocSizeClass(uint64_t LocalStackSize) {
01576   assert(LocalStackSize <= kMaxStackMallocSize);
01577   uint64_t MaxSize = kMinStackMallocSize;
01578   for (int i = 0; ; i++, MaxSize *= 2)
01579     if (LocalStackSize <= MaxSize)
01580       return i;
01581   llvm_unreachable("impossible LocalStackSize");
01582 }
01583 
01584 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
01585 // We can not use MemSet intrinsic because it may end up calling the actual
01586 // memset. Size is a multiple of 8.
01587 // Currently this generates 8-byte stores on x86_64; it may be better to
01588 // generate wider stores.
01589 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
01590     IRBuilder<> &IRB, Value *ShadowBase, int Size) {
01591   assert(!(Size % 8));
01592   assert(kAsanStackAfterReturnMagic == 0xf5);
01593   for (int i = 0; i < Size; i += 8) {
01594     Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
01595     IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
01596                     IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
01597   }
01598 }
01599 
01600 static DebugLoc getFunctionEntryDebugLocation(Function &F) {
01601   for (const auto &Inst : F.getEntryBlock())
01602     if (!isa<AllocaInst>(Inst))
01603       return Inst.getDebugLoc();
01604   return DebugLoc();
01605 }
01606 
01607 void FunctionStackPoisoner::poisonStack() {
01608   int StackMallocIdx = -1;
01609   DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
01610 
01611   assert(AllocaVec.size() > 0);
01612   Instruction *InsBefore = AllocaVec[0];
01613   IRBuilder<> IRB(InsBefore);
01614   IRB.SetCurrentDebugLocation(EntryDebugLocation);
01615 
01616   SmallVector<ASanStackVariableDescription, 16> SVD;
01617   SVD.reserve(AllocaVec.size());
01618   for (AllocaInst *AI : AllocaVec) {
01619     ASanStackVariableDescription D = { AI->getName().data(),
01620                                    getAllocaSizeInBytes(AI),
01621                                    AI->getAlignment(), AI, 0};
01622     SVD.push_back(D);
01623   }
01624   // Minimal header size (left redzone) is 4 pointers,
01625   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
01626   size_t MinHeaderSize = ASan.LongSize / 2;
01627   ASanStackFrameLayout L;
01628   ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
01629   DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
01630   uint64_t LocalStackSize = L.FrameSize;
01631   bool DoStackMalloc =
01632       ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
01633 
01634   Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
01635   AllocaInst *MyAlloca =
01636       new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
01637   MyAlloca->setDebugLoc(EntryDebugLocation);
01638   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
01639   size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
01640   MyAlloca->setAlignment(FrameAlignment);
01641   assert(MyAlloca->isStaticAlloca());
01642   Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
01643   Value *LocalStackBase = OrigStackBase;
01644 
01645   if (DoStackMalloc) {
01646     // LocalStackBase = OrigStackBase
01647     // if (__asan_option_detect_stack_use_after_return)
01648     //   LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
01649     StackMallocIdx = StackMallocSizeClass(LocalStackSize);
01650     assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
01651     Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
01652         kAsanOptionDetectUAR, IRB.getInt32Ty());
01653     Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
01654                                   Constant::getNullValue(IRB.getInt32Ty()));
01655     Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
01656     BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
01657     IRBuilder<> IRBIf(Term);
01658     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
01659     LocalStackBase = IRBIf.CreateCall2(
01660         AsanStackMallocFunc[StackMallocIdx],
01661         ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
01662     BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
01663     IRB.SetInsertPoint(InsBefore);
01664     IRB.SetCurrentDebugLocation(EntryDebugLocation);
01665     PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
01666     Phi->addIncoming(OrigStackBase, CmpBlock);
01667     Phi->addIncoming(LocalStackBase, SetBlock);
01668     LocalStackBase = Phi;
01669   }
01670 
01671   // Insert poison calls for lifetime intrinsics for alloca.
01672   bool HavePoisonedAllocas = false;
01673   for (const auto &APC : AllocaPoisonCallVec) {
01674     assert(APC.InsBefore);
01675     assert(APC.AI);
01676     IRBuilder<> IRB(APC.InsBefore);
01677     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
01678     HavePoisonedAllocas |= APC.DoPoison;
01679   }
01680 
01681   // Replace Alloca instructions with base+offset.
01682   for (const auto &Desc : SVD) {
01683     AllocaInst *AI = Desc.AI;
01684     Value *NewAllocaPtr = IRB.CreateIntToPtr(
01685         IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
01686         AI->getType());
01687     replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
01688     AI->replaceAllUsesWith(NewAllocaPtr);
01689   }
01690 
01691   // The left-most redzone has enough space for at least 4 pointers.
01692   // Write the Magic value to redzone[0].
01693   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
01694   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
01695                   BasePlus0);
01696   // Write the frame description constant to redzone[1].
01697   Value *BasePlus1 = IRB.CreateIntToPtr(
01698     IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
01699     IntptrPtrTy);
01700   GlobalVariable *StackDescriptionGlobal =
01701       createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
01702                                    /*AllowMerging*/true);
01703   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
01704                                              IntptrTy);
01705   IRB.CreateStore(Description, BasePlus1);
01706   // Write the PC to redzone[2].
01707   Value *BasePlus2 = IRB.CreateIntToPtr(
01708     IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
01709                                                    2 * ASan.LongSize/8)),
01710     IntptrPtrTy);
01711   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
01712 
01713   // Poison the stack redzones at the entry.
01714   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
01715   poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
01716 
01717   // (Un)poison the stack before all ret instructions.
01718   for (auto Ret : RetVec) {
01719     IRBuilder<> IRBRet(Ret);
01720     // Mark the current frame as retired.
01721     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
01722                        BasePlus0);
01723     if (DoStackMalloc) {
01724       assert(StackMallocIdx >= 0);
01725       // if LocalStackBase != OrigStackBase:
01726       //     // In use-after-return mode, poison the whole stack frame.
01727       //     if StackMallocIdx <= 4
01728       //         // For small sizes inline the whole thing:
01729       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
01730       //         **SavedFlagPtr(LocalStackBase) = 0
01731       //     else
01732       //         __asan_stack_free_N(LocalStackBase, OrigStackBase)
01733       // else
01734       //     <This is not a fake stack; unpoison the redzones>
01735       Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
01736       TerminatorInst *ThenTerm, *ElseTerm;
01737       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
01738 
01739       IRBuilder<> IRBPoison(ThenTerm);
01740       if (StackMallocIdx <= 4) {
01741         int ClassSize = kMinStackMallocSize << StackMallocIdx;
01742         SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
01743                                            ClassSize >> Mapping.Scale);
01744         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
01745             LocalStackBase,
01746             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
01747         Value *SavedFlagPtr = IRBPoison.CreateLoad(
01748             IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
01749         IRBPoison.CreateStore(
01750             Constant::getNullValue(IRBPoison.getInt8Ty()),
01751             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
01752       } else {
01753         // For larger frames call __asan_stack_free_*.
01754         IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
01755                               ConstantInt::get(IntptrTy, LocalStackSize),
01756                               OrigStackBase);
01757       }
01758 
01759       IRBuilder<> IRBElse(ElseTerm);
01760       poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
01761     } else if (HavePoisonedAllocas) {
01762       // If we poisoned some allocas in llvm.lifetime analysis,
01763       // unpoison whole stack frame now.
01764       assert(LocalStackBase == OrigStackBase);
01765       poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
01766     } else {
01767       poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
01768     }
01769   }
01770 
01771   // We are done. Remove the old unused alloca instructions.
01772   for (auto AI : AllocaVec)
01773     AI->eraseFromParent();
01774 }
01775 
01776 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
01777                                          IRBuilder<> &IRB, bool DoPoison) {
01778   // For now just insert the call to ASan runtime.
01779   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
01780   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
01781   IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
01782                            : AsanUnpoisonStackMemoryFunc,
01783                   AddrArg, SizeArg);
01784 }
01785 
01786 // Handling llvm.lifetime intrinsics for a given %alloca:
01787 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
01788 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
01789 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
01790 //     could be poisoned by previous llvm.lifetime.end instruction, as the
01791 //     variable may go in and out of scope several times, e.g. in loops).
01792 // (3) if we poisoned at least one %alloca in a function,
01793 //     unpoison the whole stack frame at function exit.
01794 
01795 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
01796   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
01797     // We're intested only in allocas we can handle.
01798     return isInterestingAlloca(*AI) ? AI : nullptr;
01799   // See if we've already calculated (or started to calculate) alloca for a
01800   // given value.
01801   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
01802   if (I != AllocaForValue.end())
01803     return I->second;
01804   // Store 0 while we're calculating alloca for value V to avoid
01805   // infinite recursion if the value references itself.
01806   AllocaForValue[V] = nullptr;
01807   AllocaInst *Res = nullptr;
01808   if (CastInst *CI = dyn_cast<CastInst>(V))
01809     Res = findAllocaForValue(CI->getOperand(0));
01810   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
01811     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01812       Value *IncValue = PN->getIncomingValue(i);
01813       // Allow self-referencing phi-nodes.
01814       if (IncValue == PN) continue;
01815       AllocaInst *IncValueAI = findAllocaForValue(IncValue);
01816       // AI for incoming values should exist and should all be equal.
01817       if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
01818         return nullptr;
01819       Res = IncValueAI;
01820     }
01821   }
01822   if (Res)
01823     AllocaForValue[V] = Res;
01824   return Res;
01825 }