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