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