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