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