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