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