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