LLVM API Documentation

AddressSanitizer.cpp
Go to the documentation of this file.
00001 //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file is a part of AddressSanitizer, an address sanity checker.
00011 // Details of the algorithm:
00012 //  http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #define DEBUG_TYPE "asan"
00017 
00018 #include "llvm/Transforms/Instrumentation.h"
00019 #include "llvm/ADT/ArrayRef.h"
00020 #include "llvm/ADT/DenseMap.h"
00021 #include "llvm/ADT/DepthFirstIterator.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/IR/CallSite.h"
00029 #include "llvm/IR/DIBuilder.h"
00030 #include "llvm/IR/DataLayout.h"
00031 #include "llvm/IR/Function.h"
00032 #include "llvm/IR/IRBuilder.h"
00033 #include "llvm/IR/InlineAsm.h"
00034 #include "llvm/IR/InstVisitor.h"
00035 #include "llvm/IR/IntrinsicInst.h"
00036 #include "llvm/IR/LLVMContext.h"
00037 #include "llvm/IR/MDBuilder.h"
00038 #include "llvm/IR/Module.h"
00039 #include "llvm/IR/Type.h"
00040 #include "llvm/Support/CommandLine.h"
00041 #include "llvm/Support/DataTypes.h"
00042 #include "llvm/Support/Debug.h"
00043 #include "llvm/Support/Endian.h"
00044 #include "llvm/Support/system_error.h"
00045 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
00046 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00047 #include "llvm/Transforms/Utils/Cloning.h"
00048 #include "llvm/Transforms/Utils/Local.h"
00049 #include "llvm/Transforms/Utils/ModuleUtils.h"
00050 #include "llvm/Transforms/Utils/SpecialCaseList.h"
00051 #include <algorithm>
00052 #include <string>
00053 
00054 using namespace llvm;
00055 
00056 static const uint64_t kDefaultShadowScale = 3;
00057 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
00058 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
00059 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000;  // < 2G.
00060 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
00061 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
00062 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
00063 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
00064 
00065 static const size_t kMinStackMallocSize = 1 << 6;  // 64B
00066 static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
00067 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
00068 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
00069 
00070 static const char *const kAsanModuleCtorName = "asan.module_ctor";
00071 static const char *const kAsanModuleDtorName = "asan.module_dtor";
00072 static const int         kAsanCtorAndCtorPriority = 1;
00073 static const char *const kAsanReportErrorTemplate = "__asan_report_";
00074 static const char *const kAsanReportLoadN = "__asan_report_load_n";
00075 static const char *const kAsanReportStoreN = "__asan_report_store_n";
00076 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
00077 static const char *const kAsanUnregisterGlobalsName =
00078     "__asan_unregister_globals";
00079 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
00080 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
00081 static const char *const kAsanInitName = "__asan_init_v3";
00082 static const char *const kAsanCovName = "__sanitizer_cov";
00083 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
00084 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
00085 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
00086 static const int         kMaxAsanStackMallocSizeClass = 10;
00087 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
00088 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
00089 static const char *const kAsanGenPrefix = "__asan_gen_";
00090 static const char *const kAsanPoisonStackMemoryName =
00091     "__asan_poison_stack_memory";
00092 static const char *const kAsanUnpoisonStackMemoryName =
00093     "__asan_unpoison_stack_memory";
00094 
00095 static const char *const kAsanOptionDetectUAR =
00096     "__asan_option_detect_stack_use_after_return";
00097 
00098 #ifndef NDEBUG
00099 static const int kAsanStackAfterReturnMagic = 0xf5;
00100 #endif
00101 
00102 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
00103 static const size_t kNumberOfAccessSizes = 5;
00104 
00105 // Command-line flags.
00106 
00107 // This flag may need to be replaced with -f[no-]asan-reads.
00108 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
00109        cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
00110 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
00111        cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
00112 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
00113        cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
00114        cl::Hidden, cl::init(true));
00115 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
00116        cl::desc("use instrumentation with slow path for all accesses"),
00117        cl::Hidden, cl::init(false));
00118 // This flag limits the number of instructions to be instrumented
00119 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
00120 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
00121 // set it to 10000.
00122 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
00123        cl::init(10000),
00124        cl::desc("maximal number of instructions to instrument in any given BB"),
00125        cl::Hidden);
00126 // This flag may need to be replaced with -f[no]asan-stack.
00127 static cl::opt<bool> ClStack("asan-stack",
00128        cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
00129 // This flag may need to be replaced with -f[no]asan-use-after-return.
00130 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
00131        cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
00132 // This flag may need to be replaced with -f[no]asan-globals.
00133 static cl::opt<bool> ClGlobals("asan-globals",
00134        cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
00135 static cl::opt<int> ClCoverage("asan-coverage",
00136        cl::desc("ASan coverage. 0: none, 1: entry block, 2: all blocks"),
00137        cl::Hidden, cl::init(false));
00138 static cl::opt<bool> ClInitializers("asan-initialization-order",
00139        cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
00140 static cl::opt<bool> ClMemIntrin("asan-memintrin",
00141        cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
00142 static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
00143        cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
00144        cl::Hidden, cl::init(false));
00145 static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
00146        cl::desc("Realign stack to the value of this flag (power of two)"),
00147        cl::Hidden, cl::init(32));
00148 static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
00149        cl::desc("File containing the list of objects to ignore "
00150                 "during instrumentation"), cl::Hidden);
00151 
00152 // This is an experimental feature that will allow to choose between
00153 // instrumented and non-instrumented code at link-time.
00154 // If this option is on, just before instrumenting a function we create its
00155 // clone; if the function is not changed by asan the clone is deleted.
00156 // If we end up with a clone, we put the instrumented function into a section
00157 // called "ASAN" and the uninstrumented function into a section called "NOASAN".
00158 //
00159 // This is still a prototype, we need to figure out a way to keep two copies of
00160 // a function so that the linker can easily choose one of them.
00161 static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
00162        cl::desc("Keep uninstrumented copies of functions"),
00163        cl::Hidden, cl::init(false));
00164 
00165 // These flags allow to change the shadow mapping.
00166 // The shadow mapping looks like
00167 //    Shadow = (Mem >> scale) + (1 << offset_log)
00168 static cl::opt<int> ClMappingScale("asan-mapping-scale",
00169        cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
00170 
00171 // Optimization flags. Not user visible, used mostly for testing
00172 // and benchmarking the tool.
00173 static cl::opt<bool> ClOpt("asan-opt",
00174        cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
00175 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
00176        cl::desc("Instrument the same temp just once"), cl::Hidden,
00177        cl::init(true));
00178 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
00179        cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
00180 
00181 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
00182        cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
00183        cl::Hidden, cl::init(false));
00184 
00185 // Debug flags.
00186 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
00187                             cl::init(0));
00188 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
00189                                  cl::Hidden, cl::init(0));
00190 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
00191                                         cl::Hidden, cl::desc("Debug func"));
00192 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
00193                                cl::Hidden, cl::init(-1));
00194 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
00195                                cl::Hidden, cl::init(-1));
00196 
00197 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
00198 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
00199 STATISTIC(NumOptimizedAccessesToGlobalArray,
00200           "Number of optimized accesses to global arrays");
00201 STATISTIC(NumOptimizedAccessesToGlobalVar,
00202           "Number of optimized accesses to global vars");
00203 
00204 namespace {
00205 /// A set of dynamically initialized globals extracted from metadata.
00206 class SetOfDynamicallyInitializedGlobals {
00207  public:
00208   void Init(Module& M) {
00209     // Clang generates metadata identifying all dynamically initialized globals.
00210     NamedMDNode *DynamicGlobals =
00211         M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
00212     if (!DynamicGlobals)
00213       return;
00214     for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
00215       MDNode *MDN = DynamicGlobals->getOperand(i);
00216       assert(MDN->getNumOperands() == 1);
00217       Value *VG = MDN->getOperand(0);
00218       // The optimizer may optimize away a global entirely, in which case we
00219       // cannot instrument access to it.
00220       if (!VG)
00221         continue;
00222       DynInitGlobals.insert(cast<GlobalVariable>(VG));
00223     }
00224   }
00225   bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
00226  private:
00227   SmallSet<GlobalValue*, 32> DynInitGlobals;
00228 };
00229 
00230 /// This struct defines the shadow mapping using the rule:
00231 ///   shadow = (mem >> Scale) ADD-or-OR Offset.
00232 struct ShadowMapping {
00233   int Scale;
00234   uint64_t Offset;
00235   bool OrShadowOffset;
00236 };
00237 
00238 static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
00239   llvm::Triple TargetTriple(M.getTargetTriple());
00240   bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
00241   // bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
00242   bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
00243   bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
00244   bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
00245                  TargetTriple.getArch() == llvm::Triple::ppc64le;
00246   bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
00247   bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
00248                   TargetTriple.getArch() == llvm::Triple::mipsel;
00249 
00250   ShadowMapping Mapping;
00251 
00252   if (LongSize == 32) {
00253     if (IsAndroid)
00254       Mapping.Offset = 0;
00255     else if (IsMIPS32)
00256       Mapping.Offset = kMIPS32_ShadowOffset32;
00257     else if (IsFreeBSD)
00258       Mapping.Offset = kFreeBSD_ShadowOffset32;
00259     else
00260       Mapping.Offset = kDefaultShadowOffset32;
00261   } else {  // LongSize == 64
00262     if (IsPPC64)
00263       Mapping.Offset = kPPC64_ShadowOffset64;
00264     else if (IsFreeBSD)
00265       Mapping.Offset = kFreeBSD_ShadowOffset64;
00266     else if (IsLinux && IsX86_64)
00267       Mapping.Offset = kSmallX86_64ShadowOffset;
00268     else
00269       Mapping.Offset = kDefaultShadowOffset64;
00270   }
00271 
00272   Mapping.Scale = kDefaultShadowScale;
00273   if (ClMappingScale) {
00274     Mapping.Scale = ClMappingScale;
00275   }
00276 
00277   // OR-ing shadow offset if more efficient (at least on x86) if the offset
00278   // is a power of two, but on ppc64 we have to use add since the shadow
00279   // offset is not necessary 1/8-th of the address space.
00280   Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
00281 
00282   return Mapping;
00283 }
00284 
00285 static size_t RedzoneSizeForScale(int MappingScale) {
00286   // Redzone used for stack and globals is at least 32 bytes.
00287   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
00288   return std::max(32U, 1U << MappingScale);
00289 }
00290 
00291 /// AddressSanitizer: instrument the code in module to find memory bugs.
00292 struct AddressSanitizer : public FunctionPass {
00293   AddressSanitizer(bool CheckInitOrder = true,
00294                    bool CheckUseAfterReturn = false,
00295                    bool CheckLifetime = false,
00296                    StringRef BlacklistFile = StringRef())
00297       : FunctionPass(ID),
00298         CheckInitOrder(CheckInitOrder || ClInitializers),
00299         CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
00300         CheckLifetime(CheckLifetime || ClCheckLifetime),
00301         BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
00302                                             : BlacklistFile) {}
00303   const char *getPassName() const override {
00304     return "AddressSanitizerFunctionPass";
00305   }
00306   void instrumentMop(Instruction *I);
00307   void instrumentPointerComparisonOrSubtraction(Instruction *I);
00308   void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
00309                          Value *Addr, uint32_t TypeSize, bool IsWrite,
00310                          Value *SizeArgument);
00311   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
00312                            Value *ShadowValue, uint32_t TypeSize);
00313   Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
00314                                  bool IsWrite, size_t AccessSizeIndex,
00315                                  Value *SizeArgument);
00316   bool instrumentMemIntrinsic(MemIntrinsic *MI);
00317   void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
00318                                    Value *Size,
00319                                    Instruction *InsertBefore, bool IsWrite);
00320   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
00321   bool runOnFunction(Function &F) override;
00322   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
00323   bool doInitialization(Module &M) override;
00324   static char ID;  // Pass identification, replacement for typeid
00325 
00326  private:
00327   void initializeCallbacks(Module &M);
00328 
00329   bool LooksLikeCodeInBug11395(Instruction *I);
00330   bool GlobalIsLinkerInitialized(GlobalVariable *G);
00331   bool InjectCoverage(Function &F, const ArrayRef<BasicBlock*> AllBlocks);
00332   void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
00333 
00334   bool CheckInitOrder;
00335   bool CheckUseAfterReturn;
00336   bool CheckLifetime;
00337   SmallString<64> BlacklistFile;
00338 
00339   LLVMContext *C;
00340   const DataLayout *DL;
00341   int LongSize;
00342   Type *IntptrTy;
00343   ShadowMapping Mapping;
00344   Function *AsanCtorFunction;
00345   Function *AsanInitFunction;
00346   Function *AsanHandleNoReturnFunc;
00347   Function *AsanCovFunction;
00348   Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
00349   std::unique_ptr<SpecialCaseList> BL;
00350   // This array is indexed by AccessIsWrite and log2(AccessSize).
00351   Function *AsanErrorCallback[2][kNumberOfAccessSizes];
00352   // This array is indexed by AccessIsWrite.
00353   Function *AsanErrorCallbackSized[2];
00354   InlineAsm *EmptyAsm;
00355   SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
00356 
00357   friend struct FunctionStackPoisoner;
00358 };
00359 
00360 class AddressSanitizerModule : public ModulePass {
00361  public:
00362   AddressSanitizerModule(bool CheckInitOrder = true,
00363                          StringRef BlacklistFile = StringRef())
00364       : ModulePass(ID),
00365         CheckInitOrder(CheckInitOrder || ClInitializers),
00366         BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
00367                                             : BlacklistFile) {}
00368   bool runOnModule(Module &M) override;
00369   static char ID;  // Pass identification, replacement for typeid
00370   const char *getPassName() const override {
00371     return "AddressSanitizerModule";
00372   }
00373 
00374  private:
00375   void initializeCallbacks(Module &M);
00376 
00377   bool ShouldInstrumentGlobal(GlobalVariable *G);
00378   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
00379   size_t MinRedzoneSizeForGlobal() const {
00380     return RedzoneSizeForScale(Mapping.Scale);
00381   }
00382 
00383   bool CheckInitOrder;
00384   SmallString<64> BlacklistFile;
00385 
00386   std::unique_ptr<SpecialCaseList> BL;
00387   SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
00388   Type *IntptrTy;
00389   LLVMContext *C;
00390   const DataLayout *DL;
00391   ShadowMapping Mapping;
00392   Function *AsanPoisonGlobals;
00393   Function *AsanUnpoisonGlobals;
00394   Function *AsanRegisterGlobals;
00395   Function *AsanUnregisterGlobals;
00396 };
00397 
00398 // Stack poisoning does not play well with exception handling.
00399 // When an exception is thrown, we essentially bypass the code
00400 // that unpoisones the stack. This is why the run-time library has
00401 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
00402 // stack in the interceptor. This however does not work inside the
00403 // actual function which catches the exception. Most likely because the
00404 // compiler hoists the load of the shadow value somewhere too high.
00405 // This causes asan to report a non-existing bug on 453.povray.
00406 // It sounds like an LLVM bug.
00407 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
00408   Function &F;
00409   AddressSanitizer &ASan;
00410   DIBuilder DIB;
00411   LLVMContext *C;
00412   Type *IntptrTy;
00413   Type *IntptrPtrTy;
00414   ShadowMapping Mapping;
00415 
00416   SmallVector<AllocaInst*, 16> AllocaVec;
00417   SmallVector<Instruction*, 8> RetVec;
00418   unsigned StackAlignment;
00419 
00420   Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
00421            *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
00422   Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
00423 
00424   // Stores a place and arguments of poisoning/unpoisoning call for alloca.
00425   struct AllocaPoisonCall {
00426     IntrinsicInst *InsBefore;
00427     AllocaInst *AI;
00428     uint64_t Size;
00429     bool DoPoison;
00430   };
00431   SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
00432 
00433   // Maps Value to an AllocaInst from which the Value is originated.
00434   typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
00435   AllocaForValueMapTy AllocaForValue;
00436 
00437   FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
00438       : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
00439         IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
00440         Mapping(ASan.Mapping),
00441         StackAlignment(1 << Mapping.Scale) {}
00442 
00443   bool runOnFunction() {
00444     if (!ClStack) return false;
00445     // Collect alloca, ret, lifetime instructions etc.
00446     for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
00447       visit(*BB);
00448 
00449     if (AllocaVec.empty()) return false;
00450 
00451     initializeCallbacks(*F.getParent());
00452 
00453     poisonStack();
00454 
00455     if (ClDebugStack) {
00456       DEBUG(dbgs() << F);
00457     }
00458     return true;
00459   }
00460 
00461   // Finds all static Alloca instructions and puts
00462   // poisoned red zones around all of them.
00463   // Then unpoison everything back before the function returns.
00464   void poisonStack();
00465 
00466   // ----------------------- Visitors.
00467   /// \brief Collect all Ret instructions.
00468   void visitReturnInst(ReturnInst &RI) {
00469     RetVec.push_back(&RI);
00470   }
00471 
00472   /// \brief Collect Alloca instructions we want (and can) handle.
00473   void visitAllocaInst(AllocaInst &AI) {
00474     if (!isInterestingAlloca(AI)) return;
00475 
00476     StackAlignment = std::max(StackAlignment, AI.getAlignment());
00477     AllocaVec.push_back(&AI);
00478   }
00479 
00480   /// \brief Collect lifetime intrinsic calls to check for use-after-scope
00481   /// errors.
00482   void visitIntrinsicInst(IntrinsicInst &II) {
00483     if (!ASan.CheckLifetime) return;
00484     Intrinsic::ID ID = II.getIntrinsicID();
00485     if (ID != Intrinsic::lifetime_start &&
00486         ID != Intrinsic::lifetime_end)
00487       return;
00488     // Found lifetime intrinsic, add ASan instrumentation if necessary.
00489     ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
00490     // If size argument is undefined, don't do anything.
00491     if (Size->isMinusOne()) return;
00492     // Check that size doesn't saturate uint64_t and can
00493     // be stored in IntptrTy.
00494     const uint64_t SizeValue = Size->getValue().getLimitedValue();
00495     if (SizeValue == ~0ULL ||
00496         !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
00497       return;
00498     // Find alloca instruction that corresponds to llvm.lifetime argument.
00499     AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
00500     if (!AI) return;
00501     bool DoPoison = (ID == Intrinsic::lifetime_end);
00502     AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
00503     AllocaPoisonCallVec.push_back(APC);
00504   }
00505 
00506   // ---------------------- Helpers.
00507   void initializeCallbacks(Module &M);
00508 
00509   // Check if we want (and can) handle this alloca.
00510   bool isInterestingAlloca(AllocaInst &AI) const {
00511     return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
00512             AI.getAllocatedType()->isSized() &&
00513             // alloca() may be called with 0 size, ignore it.
00514             getAllocaSizeInBytes(&AI) > 0);
00515   }
00516 
00517   uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
00518     Type *Ty = AI->getAllocatedType();
00519     uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
00520     return SizeInBytes;
00521   }
00522   /// Finds alloca where the value comes from.
00523   AllocaInst *findAllocaForValue(Value *V);
00524   void poisonRedZones(const ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
00525                       Value *ShadowBase, bool DoPoison);
00526   void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
00527 
00528   void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
00529                                           int Size);
00530 };
00531 
00532 }  // namespace
00533 
00534 char AddressSanitizer::ID = 0;
00535 INITIALIZE_PASS(AddressSanitizer, "asan",
00536     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
00537     false, false)
00538 FunctionPass *llvm::createAddressSanitizerFunctionPass(
00539     bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
00540     StringRef BlacklistFile) {
00541   return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
00542                               CheckLifetime, BlacklistFile);
00543 }
00544 
00545 char AddressSanitizerModule::ID = 0;
00546 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
00547     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
00548     "ModulePass", false, false)
00549 ModulePass *llvm::createAddressSanitizerModulePass(
00550     bool CheckInitOrder, StringRef BlacklistFile) {
00551   return new AddressSanitizerModule(CheckInitOrder, BlacklistFile);
00552 }
00553 
00554 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
00555   size_t Res = countTrailingZeros(TypeSize / 8);
00556   assert(Res < kNumberOfAccessSizes);
00557   return Res;
00558 }
00559 
00560 // \brief Create a constant for Str so that we can pass it to the run-time lib.
00561 static GlobalVariable *createPrivateGlobalForString(
00562     Module &M, StringRef Str, bool AllowMerging) {
00563   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
00564   // We use private linkage for module-local strings. If they can be merged
00565   // with another one, we set the unnamed_addr attribute.
00566   GlobalVariable *GV =
00567       new GlobalVariable(M, StrConst->getType(), true,
00568                          GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
00569   if (AllowMerging)
00570     GV->setUnnamedAddr(true);
00571   GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
00572   return GV;
00573 }
00574 
00575 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
00576   return G->getName().find(kAsanGenPrefix) == 0;
00577 }
00578 
00579 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
00580   // Shadow >> scale
00581   Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
00582   if (Mapping.Offset == 0)
00583     return Shadow;
00584   // (Shadow >> scale) | offset
00585   if (Mapping.OrShadowOffset)
00586     return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
00587   else
00588     return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
00589 }
00590 
00591 void AddressSanitizer::instrumentMemIntrinsicParam(
00592     Instruction *OrigIns,
00593     Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
00594   IRBuilder<> IRB(InsertBefore);
00595   if (Size->getType() != IntptrTy)
00596     Size = IRB.CreateIntCast(Size, IntptrTy, false);
00597   // Check the first byte.
00598   instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
00599   // Check the last byte.
00600   IRB.SetInsertPoint(InsertBefore);
00601   Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
00602   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
00603   Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
00604   instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
00605 }
00606 
00607 // Instrument memset/memmove/memcpy
00608 bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
00609   Value *Dst = MI->getDest();
00610   MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
00611   Value *Src = MemTran ? MemTran->getSource() : 0;
00612   Value *Length = MI->getLength();
00613 
00614   Constant *ConstLength = dyn_cast<Constant>(Length);
00615   Instruction *InsertBefore = MI;
00616   if (ConstLength) {
00617     if (ConstLength->isNullValue()) return false;
00618   } else {
00619     // The size is not a constant so it could be zero -- check at run-time.
00620     IRBuilder<> IRB(InsertBefore);
00621 
00622     Value *Cmp = IRB.CreateICmpNE(Length,
00623                                   Constant::getNullValue(Length->getType()));
00624     InsertBefore = SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
00625   }
00626 
00627   instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
00628   if (Src)
00629     instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
00630   return true;
00631 }
00632 
00633 // If I is an interesting memory access, return the PointerOperand
00634 // and set IsWrite. Otherwise return NULL.
00635 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
00636   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00637     if (!ClInstrumentReads) return NULL;
00638     *IsWrite = false;
00639     return LI->getPointerOperand();
00640   }
00641   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
00642     if (!ClInstrumentWrites) return NULL;
00643     *IsWrite = true;
00644     return SI->getPointerOperand();
00645   }
00646   if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
00647     if (!ClInstrumentAtomics) return NULL;
00648     *IsWrite = true;
00649     return RMW->getPointerOperand();
00650   }
00651   if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
00652     if (!ClInstrumentAtomics) return NULL;
00653     *IsWrite = true;
00654     return XCHG->getPointerOperand();
00655   }
00656   return NULL;
00657 }
00658 
00659 static bool isPointerOperand(Value *V) {
00660   return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
00661 }
00662 
00663 // This is a rough heuristic; it may cause both false positives and
00664 // false negatives. The proper implementation requires cooperation with
00665 // the frontend.
00666 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
00667   if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
00668     if (!Cmp->isRelational())
00669       return false;
00670   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
00671     if (BO->getOpcode() != Instruction::Sub)
00672       return false;
00673   } else {
00674     return false;
00675   }
00676   if (!isPointerOperand(I->getOperand(0)) ||
00677       !isPointerOperand(I->getOperand(1)))
00678       return false;
00679   return true;
00680 }
00681 
00682 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
00683   // If a global variable does not have dynamic initialization we don't
00684   // have to instrument it.  However, if a global does not have initializer
00685   // at all, we assume it has dynamic initializer (in other TU).
00686   return G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G);
00687 }
00688 
00689 void
00690 AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
00691   IRBuilder<> IRB(I);
00692   Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
00693   Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
00694   for (int i = 0; i < 2; i++) {
00695     if (Param[i]->getType()->isPointerTy())
00696       Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
00697   }
00698   IRB.CreateCall2(F, Param[0], Param[1]);
00699 }
00700 
00701 void AddressSanitizer::instrumentMop(Instruction *I) {
00702   bool IsWrite = false;
00703   Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
00704   assert(Addr);
00705   if (ClOpt && ClOptGlobals) {
00706     if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
00707       // If initialization order checking is disabled, a simple access to a
00708       // dynamically initialized global is always valid.
00709       if (!CheckInitOrder || GlobalIsLinkerInitialized(G)) {
00710         NumOptimizedAccessesToGlobalVar++;
00711         return;
00712       }
00713     }
00714     ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
00715     if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
00716       if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
00717         if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
00718           NumOptimizedAccessesToGlobalArray++;
00719           return;
00720         }
00721       }
00722     }
00723   }
00724 
00725   Type *OrigPtrTy = Addr->getType();
00726   Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
00727 
00728   assert(OrigTy->isSized());
00729   uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
00730 
00731   assert((TypeSize % 8) == 0);
00732 
00733   if (IsWrite)
00734     NumInstrumentedWrites++;
00735   else
00736     NumInstrumentedReads++;
00737 
00738   // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
00739   if (TypeSize == 8  || TypeSize == 16 ||
00740       TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
00741     return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
00742   // Instrument unusual size (but still multiple of 8).
00743   // We can not do it with a single check, so we do 1-byte check for the first
00744   // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
00745   // to report the actual access size.
00746   IRBuilder<> IRB(I);
00747   Value *LastByte =  IRB.CreateIntToPtr(
00748       IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
00749                     ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
00750       OrigPtrTy);
00751   Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
00752   instrumentAddress(I, I, Addr, 8, IsWrite, Size);
00753   instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
00754 }
00755 
00756 // Validate the result of Module::getOrInsertFunction called for an interface
00757 // function of AddressSanitizer. If the instrumented module defines a function
00758 // with the same name, their prototypes must match, otherwise
00759 // getOrInsertFunction returns a bitcast.
00760 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
00761   if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
00762   FuncOrBitcast->dump();
00763   report_fatal_error("trying to redefine an AddressSanitizer "
00764                      "interface function");
00765 }
00766 
00767 Instruction *AddressSanitizer::generateCrashCode(
00768     Instruction *InsertBefore, Value *Addr,
00769     bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
00770   IRBuilder<> IRB(InsertBefore);
00771   CallInst *Call = SizeArgument
00772     ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
00773     : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
00774 
00775   // We don't do Call->setDoesNotReturn() because the BB already has
00776   // UnreachableInst at the end.
00777   // This EmptyAsm is required to avoid callback merge.
00778   IRB.CreateCall(EmptyAsm);
00779   return Call;
00780 }
00781 
00782 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
00783                                             Value *ShadowValue,
00784                                             uint32_t TypeSize) {
00785   size_t Granularity = 1 << Mapping.Scale;
00786   // Addr & (Granularity - 1)
00787   Value *LastAccessedByte = IRB.CreateAnd(
00788       AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
00789   // (Addr & (Granularity - 1)) + size - 1
00790   if (TypeSize / 8 > 1)
00791     LastAccessedByte = IRB.CreateAdd(
00792         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
00793   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
00794   LastAccessedByte = IRB.CreateIntCast(
00795       LastAccessedByte, ShadowValue->getType(), false);
00796   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
00797   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
00798 }
00799 
00800 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
00801                                          Instruction *InsertBefore,
00802                                          Value *Addr, uint32_t TypeSize,
00803                                          bool IsWrite, Value *SizeArgument) {
00804   IRBuilder<> IRB(InsertBefore);
00805   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
00806 
00807   Type *ShadowTy  = IntegerType::get(
00808       *C, std::max(8U, TypeSize >> Mapping.Scale));
00809   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
00810   Value *ShadowPtr = memToShadow(AddrLong, IRB);
00811   Value *CmpVal = Constant::getNullValue(ShadowTy);
00812   Value *ShadowValue = IRB.CreateLoad(
00813       IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
00814 
00815   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
00816   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
00817   size_t Granularity = 1 << Mapping.Scale;
00818   TerminatorInst *CrashTerm = 0;
00819 
00820   if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
00821     TerminatorInst *CheckTerm =
00822         SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
00823     assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
00824     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
00825     IRB.SetInsertPoint(CheckTerm);
00826     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
00827     BasicBlock *CrashBlock =
00828         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
00829     CrashTerm = new UnreachableInst(*C, CrashBlock);
00830     BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
00831     ReplaceInstWithInst(CheckTerm, NewTerm);
00832   } else {
00833     CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
00834   }
00835 
00836   Instruction *Crash = generateCrashCode(
00837       CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
00838   Crash->setDebugLoc(OrigIns->getDebugLoc());
00839 }
00840 
00841 void AddressSanitizerModule::createInitializerPoisonCalls(
00842     Module &M, GlobalValue *ModuleName) {
00843   // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
00844   Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
00845   // If that function is not present, this TU contains no globals, or they have
00846   // all been optimized away
00847   if (!GlobalInit)
00848     return;
00849 
00850   // Set up the arguments to our poison/unpoison functions.
00851   IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
00852 
00853   // Add a call to poison all external globals before the given function starts.
00854   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
00855   IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
00856 
00857   // Add calls to unpoison all globals before each return instruction.
00858   for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
00859       I != E; ++I) {
00860     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
00861       CallInst::Create(AsanUnpoisonGlobals, "", RI);
00862     }
00863   }
00864 }
00865 
00866 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
00867   Type *Ty = cast<PointerType>(G->getType())->getElementType();
00868   DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
00869 
00870   if (BL->isIn(*G)) return false;
00871   if (!Ty->isSized()) return false;
00872   if (!G->hasInitializer()) return false;
00873   if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
00874   // Touch only those globals that will not be defined in other modules.
00875   // Don't handle ODR type linkages since other modules may be built w/o asan.
00876   if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
00877       G->getLinkage() != GlobalVariable::PrivateLinkage &&
00878       G->getLinkage() != GlobalVariable::InternalLinkage)
00879     return false;
00880   // Two problems with thread-locals:
00881   //   - The address of the main thread's copy can't be computed at link-time.
00882   //   - Need to poison all copies, not just the main thread's one.
00883   if (G->isThreadLocal())
00884     return false;
00885   // For now, just ignore this Global if the alignment is large.
00886   if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
00887 
00888   // Ignore all the globals with the names starting with "\01L_OBJC_".
00889   // Many of those are put into the .cstring section. The linker compresses
00890   // that section by removing the spare \0s after the string terminator, so
00891   // our redzones get broken.
00892   if ((G->getName().find("\01L_OBJC_") == 0) ||
00893       (G->getName().find("\01l_OBJC_") == 0)) {
00894     DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G << "\n");
00895     return false;
00896   }
00897 
00898   if (G->hasSection()) {
00899     StringRef Section(G->getSection());
00900     // Ignore the globals from the __OBJC section. The ObjC runtime assumes
00901     // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
00902     // them.
00903     if ((Section.find("__OBJC,") == 0) ||
00904         (Section.find("__DATA, __objc_") == 0)) {
00905       DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
00906       return false;
00907     }
00908     // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
00909     // Constant CFString instances are compiled in the following way:
00910     //  -- the string buffer is emitted into
00911     //     __TEXT,__cstring,cstring_literals
00912     //  -- the constant NSConstantString structure referencing that buffer
00913     //     is placed into __DATA,__cfstring
00914     // Therefore there's no point in placing redzones into __DATA,__cfstring.
00915     // Moreover, it causes the linker to crash on OS X 10.7
00916     if (Section.find("__DATA,__cfstring") == 0) {
00917       DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
00918       return false;
00919     }
00920     // The linker merges the contents of cstring_literals and removes the
00921     // trailing zeroes.
00922     if (Section.find("__TEXT,__cstring,cstring_literals") == 0) {
00923       DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
00924       return false;
00925     }
00926     // Globals from llvm.metadata aren't emitted, do not instrument them.
00927     if (Section == "llvm.metadata") return false;
00928   }
00929 
00930   return true;
00931 }
00932 
00933 void AddressSanitizerModule::initializeCallbacks(Module &M) {
00934   IRBuilder<> IRB(*C);
00935   // Declare our poisoning and unpoisoning functions.
00936   AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
00937       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
00938   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
00939   AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
00940       kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
00941   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
00942   // Declare functions that register/unregister globals.
00943   AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
00944       kAsanRegisterGlobalsName, IRB.getVoidTy(),
00945       IntptrTy, IntptrTy, NULL));
00946   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
00947   AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
00948       kAsanUnregisterGlobalsName,
00949       IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
00950   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
00951 }
00952 
00953 // This function replaces all global variables with new variables that have
00954 // trailing redzones. It also creates a function that poisons
00955 // redzones and inserts this function into llvm.global_ctors.
00956 bool AddressSanitizerModule::runOnModule(Module &M) {
00957   if (!ClGlobals) return false;
00958 
00959   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
00960   if (!DLP)
00961     return false;
00962   DL = &DLP->getDataLayout();
00963 
00964   BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
00965   if (BL->isIn(M)) return false;
00966   C = &(M.getContext());
00967   int LongSize = DL->getPointerSizeInBits();
00968   IntptrTy = Type::getIntNTy(*C, LongSize);
00969   Mapping = getShadowMapping(M, LongSize);
00970   initializeCallbacks(M);
00971   DynamicallyInitializedGlobals.Init(M);
00972 
00973   SmallVector<GlobalVariable *, 16> GlobalsToChange;
00974 
00975   for (Module::GlobalListType::iterator G = M.global_begin(),
00976        E = M.global_end(); G != E; ++G) {
00977     if (ShouldInstrumentGlobal(G))
00978       GlobalsToChange.push_back(G);
00979   }
00980 
00981   size_t n = GlobalsToChange.size();
00982   if (n == 0) return false;
00983 
00984   // A global is described by a structure
00985   //   size_t beg;
00986   //   size_t size;
00987   //   size_t size_with_redzone;
00988   //   const char *name;
00989   //   const char *module_name;
00990   //   size_t has_dynamic_init;
00991   // We initialize an array of such structures and pass it to a run-time call.
00992   StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
00993                                                IntptrTy, IntptrTy,
00994                                                IntptrTy, IntptrTy, NULL);
00995   SmallVector<Constant *, 16> Initializers(n);
00996 
00997   Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
00998   assert(CtorFunc);
00999   IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
01000 
01001   bool HasDynamicallyInitializedGlobals = false;
01002 
01003   // We shouldn't merge same module names, as this string serves as unique
01004   // module ID in runtime.
01005   GlobalVariable *ModuleName = createPrivateGlobalForString(
01006       M, M.getModuleIdentifier(), /*AllowMerging*/false);
01007 
01008   for (size_t i = 0; i < n; i++) {
01009     static const uint64_t kMaxGlobalRedzone = 1 << 18;
01010     GlobalVariable *G = GlobalsToChange[i];
01011     PointerType *PtrTy = cast<PointerType>(G->getType());
01012     Type *Ty = PtrTy->getElementType();
01013     uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
01014     uint64_t MinRZ = MinRedzoneSizeForGlobal();
01015     // MinRZ <= RZ <= kMaxGlobalRedzone
01016     // and trying to make RZ to be ~ 1/4 of SizeInBytes.
01017     uint64_t RZ = std::max(MinRZ,
01018                          std::min(kMaxGlobalRedzone,
01019                                   (SizeInBytes / MinRZ / 4) * MinRZ));
01020     uint64_t RightRedzoneSize = RZ;
01021     // Round up to MinRZ
01022     if (SizeInBytes % MinRZ)
01023       RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
01024     assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
01025     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
01026     // Determine whether this global should be poisoned in initialization.
01027     bool GlobalHasDynamicInitializer =
01028         DynamicallyInitializedGlobals.Contains(G);
01029     // Don't check initialization order if this global is blacklisted.
01030     GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
01031 
01032     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
01033     Constant *NewInitializer = ConstantStruct::get(
01034         NewTy, G->getInitializer(),
01035         Constant::getNullValue(RightRedZoneTy), NULL);
01036 
01037     GlobalVariable *Name =
01038         createPrivateGlobalForString(M, G->getName(), /*AllowMerging*/true);
01039 
01040     // Create a new global variable with enough space for a redzone.
01041     GlobalValue::LinkageTypes Linkage = G->getLinkage();
01042     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
01043       Linkage = GlobalValue::InternalLinkage;
01044     GlobalVariable *NewGlobal = new GlobalVariable(
01045         M, NewTy, G->isConstant(), Linkage,
01046         NewInitializer, "", G, G->getThreadLocalMode());
01047     NewGlobal->copyAttributesFrom(G);
01048     NewGlobal->setAlignment(MinRZ);
01049 
01050     Value *Indices2[2];
01051     Indices2[0] = IRB.getInt32(0);
01052     Indices2[1] = IRB.getInt32(0);
01053 
01054     G->replaceAllUsesWith(
01055         ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
01056     NewGlobal->takeName(G);
01057     G->eraseFromParent();
01058 
01059     Initializers[i] = ConstantStruct::get(
01060         GlobalStructTy,
01061         ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
01062         ConstantInt::get(IntptrTy, SizeInBytes),
01063         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
01064         ConstantExpr::getPointerCast(Name, IntptrTy),
01065         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
01066         ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
01067         NULL);
01068 
01069     // Populate the first and last globals declared in this TU.
01070     if (CheckInitOrder && GlobalHasDynamicInitializer)
01071       HasDynamicallyInitializedGlobals = true;
01072 
01073     DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
01074   }
01075 
01076   ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
01077   GlobalVariable *AllGlobals = new GlobalVariable(
01078       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
01079       ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
01080 
01081   // Create calls for poisoning before initializers run and unpoisoning after.
01082   if (CheckInitOrder && HasDynamicallyInitializedGlobals)
01083     createInitializerPoisonCalls(M, ModuleName);
01084   IRB.CreateCall2(AsanRegisterGlobals,
01085                   IRB.CreatePointerCast(AllGlobals, IntptrTy),
01086                   ConstantInt::get(IntptrTy, n));
01087 
01088   // We also need to unregister globals at the end, e.g. when a shared library
01089   // gets closed.
01090   Function *AsanDtorFunction = Function::Create(
01091       FunctionType::get(Type::getVoidTy(*C), false),
01092       GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
01093   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
01094   IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
01095   IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
01096                        IRB.CreatePointerCast(AllGlobals, IntptrTy),
01097                        ConstantInt::get(IntptrTy, n));
01098   appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
01099 
01100   DEBUG(dbgs() << M);
01101   return true;
01102 }
01103 
01104 void AddressSanitizer::initializeCallbacks(Module &M) {
01105   IRBuilder<> IRB(*C);
01106   // Create __asan_report* callbacks.
01107   for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
01108     for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
01109          AccessSizeIndex++) {
01110       // IsWrite and TypeSize are encoded in the function name.
01111       std::string FunctionName = std::string(kAsanReportErrorTemplate) +
01112           (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
01113       // If we are merging crash callbacks, they have two parameters.
01114       AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
01115           checkInterfaceFunction(M.getOrInsertFunction(
01116               FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
01117     }
01118   }
01119   AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
01120               kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01121   AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
01122               kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01123 
01124   AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
01125       kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
01126   AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
01127       kAsanCovName, IRB.getVoidTy(), NULL));
01128   AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
01129       kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01130   AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
01131       kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01132   // We insert an empty inline asm after __asan_report* to avoid callback merge.
01133   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
01134                             StringRef(""), StringRef(""),
01135                             /*hasSideEffects=*/true);
01136 }
01137 
01138 // virtual
01139 bool AddressSanitizer::doInitialization(Module &M) {
01140   // Initialize the private fields. No one has accessed them before.
01141   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01142   if (!DLP)
01143     return false;
01144   DL = &DLP->getDataLayout();
01145 
01146   BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
01147   DynamicallyInitializedGlobals.Init(M);
01148 
01149   C = &(M.getContext());
01150   LongSize = DL->getPointerSizeInBits();
01151   IntptrTy = Type::getIntNTy(*C, LongSize);
01152 
01153   AsanCtorFunction = Function::Create(
01154       FunctionType::get(Type::getVoidTy(*C), false),
01155       GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
01156   BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
01157   // call __asan_init in the module ctor.
01158   IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
01159   AsanInitFunction = checkInterfaceFunction(
01160       M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
01161   AsanInitFunction->setLinkage(Function::ExternalLinkage);
01162   IRB.CreateCall(AsanInitFunction);
01163 
01164   Mapping = getShadowMapping(M, LongSize);
01165 
01166   appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
01167   return true;
01168 }
01169 
01170 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
01171   // For each NSObject descendant having a +load method, this method is invoked
01172   // by the ObjC runtime before any of the static constructors is called.
01173   // Therefore we need to instrument such methods with a call to __asan_init
01174   // at the beginning in order to initialize our runtime before any access to
01175   // the shadow memory.
01176   // We cannot just ignore these methods, because they may call other
01177   // instrumented functions.
01178   if (F.getName().find(" load]") != std::string::npos) {
01179     IRBuilder<> IRB(F.begin()->begin());
01180     IRB.CreateCall(AsanInitFunction);
01181     return true;
01182   }
01183   return false;
01184 }
01185 
01186 void AddressSanitizer::InjectCoverageAtBlock(Function &F, BasicBlock &BB) {
01187   BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
01188   // Skip static allocas at the top of the entry block so they don't become
01189   // dynamic when we split the block.  If we used our optimized stack layout,
01190   // then there will only be one alloca and it will come first.
01191   for (; IP != BE; ++IP) {
01192     AllocaInst *AI = dyn_cast<AllocaInst>(IP);
01193     if (!AI || !AI->isStaticAlloca())
01194       break;
01195   }
01196 
01197   IRBuilder<> IRB(IP);
01198   Type *Int8Ty = IRB.getInt8Ty();
01199   GlobalVariable *Guard = new GlobalVariable(
01200       *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
01201       Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
01202   LoadInst *Load = IRB.CreateLoad(Guard);
01203   Load->setAtomic(Monotonic);
01204   Load->setAlignment(1);
01205   Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
01206   Instruction *Ins = SplitBlockAndInsertIfThen(
01207       Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
01208   IRB.SetInsertPoint(Ins);
01209   // We pass &F to __sanitizer_cov. We could avoid this and rely on
01210   // GET_CALLER_PC, but having the PC of the first instruction is just nice.
01211   Instruction *Call = IRB.CreateCall(AsanCovFunction);
01212   Call->setDebugLoc(IP->getDebugLoc());
01213   StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
01214   Store->setAtomic(Monotonic);
01215   Store->setAlignment(1);
01216 }
01217 
01218 // Poor man's coverage that works with ASan.
01219 // We create a Guard boolean variable with the same linkage
01220 // as the function and inject this code into the entry block (-asan-coverage=1)
01221 // or all blocks (-asan-coverage=2):
01222 // if (*Guard) {
01223 //    __sanitizer_cov(&F);
01224 //    *Guard = 1;
01225 // }
01226 // The accesses to Guard are atomic. The rest of the logic is
01227 // in __sanitizer_cov (it's fine to call it more than once).
01228 //
01229 // This coverage implementation provides very limited data:
01230 // it only tells if a given function (block) was ever executed.
01231 // No counters, no per-edge data.
01232 // But for many use cases this is what we need and the added slowdown
01233 // is negligible. This simple implementation will probably be obsoleted
01234 // by the upcoming Clang-based coverage implementation.
01235 // By having it here and now we hope to
01236 //  a) get the functionality to users earlier and
01237 //  b) collect usage statistics to help improve Clang coverage design.
01238 bool AddressSanitizer::InjectCoverage(Function &F,
01239                                       const ArrayRef<BasicBlock *> AllBlocks) {
01240   if (!ClCoverage) return false;
01241 
01242   if (ClCoverage == 1) {
01243     InjectCoverageAtBlock(F, F.getEntryBlock());
01244   } else {
01245     for (size_t i = 0, n = AllBlocks.size(); i < n; i++)
01246       InjectCoverageAtBlock(F, *AllBlocks[i]);
01247   }
01248   return true;
01249 }
01250 
01251 bool AddressSanitizer::runOnFunction(Function &F) {
01252   if (BL->isIn(F)) return false;
01253   if (&F == AsanCtorFunction) return false;
01254   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
01255   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
01256   initializeCallbacks(*F.getParent());
01257 
01258   // If needed, insert __asan_init before checking for SanitizeAddress attr.
01259   maybeInsertAsanInitAtFunctionEntry(F);
01260 
01261   if (!F.hasFnAttribute(Attribute::SanitizeAddress))
01262     return false;
01263 
01264   if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
01265     return false;
01266 
01267   // We want to instrument every address only once per basic block (unless there
01268   // are calls between uses).
01269   SmallSet<Value*, 16> TempsToInstrument;
01270   SmallVector<Instruction*, 16> ToInstrument;
01271   SmallVector<Instruction*, 8> NoReturnCalls;
01272   SmallVector<BasicBlock*, 16> AllBlocks;
01273   SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
01274   int NumAllocas = 0;
01275   bool IsWrite;
01276 
01277   // Fill the set of memory operations to instrument.
01278   for (Function::iterator FI = F.begin(), FE = F.end();
01279        FI != FE; ++FI) {
01280     AllBlocks.push_back(FI);
01281     TempsToInstrument.clear();
01282     int NumInsnsPerBB = 0;
01283     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
01284          BI != BE; ++BI) {
01285       if (LooksLikeCodeInBug11395(BI)) return false;
01286       if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
01287         if (ClOpt && ClOptSameTemp) {
01288           if (!TempsToInstrument.insert(Addr))
01289             continue;  // We've seen this temp in the current BB.
01290         }
01291       } else if (ClInvalidPointerPairs &&
01292                  isInterestingPointerComparisonOrSubtraction(BI)) {
01293         PointerComparisonsOrSubtracts.push_back(BI);
01294         continue;
01295       } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
01296         // ok, take it.
01297       } else {
01298         if (isa<AllocaInst>(BI))
01299           NumAllocas++;
01300         CallSite CS(BI);
01301         if (CS) {
01302           // A call inside BB.
01303           TempsToInstrument.clear();
01304           if (CS.doesNotReturn())
01305             NoReturnCalls.push_back(CS.getInstruction());
01306         }
01307         continue;
01308       }
01309       ToInstrument.push_back(BI);
01310       NumInsnsPerBB++;
01311       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
01312         break;
01313     }
01314   }
01315 
01316   Function *UninstrumentedDuplicate = 0;
01317   bool LikelyToInstrument =
01318       !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
01319   if (ClKeepUninstrumented && LikelyToInstrument) {
01320     ValueToValueMapTy VMap;
01321     UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
01322     UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
01323     UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
01324     F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
01325   }
01326 
01327   // Instrument.
01328   int NumInstrumented = 0;
01329   for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
01330     Instruction *Inst = ToInstrument[i];
01331     if (ClDebugMin < 0 || ClDebugMax < 0 ||
01332         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
01333       if (isInterestingMemoryAccess(Inst, &IsWrite))
01334         instrumentMop(Inst);
01335       else
01336         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
01337     }
01338     NumInstrumented++;
01339   }
01340 
01341   FunctionStackPoisoner FSP(F, *this);
01342   bool ChangedStack = FSP.runOnFunction();
01343 
01344   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
01345   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
01346   for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
01347     Instruction *CI = NoReturnCalls[i];
01348     IRBuilder<> IRB(CI);
01349     IRB.CreateCall(AsanHandleNoReturnFunc);
01350   }
01351 
01352   for (size_t i = 0, n = PointerComparisonsOrSubtracts.size(); i != n; i++) {
01353     instrumentPointerComparisonOrSubtraction(PointerComparisonsOrSubtracts[i]);
01354     NumInstrumented++;
01355   }
01356 
01357   bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
01358 
01359   if (InjectCoverage(F, AllBlocks))
01360     res = true;
01361 
01362   DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
01363 
01364   if (ClKeepUninstrumented) {
01365     if (!res) {
01366       // No instrumentation is done, no need for the duplicate.
01367       if (UninstrumentedDuplicate)
01368         UninstrumentedDuplicate->eraseFromParent();
01369     } else {
01370       // The function was instrumented. We must have the duplicate.
01371       assert(UninstrumentedDuplicate);
01372       UninstrumentedDuplicate->setSection("NOASAN");
01373       assert(!F.hasSection());
01374       F.setSection("ASAN");
01375     }
01376   }
01377 
01378   return res;
01379 }
01380 
01381 // Workaround for bug 11395: we don't want to instrument stack in functions
01382 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
01383 // FIXME: remove once the bug 11395 is fixed.
01384 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
01385   if (LongSize != 32) return false;
01386   CallInst *CI = dyn_cast<CallInst>(I);
01387   if (!CI || !CI->isInlineAsm()) return false;
01388   if (CI->getNumArgOperands() <= 5) return false;
01389   // We have inline assembly with quite a few arguments.
01390   return true;
01391 }
01392 
01393 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
01394   IRBuilder<> IRB(*C);
01395   for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
01396     std::string Suffix = itostr(i);
01397     AsanStackMallocFunc[i] = checkInterfaceFunction(
01398         M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
01399                               IntptrTy, IntptrTy, NULL));
01400     AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
01401         kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
01402         IntptrTy, IntptrTy, NULL));
01403   }
01404   AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
01405       kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01406   AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
01407       kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
01408 }
01409 
01410 void
01411 FunctionStackPoisoner::poisonRedZones(const ArrayRef<uint8_t> ShadowBytes,
01412                                       IRBuilder<> &IRB, Value *ShadowBase,
01413                                       bool DoPoison) {
01414   size_t n = ShadowBytes.size();
01415   size_t i = 0;
01416   // We need to (un)poison n bytes of stack shadow. Poison as many as we can
01417   // using 64-bit stores (if we are on 64-bit arch), then poison the rest
01418   // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
01419   for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
01420        LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
01421     for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
01422       uint64_t Val = 0;
01423       for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
01424         if (ASan.DL->isLittleEndian())
01425           Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
01426         else
01427           Val = (Val << 8) | ShadowBytes[i + j];
01428       }
01429       if (!Val) continue;
01430       Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
01431       Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
01432       Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
01433       IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
01434     }
01435   }
01436 }
01437 
01438 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
01439 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
01440 static int StackMallocSizeClass(uint64_t LocalStackSize) {
01441   assert(LocalStackSize <= kMaxStackMallocSize);
01442   uint64_t MaxSize = kMinStackMallocSize;
01443   for (int i = 0; ; i++, MaxSize *= 2)
01444     if (LocalStackSize <= MaxSize)
01445       return i;
01446   llvm_unreachable("impossible LocalStackSize");
01447 }
01448 
01449 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
01450 // We can not use MemSet intrinsic because it may end up calling the actual
01451 // memset. Size is a multiple of 8.
01452 // Currently this generates 8-byte stores on x86_64; it may be better to
01453 // generate wider stores.
01454 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
01455     IRBuilder<> &IRB, Value *ShadowBase, int Size) {
01456   assert(!(Size % 8));
01457   assert(kAsanStackAfterReturnMagic == 0xf5);
01458   for (int i = 0; i < Size; i += 8) {
01459     Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
01460     IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
01461                     IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
01462   }
01463 }
01464 
01465 void FunctionStackPoisoner::poisonStack() {
01466   int StackMallocIdx = -1;
01467 
01468   assert(AllocaVec.size() > 0);
01469   Instruction *InsBefore = AllocaVec[0];
01470   IRBuilder<> IRB(InsBefore);
01471 
01472   SmallVector<ASanStackVariableDescription, 16> SVD;
01473   SVD.reserve(AllocaVec.size());
01474   for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
01475     AllocaInst *AI = AllocaVec[i];
01476     ASanStackVariableDescription D = { AI->getName().data(),
01477                                    getAllocaSizeInBytes(AI),
01478                                    AI->getAlignment(), AI, 0};
01479     SVD.push_back(D);
01480   }
01481   // Minimal header size (left redzone) is 4 pointers,
01482   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
01483   size_t MinHeaderSize = ASan.LongSize / 2;
01484   ASanStackFrameLayout L;
01485   ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
01486   DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
01487   uint64_t LocalStackSize = L.FrameSize;
01488   bool DoStackMalloc =
01489       ASan.CheckUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
01490 
01491   Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
01492   AllocaInst *MyAlloca =
01493       new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
01494   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
01495   size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
01496   MyAlloca->setAlignment(FrameAlignment);
01497   assert(MyAlloca->isStaticAlloca());
01498   Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
01499   Value *LocalStackBase = OrigStackBase;
01500 
01501   if (DoStackMalloc) {
01502     // LocalStackBase = OrigStackBase
01503     // if (__asan_option_detect_stack_use_after_return)
01504     //   LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
01505     StackMallocIdx = StackMallocSizeClass(LocalStackSize);
01506     assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
01507     Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
01508         kAsanOptionDetectUAR, IRB.getInt32Ty());
01509     Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
01510                                   Constant::getNullValue(IRB.getInt32Ty()));
01511     Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
01512     BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
01513     IRBuilder<> IRBIf(Term);
01514     LocalStackBase = IRBIf.CreateCall2(
01515         AsanStackMallocFunc[StackMallocIdx],
01516         ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
01517     BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
01518     IRB.SetInsertPoint(InsBefore);
01519     PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
01520     Phi->addIncoming(OrigStackBase, CmpBlock);
01521     Phi->addIncoming(LocalStackBase, SetBlock);
01522     LocalStackBase = Phi;
01523   }
01524 
01525   // Insert poison calls for lifetime intrinsics for alloca.
01526   bool HavePoisonedAllocas = false;
01527   for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
01528     const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
01529     assert(APC.InsBefore);
01530     assert(APC.AI);
01531     IRBuilder<> IRB(APC.InsBefore);
01532     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
01533     HavePoisonedAllocas |= APC.DoPoison;
01534   }
01535 
01536   // Replace Alloca instructions with base+offset.
01537   for (size_t i = 0, n = SVD.size(); i < n; i++) {
01538     AllocaInst *AI = SVD[i].AI;
01539     Value *NewAllocaPtr = IRB.CreateIntToPtr(
01540         IRB.CreateAdd(LocalStackBase,
01541                       ConstantInt::get(IntptrTy, SVD[i].Offset)),
01542         AI->getType());
01543     replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
01544     AI->replaceAllUsesWith(NewAllocaPtr);
01545   }
01546 
01547   // The left-most redzone has enough space for at least 4 pointers.
01548   // Write the Magic value to redzone[0].
01549   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
01550   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
01551                   BasePlus0);
01552   // Write the frame description constant to redzone[1].
01553   Value *BasePlus1 = IRB.CreateIntToPtr(
01554     IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
01555     IntptrPtrTy);
01556   GlobalVariable *StackDescriptionGlobal =
01557       createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
01558                                    /*AllowMerging*/true);
01559   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
01560                                              IntptrTy);
01561   IRB.CreateStore(Description, BasePlus1);
01562   // Write the PC to redzone[2].
01563   Value *BasePlus2 = IRB.CreateIntToPtr(
01564     IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
01565                                                    2 * ASan.LongSize/8)),
01566     IntptrPtrTy);
01567   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
01568 
01569   // Poison the stack redzones at the entry.
01570   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
01571   poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
01572 
01573   // (Un)poison the stack before all ret instructions.
01574   for (size_t i = 0, n = RetVec.size(); i < n; i++) {
01575     Instruction *Ret = RetVec[i];
01576     IRBuilder<> IRBRet(Ret);
01577     // Mark the current frame as retired.
01578     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
01579                        BasePlus0);
01580     if (DoStackMalloc) {
01581       assert(StackMallocIdx >= 0);
01582       // if LocalStackBase != OrigStackBase:
01583       //     // In use-after-return mode, poison the whole stack frame.
01584       //     if StackMallocIdx <= 4
01585       //         // For small sizes inline the whole thing:
01586       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
01587       //         **SavedFlagPtr(LocalStackBase) = 0
01588       //     else
01589       //         __asan_stack_free_N(LocalStackBase, OrigStackBase)
01590       // else
01591       //     <This is not a fake stack; unpoison the redzones>
01592       Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
01593       TerminatorInst *ThenTerm, *ElseTerm;
01594       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
01595 
01596       IRBuilder<> IRBPoison(ThenTerm);
01597       if (StackMallocIdx <= 4) {
01598         int ClassSize = kMinStackMallocSize << StackMallocIdx;
01599         SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
01600                                            ClassSize >> Mapping.Scale);
01601         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
01602             LocalStackBase,
01603             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
01604         Value *SavedFlagPtr = IRBPoison.CreateLoad(
01605             IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
01606         IRBPoison.CreateStore(
01607             Constant::getNullValue(IRBPoison.getInt8Ty()),
01608             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
01609       } else {
01610         // For larger frames call __asan_stack_free_*.
01611         IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
01612                               ConstantInt::get(IntptrTy, LocalStackSize),
01613                               OrigStackBase);
01614       }
01615 
01616       IRBuilder<> IRBElse(ElseTerm);
01617       poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
01618     } else if (HavePoisonedAllocas) {
01619       // If we poisoned some allocas in llvm.lifetime analysis,
01620       // unpoison whole stack frame now.
01621       assert(LocalStackBase == OrigStackBase);
01622       poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
01623     } else {
01624       poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
01625     }
01626   }
01627 
01628   // We are done. Remove the old unused alloca instructions.
01629   for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
01630     AllocaVec[i]->eraseFromParent();
01631 }
01632 
01633 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
01634                                          IRBuilder<> &IRB, bool DoPoison) {
01635   // For now just insert the call to ASan runtime.
01636   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
01637   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
01638   IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
01639                            : AsanUnpoisonStackMemoryFunc,
01640                   AddrArg, SizeArg);
01641 }
01642 
01643 // Handling llvm.lifetime intrinsics for a given %alloca:
01644 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
01645 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
01646 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
01647 //     could be poisoned by previous llvm.lifetime.end instruction, as the
01648 //     variable may go in and out of scope several times, e.g. in loops).
01649 // (3) if we poisoned at least one %alloca in a function,
01650 //     unpoison the whole stack frame at function exit.
01651 
01652 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
01653   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
01654     // We're intested only in allocas we can handle.
01655     return isInterestingAlloca(*AI) ? AI : 0;
01656   // See if we've already calculated (or started to calculate) alloca for a
01657   // given value.
01658   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
01659   if (I != AllocaForValue.end())
01660     return I->second;
01661   // Store 0 while we're calculating alloca for value V to avoid
01662   // infinite recursion if the value references itself.
01663   AllocaForValue[V] = 0;
01664   AllocaInst *Res = 0;
01665   if (CastInst *CI = dyn_cast<CastInst>(V))
01666     Res = findAllocaForValue(CI->getOperand(0));
01667   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
01668     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01669       Value *IncValue = PN->getIncomingValue(i);
01670       // Allow self-referencing phi-nodes.
01671       if (IncValue == PN) continue;
01672       AllocaInst *IncValueAI = findAllocaForValue(IncValue);
01673       // AI for incoming values should exist and should all be equal.
01674       if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
01675         return 0;
01676       Res = IncValueAI;
01677     }
01678   }
01679   if (Res != 0)
01680     AllocaForValue[V] = Res;
01681   return Res;
01682 }