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