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