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