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