Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1 | //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file is a part of AddressSanitizer, an address sanity checker. |
| 11 | // Details of the algorithm: |
| 12 | // http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm |
| 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
| 16 | #define DEBUG_TYPE "asan" |
| 17 | |
Kostya Serebryany | b5b86d2 | 2012-08-24 16:44:47 +0000 | [diff] [blame] | 18 | #include "BlackList.h" |
Chandler Carruth | 06cb8ed | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 19 | #include "llvm/Function.h" |
| 20 | #include "llvm/IRBuilder.h" |
Kostya Serebryany | f7b0822 | 2012-07-20 09:54:50 +0000 | [diff] [blame] | 21 | #include "llvm/InlineAsm.h" |
Chandler Carruth | 06cb8ed | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 22 | #include "llvm/IntrinsicInst.h" |
| 23 | #include "llvm/LLVMContext.h" |
| 24 | #include "llvm/Module.h" |
| 25 | #include "llvm/Type.h" |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 26 | #include "llvm/ADT/ArrayRef.h" |
| 27 | #include "llvm/ADT/OwningPtr.h" |
| 28 | #include "llvm/ADT/SmallSet.h" |
| 29 | #include "llvm/ADT/SmallString.h" |
| 30 | #include "llvm/ADT/SmallVector.h" |
| 31 | #include "llvm/ADT/StringExtras.h" |
Evgeniy Stepanov | 06fdbaa | 2012-05-23 11:52:12 +0000 | [diff] [blame] | 32 | #include "llvm/ADT/Triple.h" |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 33 | #include "llvm/Support/CommandLine.h" |
| 34 | #include "llvm/Support/DataTypes.h" |
| 35 | #include "llvm/Support/Debug.h" |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 36 | #include "llvm/Support/raw_ostream.h" |
| 37 | #include "llvm/Support/system_error.h" |
Micah Villmow | 3574eca | 2012-10-08 16:38:25 +0000 | [diff] [blame] | 38 | #include "llvm/DataLayout.h" |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 39 | #include "llvm/Target/TargetMachine.h" |
| 40 | #include "llvm/Transforms/Instrumentation.h" |
| 41 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 42 | #include "llvm/Transforms/Utils/ModuleUtils.h" |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 43 | |
| 44 | #include <string> |
| 45 | #include <algorithm> |
| 46 | |
| 47 | using namespace llvm; |
| 48 | |
| 49 | static const uint64_t kDefaultShadowScale = 3; |
| 50 | static const uint64_t kDefaultShadowOffset32 = 1ULL << 29; |
| 51 | static const uint64_t kDefaultShadowOffset64 = 1ULL << 44; |
Evgeniy Stepanov | 06fdbaa | 2012-05-23 11:52:12 +0000 | [diff] [blame] | 52 | static const uint64_t kDefaultShadowOffsetAndroid = 0; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 53 | |
| 54 | static const size_t kMaxStackMallocSize = 1 << 16; // 64K |
| 55 | static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3; |
| 56 | static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E; |
| 57 | |
| 58 | static const char *kAsanModuleCtorName = "asan.module_ctor"; |
Kostya Serebryany | 7bcfc99 | 2011-12-15 21:59:03 +0000 | [diff] [blame] | 59 | static const char *kAsanModuleDtorName = "asan.module_dtor"; |
| 60 | static const int kAsanCtorAndCtorPriority = 1; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 61 | static const char *kAsanReportErrorTemplate = "__asan_report_"; |
| 62 | static const char *kAsanRegisterGlobalsName = "__asan_register_globals"; |
Kostya Serebryany | 7bcfc99 | 2011-12-15 21:59:03 +0000 | [diff] [blame] | 63 | static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals"; |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 64 | static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init"; |
| 65 | static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init"; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 66 | static const char *kAsanInitName = "__asan_init"; |
Kostya Serebryany | 95e3cf4 | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 67 | static const char *kAsanHandleNoReturnName = "__asan_handle_no_return"; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 68 | static const char *kAsanMappingOffsetName = "__asan_mapping_offset"; |
| 69 | static const char *kAsanMappingScaleName = "__asan_mapping_scale"; |
| 70 | static const char *kAsanStackMallocName = "__asan_stack_malloc"; |
| 71 | static const char *kAsanStackFreeName = "__asan_stack_free"; |
| 72 | |
| 73 | static const int kAsanStackLeftRedzoneMagic = 0xf1; |
| 74 | static const int kAsanStackMidRedzoneMagic = 0xf2; |
| 75 | static const int kAsanStackRightRedzoneMagic = 0xf3; |
| 76 | static const int kAsanStackPartialRedzoneMagic = 0xf4; |
| 77 | |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 78 | // Accesses sizes are powers of two: 1, 2, 4, 8, 16. |
| 79 | static const size_t kNumberOfAccessSizes = 5; |
| 80 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 81 | // Command-line flags. |
| 82 | |
| 83 | // This flag may need to be replaced with -f[no-]asan-reads. |
| 84 | static cl::opt<bool> ClInstrumentReads("asan-instrument-reads", |
| 85 | cl::desc("instrument read instructions"), cl::Hidden, cl::init(true)); |
| 86 | static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes", |
| 87 | cl::desc("instrument write instructions"), cl::Hidden, cl::init(true)); |
Kostya Serebryany | e6cf2e0 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 88 | static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics", |
| 89 | cl::desc("instrument atomic instructions (rmw, cmpxchg)"), |
| 90 | cl::Hidden, cl::init(true)); |
Kostya Serebryany | 6e2d506 | 2012-08-15 08:58:58 +0000 | [diff] [blame] | 91 | static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path", |
| 92 | cl::desc("use instrumentation with slow path for all accesses"), |
| 93 | cl::Hidden, cl::init(false)); |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 94 | // This flag limits the number of instructions to be instrumented |
Kostya Serebryany | 324cbb8 | 2012-06-28 09:34:41 +0000 | [diff] [blame] | 95 | // in any given BB. Normally, this should be set to unlimited (INT_MAX), |
| 96 | // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary |
| 97 | // set it to 10000. |
| 98 | static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb", |
| 99 | cl::init(10000), |
| 100 | cl::desc("maximal number of instructions to instrument in any given BB"), |
| 101 | cl::Hidden); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 102 | // This flag may need to be replaced with -f[no]asan-stack. |
| 103 | static cl::opt<bool> ClStack("asan-stack", |
| 104 | cl::desc("Handle stack memory"), cl::Hidden, cl::init(true)); |
| 105 | // This flag may need to be replaced with -f[no]asan-use-after-return. |
| 106 | static cl::opt<bool> ClUseAfterReturn("asan-use-after-return", |
| 107 | cl::desc("Check return-after-free"), cl::Hidden, cl::init(false)); |
| 108 | // This flag may need to be replaced with -f[no]asan-globals. |
| 109 | static cl::opt<bool> ClGlobals("asan-globals", |
| 110 | cl::desc("Handle global objects"), cl::Hidden, cl::init(true)); |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 111 | static cl::opt<bool> ClInitializers("asan-initialization-order", |
| 112 | cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false)); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 113 | static cl::opt<bool> ClMemIntrin("asan-memintrin", |
| 114 | cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true)); |
| 115 | // This flag may need to be replaced with -fasan-blacklist. |
| 116 | static cl::opt<std::string> ClBlackListFile("asan-blacklist", |
| 117 | cl::desc("File containing the list of functions to ignore " |
| 118 | "during instrumentation"), cl::Hidden); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 119 | |
| 120 | // These flags allow to change the shadow mapping. |
| 121 | // The shadow mapping looks like |
| 122 | // Shadow = (Mem >> scale) + (1 << offset_log) |
| 123 | static cl::opt<int> ClMappingScale("asan-mapping-scale", |
| 124 | cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0)); |
| 125 | static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log", |
| 126 | cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1)); |
| 127 | |
| 128 | // Optimization flags. Not user visible, used mostly for testing |
| 129 | // and benchmarking the tool. |
| 130 | static cl::opt<bool> ClOpt("asan-opt", |
| 131 | cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true)); |
| 132 | static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp", |
| 133 | cl::desc("Instrument the same temp just once"), cl::Hidden, |
| 134 | cl::init(true)); |
| 135 | static cl::opt<bool> ClOptGlobals("asan-opt-globals", |
| 136 | cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true)); |
| 137 | |
| 138 | // Debug flags. |
| 139 | static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden, |
| 140 | cl::init(0)); |
| 141 | static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"), |
| 142 | cl::Hidden, cl::init(0)); |
| 143 | static cl::opt<std::string> ClDebugFunc("asan-debug-func", |
| 144 | cl::Hidden, cl::desc("Debug func")); |
| 145 | static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"), |
| 146 | cl::Hidden, cl::init(-1)); |
| 147 | static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"), |
| 148 | cl::Hidden, cl::init(-1)); |
| 149 | |
| 150 | namespace { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 151 | /// AddressSanitizer: instrument the code in module to find memory bugs. |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 152 | struct AddressSanitizer : public FunctionPass { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 153 | AddressSanitizer(); |
Alexander Potapenko | 2587804 | 2012-01-23 11:22:43 +0000 | [diff] [blame] | 154 | virtual const char *getPassName() const; |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 155 | void instrumentMop(Instruction *I); |
| 156 | void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB, |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 157 | Value *Addr, uint32_t TypeSize, bool IsWrite); |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 158 | Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong, |
| 159 | Value *ShadowValue, uint32_t TypeSize); |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 160 | Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr, |
Kostya Serebryany | 2735cf4 | 2012-07-16 17:12:07 +0000 | [diff] [blame] | 161 | bool IsWrite, size_t AccessSizeIndex); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 162 | bool instrumentMemIntrinsic(MemIntrinsic *MI); |
| 163 | void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr, |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 164 | Value *Size, |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 165 | Instruction *InsertBefore, bool IsWrite); |
| 166 | Value *memToShadow(Value *Shadow, IRBuilder<> &IRB); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 167 | bool runOnFunction(Function &F); |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 168 | void createInitializerPoisonCalls(Module &M, |
| 169 | Value *FirstAddr, Value *LastAddr); |
Kostya Serebryany | a1a8a32 | 2012-01-30 23:50:10 +0000 | [diff] [blame] | 170 | bool maybeInsertAsanInitAtFunctionEntry(Function &F); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 171 | bool poisonStackInFunction(Function &F); |
| 172 | virtual bool doInitialization(Module &M); |
| 173 | virtual bool doFinalization(Module &M); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 174 | bool insertGlobalRedzones(Module &M); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 175 | static char ID; // Pass identification, replacement for typeid |
| 176 | |
| 177 | private: |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 178 | uint64_t getAllocaSizeInBytes(AllocaInst *AI) { |
| 179 | Type *Ty = AI->getAllocatedType(); |
Evgeniy Stepanov | d8313be | 2012-03-02 10:41:08 +0000 | [diff] [blame] | 180 | uint64_t SizeInBytes = TD->getTypeAllocSize(Ty); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 181 | return SizeInBytes; |
| 182 | } |
| 183 | uint64_t getAlignedSize(uint64_t SizeInBytes) { |
| 184 | return ((SizeInBytes + RedzoneSize - 1) |
| 185 | / RedzoneSize) * RedzoneSize; |
| 186 | } |
| 187 | uint64_t getAlignedAllocaSize(AllocaInst *AI) { |
| 188 | uint64_t SizeInBytes = getAllocaSizeInBytes(AI); |
| 189 | return getAlignedSize(SizeInBytes); |
| 190 | } |
| 191 | |
Alexander Potapenko | 55cabae | 2012-04-23 10:47:31 +0000 | [diff] [blame] | 192 | Function *checkInterfaceFunction(Constant *FuncOrBitcast); |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 193 | bool ShouldInstrumentGlobal(GlobalVariable *G); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 194 | void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, |
| 195 | Value *ShadowBase, bool DoPoison); |
Kostya Serebryany | 5a3a9c9 | 2011-11-18 01:41:06 +0000 | [diff] [blame] | 196 | bool LooksLikeCodeInBug11395(Instruction *I); |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 197 | void FindDynamicInitializers(Module &M); |
| 198 | bool HasDynamicInitializer(GlobalVariable *G); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 199 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 200 | LLVMContext *C; |
Micah Villmow | 3574eca | 2012-10-08 16:38:25 +0000 | [diff] [blame] | 201 | DataLayout *TD; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 202 | uint64_t MappingOffset; |
| 203 | int MappingScale; |
| 204 | size_t RedzoneSize; |
| 205 | int LongSize; |
| 206 | Type *IntptrTy; |
| 207 | Type *IntptrPtrTy; |
| 208 | Function *AsanCtorFunction; |
| 209 | Function *AsanInitFunction; |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 210 | Function *AsanStackMallocFunc, *AsanStackFreeFunc; |
| 211 | Function *AsanHandleNoReturnFunc; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 212 | Instruction *CtorInsertBefore; |
Kostya Serebryany | b5b86d2 | 2012-08-24 16:44:47 +0000 | [diff] [blame] | 213 | OwningPtr<BlackList> BL; |
Kostya Serebryany | 9db5b5f | 2012-07-16 14:09:42 +0000 | [diff] [blame] | 214 | // This array is indexed by AccessIsWrite and log2(AccessSize). |
| 215 | Function *AsanErrorCallback[2][kNumberOfAccessSizes]; |
Kostya Serebryany | f7b0822 | 2012-07-20 09:54:50 +0000 | [diff] [blame] | 216 | InlineAsm *EmptyAsm; |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 217 | SmallSet<GlobalValue*, 32> DynamicallyInitializedGlobals; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 218 | }; |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 219 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 220 | } // namespace |
| 221 | |
| 222 | char AddressSanitizer::ID = 0; |
| 223 | INITIALIZE_PASS(AddressSanitizer, "asan", |
| 224 | "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", |
| 225 | false, false) |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 226 | AddressSanitizer::AddressSanitizer() : FunctionPass(ID) { } |
| 227 | FunctionPass *llvm::createAddressSanitizerPass() { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 228 | return new AddressSanitizer(); |
| 229 | } |
| 230 | |
Alexander Potapenko | 2587804 | 2012-01-23 11:22:43 +0000 | [diff] [blame] | 231 | const char *AddressSanitizer::getPassName() const { |
| 232 | return "AddressSanitizer"; |
| 233 | } |
| 234 | |
Kostya Serebryany | 2735cf4 | 2012-07-16 17:12:07 +0000 | [diff] [blame] | 235 | static size_t TypeSizeToSizeIndex(uint32_t TypeSize) { |
| 236 | size_t Res = CountTrailingZeros_32(TypeSize / 8); |
| 237 | assert(Res < kNumberOfAccessSizes); |
| 238 | return Res; |
| 239 | } |
| 240 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 241 | // Create a constant for Str so that we can pass it to the run-time lib. |
| 242 | static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) { |
Chris Lattner | 18c7f80 | 2012-02-05 02:29:43 +0000 | [diff] [blame] | 243 | Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 244 | return new GlobalVariable(M, StrConst->getType(), true, |
| 245 | GlobalValue::PrivateLinkage, StrConst, ""); |
| 246 | } |
| 247 | |
| 248 | // Split the basic block and insert an if-then code. |
| 249 | // Before: |
| 250 | // Head |
Kostya Serebryany | 56139bc | 2012-07-02 11:42:29 +0000 | [diff] [blame] | 251 | // Cmp |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 252 | // Tail |
| 253 | // After: |
| 254 | // Head |
| 255 | // if (Cmp) |
Kostya Serebryany | 56139bc | 2012-07-02 11:42:29 +0000 | [diff] [blame] | 256 | // ThenBlock |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 257 | // Tail |
| 258 | // |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 259 | // ThenBlock block is created and its terminator is returned. |
| 260 | // If Unreachable, ThenBlock is terminated with UnreachableInst, otherwise |
| 261 | // it is terminated with BranchInst to Tail. |
| 262 | static TerminatorInst *splitBlockAndInsertIfThen(Value *Cmp, bool Unreachable) { |
Kostya Serebryany | 56139bc | 2012-07-02 11:42:29 +0000 | [diff] [blame] | 263 | Instruction *SplitBefore = cast<Instruction>(Cmp)->getNextNode(); |
Chandler Carruth | c3c8db9 | 2012-07-16 08:58:53 +0000 | [diff] [blame] | 264 | BasicBlock *Head = SplitBefore->getParent(); |
Chandler Carruth | 349f14c | 2012-07-16 10:01:02 +0000 | [diff] [blame] | 265 | BasicBlock *Tail = Head->splitBasicBlock(SplitBefore); |
Chandler Carruth | c3c8db9 | 2012-07-16 08:58:53 +0000 | [diff] [blame] | 266 | TerminatorInst *HeadOldTerm = Head->getTerminator(); |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 267 | LLVMContext &C = Head->getParent()->getParent()->getContext(); |
| 268 | BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); |
| 269 | TerminatorInst *CheckTerm; |
| 270 | if (Unreachable) |
| 271 | CheckTerm = new UnreachableInst(C, ThenBlock); |
| 272 | else |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 273 | CheckTerm = BranchInst::Create(Tail, ThenBlock); |
Chandler Carruth | 349f14c | 2012-07-16 10:01:02 +0000 | [diff] [blame] | 274 | BranchInst *HeadNewTerm = |
| 275 | BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cmp); |
| 276 | ReplaceInstWithInst(HeadOldTerm, HeadNewTerm); |
Chandler Carruth | 349f14c | 2012-07-16 10:01:02 +0000 | [diff] [blame] | 277 | return CheckTerm; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 278 | } |
| 279 | |
| 280 | Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) { |
| 281 | // Shadow >> scale |
| 282 | Shadow = IRB.CreateLShr(Shadow, MappingScale); |
| 283 | if (MappingOffset == 0) |
| 284 | return Shadow; |
| 285 | // (Shadow >> scale) | offset |
| 286 | return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, |
| 287 | MappingOffset)); |
| 288 | } |
| 289 | |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 290 | void AddressSanitizer::instrumentMemIntrinsicParam( |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 291 | Instruction *OrigIns, |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 292 | Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) { |
| 293 | // Check the first byte. |
| 294 | { |
| 295 | IRBuilder<> IRB(InsertBefore); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 296 | instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 297 | } |
| 298 | // Check the last byte. |
| 299 | { |
| 300 | IRBuilder<> IRB(InsertBefore); |
| 301 | Value *SizeMinusOne = IRB.CreateSub( |
| 302 | Size, ConstantInt::get(Size->getType(), 1)); |
| 303 | SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false); |
| 304 | Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy); |
| 305 | Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 306 | instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 307 | } |
| 308 | } |
| 309 | |
| 310 | // Instrument memset/memmove/memcpy |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 311 | bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 312 | Value *Dst = MI->getDest(); |
| 313 | MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI); |
Kostya Serebryany | 2735cf4 | 2012-07-16 17:12:07 +0000 | [diff] [blame] | 314 | Value *Src = MemTran ? MemTran->getSource() : 0; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 315 | Value *Length = MI->getLength(); |
| 316 | |
| 317 | Constant *ConstLength = dyn_cast<Constant>(Length); |
| 318 | Instruction *InsertBefore = MI; |
| 319 | if (ConstLength) { |
| 320 | if (ConstLength->isNullValue()) return false; |
| 321 | } else { |
| 322 | // The size is not a constant so it could be zero -- check at run-time. |
| 323 | IRBuilder<> IRB(InsertBefore); |
| 324 | |
| 325 | Value *Cmp = IRB.CreateICmpNE(Length, |
Kostya Serebryany | 56139bc | 2012-07-02 11:42:29 +0000 | [diff] [blame] | 326 | Constant::getNullValue(Length->getType())); |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 327 | InsertBefore = splitBlockAndInsertIfThen(Cmp, false); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 328 | } |
| 329 | |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 330 | instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 331 | if (Src) |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 332 | instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 333 | return true; |
| 334 | } |
| 335 | |
Kostya Serebryany | e6cf2e0 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 336 | // If I is an interesting memory access, return the PointerOperand |
| 337 | // and set IsWrite. Otherwise return NULL. |
| 338 | static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 339 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
Kostya Serebryany | e6cf2e0 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 340 | if (!ClInstrumentReads) return NULL; |
| 341 | *IsWrite = false; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 342 | return LI->getPointerOperand(); |
| 343 | } |
Kostya Serebryany | e6cf2e0 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 344 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
| 345 | if (!ClInstrumentWrites) return NULL; |
| 346 | *IsWrite = true; |
| 347 | return SI->getPointerOperand(); |
| 348 | } |
| 349 | if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) { |
| 350 | if (!ClInstrumentAtomics) return NULL; |
| 351 | *IsWrite = true; |
| 352 | return RMW->getPointerOperand(); |
| 353 | } |
| 354 | if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) { |
| 355 | if (!ClInstrumentAtomics) return NULL; |
| 356 | *IsWrite = true; |
| 357 | return XCHG->getPointerOperand(); |
| 358 | } |
| 359 | return NULL; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 360 | } |
| 361 | |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 362 | void AddressSanitizer::FindDynamicInitializers(Module& M) { |
| 363 | // Clang generates metadata identifying all dynamically initialized globals. |
| 364 | NamedMDNode *DynamicGlobals = |
| 365 | M.getNamedMetadata("llvm.asan.dynamically_initialized_globals"); |
| 366 | if (!DynamicGlobals) |
| 367 | return; |
| 368 | for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) { |
| 369 | MDNode *MDN = DynamicGlobals->getOperand(i); |
| 370 | assert(MDN->getNumOperands() == 1); |
| 371 | Value *VG = MDN->getOperand(0); |
| 372 | // The optimizer may optimize away a global entirely, in which case we |
| 373 | // cannot instrument access to it. |
| 374 | if (!VG) |
| 375 | continue; |
| 376 | |
| 377 | GlobalVariable *G = cast<GlobalVariable>(VG); |
| 378 | DynamicallyInitializedGlobals.insert(G); |
| 379 | } |
| 380 | } |
| 381 | // Returns true if a global variable is initialized dynamically in this TU. |
| 382 | bool AddressSanitizer::HasDynamicInitializer(GlobalVariable *G) { |
| 383 | return DynamicallyInitializedGlobals.count(G); |
| 384 | } |
| 385 | |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 386 | void AddressSanitizer::instrumentMop(Instruction *I) { |
Axel Naumann | 3780ad8 | 2012-09-17 14:20:57 +0000 | [diff] [blame] | 387 | bool IsWrite = false; |
Kostya Serebryany | e6cf2e0 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 388 | Value *Addr = isInterestingMemoryAccess(I, &IsWrite); |
| 389 | assert(Addr); |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 390 | if (ClOpt && ClOptGlobals) { |
| 391 | if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) { |
| 392 | // If initialization order checking is disabled, a simple access to a |
| 393 | // dynamically initialized global is always valid. |
| 394 | if (!ClInitializers) |
| 395 | return; |
| 396 | // If a global variable does not have dynamic initialization we don't |
| 397 | // have to instrument it. However, if a global has external linkage, we |
| 398 | // assume it has dynamic initialization, as it may have an initializer |
| 399 | // in a different TU. |
| 400 | if (G->getLinkage() != GlobalVariable::ExternalLinkage && |
| 401 | !HasDynamicInitializer(G)) |
| 402 | return; |
| 403 | } |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 404 | } |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 405 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 406 | Type *OrigPtrTy = Addr->getType(); |
| 407 | Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType(); |
| 408 | |
| 409 | assert(OrigTy->isSized()); |
| 410 | uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy); |
| 411 | |
| 412 | if (TypeSize != 8 && TypeSize != 16 && |
| 413 | TypeSize != 32 && TypeSize != 64 && TypeSize != 128) { |
| 414 | // Ignore all unusual sizes. |
| 415 | return; |
| 416 | } |
| 417 | |
| 418 | IRBuilder<> IRB(I); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 419 | instrumentAddress(I, IRB, Addr, TypeSize, IsWrite); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 420 | } |
| 421 | |
Alexander Potapenko | 55cabae | 2012-04-23 10:47:31 +0000 | [diff] [blame] | 422 | // Validate the result of Module::getOrInsertFunction called for an interface |
| 423 | // function of AddressSanitizer. If the instrumented module defines a function |
| 424 | // with the same name, their prototypes must match, otherwise |
| 425 | // getOrInsertFunction returns a bitcast. |
| 426 | Function *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) { |
| 427 | if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast); |
| 428 | FuncOrBitcast->dump(); |
| 429 | report_fatal_error("trying to redefine an AddressSanitizer " |
| 430 | "interface function"); |
| 431 | } |
| 432 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 433 | Instruction *AddressSanitizer::generateCrashCode( |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 434 | Instruction *InsertBefore, Value *Addr, |
Kostya Serebryany | 4f0c696 | 2012-07-17 11:04:12 +0000 | [diff] [blame] | 435 | bool IsWrite, size_t AccessSizeIndex) { |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 436 | IRBuilder<> IRB(InsertBefore); |
| 437 | CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], |
| 438 | Addr); |
Kostya Serebryany | f7b0822 | 2012-07-20 09:54:50 +0000 | [diff] [blame] | 439 | // We don't do Call->setDoesNotReturn() because the BB already has |
| 440 | // UnreachableInst at the end. |
| 441 | // This EmptyAsm is required to avoid callback merge. |
| 442 | IRB.CreateCall(EmptyAsm); |
Kostya Serebryany | 3c7faae | 2012-01-06 18:09:21 +0000 | [diff] [blame] | 443 | return Call; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 444 | } |
| 445 | |
Kostya Serebryany | 2735cf4 | 2012-07-16 17:12:07 +0000 | [diff] [blame] | 446 | Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong, |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 447 | Value *ShadowValue, |
| 448 | uint32_t TypeSize) { |
| 449 | size_t Granularity = 1 << MappingScale; |
| 450 | // Addr & (Granularity - 1) |
| 451 | Value *LastAccessedByte = IRB.CreateAnd( |
| 452 | AddrLong, ConstantInt::get(IntptrTy, Granularity - 1)); |
| 453 | // (Addr & (Granularity - 1)) + size - 1 |
| 454 | if (TypeSize / 8 > 1) |
| 455 | LastAccessedByte = IRB.CreateAdd( |
| 456 | LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)); |
| 457 | // (uint8_t) ((Addr & (Granularity-1)) + size - 1) |
| 458 | LastAccessedByte = IRB.CreateIntCast( |
Kostya Serebryany | 6e2d506 | 2012-08-15 08:58:58 +0000 | [diff] [blame] | 459 | LastAccessedByte, ShadowValue->getType(), false); |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 460 | // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue |
| 461 | return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue); |
| 462 | } |
| 463 | |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 464 | void AddressSanitizer::instrumentAddress(Instruction *OrigIns, |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 465 | IRBuilder<> &IRB, Value *Addr, |
| 466 | uint32_t TypeSize, bool IsWrite) { |
| 467 | Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy); |
| 468 | |
| 469 | Type *ShadowTy = IntegerType::get( |
| 470 | *C, std::max(8U, TypeSize >> MappingScale)); |
| 471 | Type *ShadowPtrTy = PointerType::get(ShadowTy, 0); |
| 472 | Value *ShadowPtr = memToShadow(AddrLong, IRB); |
| 473 | Value *CmpVal = Constant::getNullValue(ShadowTy); |
| 474 | Value *ShadowValue = IRB.CreateLoad( |
| 475 | IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy)); |
| 476 | |
| 477 | Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal); |
Kostya Serebryany | 11c2a47 | 2012-08-13 14:08:46 +0000 | [diff] [blame] | 478 | size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 479 | size_t Granularity = 1 << MappingScale; |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 480 | TerminatorInst *CrashTerm = 0; |
| 481 | |
Kostya Serebryany | 6e2d506 | 2012-08-15 08:58:58 +0000 | [diff] [blame] | 482 | if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) { |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 483 | TerminatorInst *CheckTerm = splitBlockAndInsertIfThen(Cmp, false); |
| 484 | assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional()); |
Kostya Serebryany | f7b0822 | 2012-07-20 09:54:50 +0000 | [diff] [blame] | 485 | BasicBlock *NextBB = CheckTerm->getSuccessor(0); |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 486 | IRB.SetInsertPoint(CheckTerm); |
| 487 | Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 488 | BasicBlock *CrashBlock = |
| 489 | BasicBlock::Create(*C, "", NextBB->getParent(), NextBB); |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 490 | CrashTerm = new UnreachableInst(*C, CrashBlock); |
Kostya Serebryany | f7b0822 | 2012-07-20 09:54:50 +0000 | [diff] [blame] | 491 | BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2); |
| 492 | ReplaceInstWithInst(CheckTerm, NewTerm); |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 493 | } else { |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 494 | CrashTerm = splitBlockAndInsertIfThen(Cmp, true); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 495 | } |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 496 | |
| 497 | Instruction *Crash = |
| 498 | generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex); |
| 499 | Crash->setDebugLoc(OrigIns->getDebugLoc()); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 500 | } |
| 501 | |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 502 | void AddressSanitizer::createInitializerPoisonCalls(Module &M, |
| 503 | Value *FirstAddr, |
| 504 | Value *LastAddr) { |
| 505 | // We do all of our poisoning and unpoisoning within _GLOBAL__I_a. |
| 506 | Function *GlobalInit = M.getFunction("_GLOBAL__I_a"); |
| 507 | // If that function is not present, this TU contains no globals, or they have |
| 508 | // all been optimized away |
| 509 | if (!GlobalInit) |
| 510 | return; |
| 511 | |
| 512 | // Set up the arguments to our poison/unpoison functions. |
| 513 | IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt()); |
| 514 | |
| 515 | // Declare our poisoning and unpoisoning functions. |
| 516 | Function *AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction( |
| 517 | kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL)); |
| 518 | AsanPoisonGlobals->setLinkage(Function::ExternalLinkage); |
| 519 | Function *AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction( |
| 520 | kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL)); |
| 521 | AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage); |
| 522 | |
| 523 | // Add a call to poison all external globals before the given function starts. |
| 524 | IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr); |
| 525 | |
| 526 | // Add calls to unpoison all globals before each return instruction. |
| 527 | for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end(); |
| 528 | I != E; ++I) { |
| 529 | if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) { |
| 530 | CallInst::Create(AsanUnpoisonGlobals, "", RI); |
| 531 | } |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | bool AddressSanitizer::ShouldInstrumentGlobal(GlobalVariable *G) { |
| 536 | Type *Ty = cast<PointerType>(G->getType())->getElementType(); |
Kostya Serebryany | 324d96b | 2012-10-17 13:40:06 +0000 | [diff] [blame] | 537 | DEBUG(dbgs() << "GLOBAL: " << *G << "\n"); |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 538 | |
Kostya Serebryany | 59a4a47 | 2012-09-05 07:29:56 +0000 | [diff] [blame] | 539 | if (BL->isIn(*G)) return false; |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 540 | if (!Ty->isSized()) return false; |
| 541 | if (!G->hasInitializer()) return false; |
| 542 | // Touch only those globals that will not be defined in other modules. |
| 543 | // Don't handle ODR type linkages since other modules may be built w/o asan. |
| 544 | if (G->getLinkage() != GlobalVariable::ExternalLinkage && |
| 545 | G->getLinkage() != GlobalVariable::PrivateLinkage && |
| 546 | G->getLinkage() != GlobalVariable::InternalLinkage) |
| 547 | return false; |
| 548 | // Two problems with thread-locals: |
| 549 | // - The address of the main thread's copy can't be computed at link-time. |
| 550 | // - Need to poison all copies, not just the main thread's one. |
| 551 | if (G->isThreadLocal()) |
| 552 | return false; |
| 553 | // For now, just ignore this Alloca if the alignment is large. |
| 554 | if (G->getAlignment() > RedzoneSize) return false; |
| 555 | |
| 556 | // Ignore all the globals with the names starting with "\01L_OBJC_". |
| 557 | // Many of those are put into the .cstring section. The linker compresses |
| 558 | // that section by removing the spare \0s after the string terminator, so |
| 559 | // our redzones get broken. |
| 560 | if ((G->getName().find("\01L_OBJC_") == 0) || |
| 561 | (G->getName().find("\01l_OBJC_") == 0)) { |
| 562 | DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G); |
| 563 | return false; |
| 564 | } |
| 565 | |
| 566 | if (G->hasSection()) { |
| 567 | StringRef Section(G->getSection()); |
| 568 | // Ignore the globals from the __OBJC section. The ObjC runtime assumes |
| 569 | // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to |
| 570 | // them. |
| 571 | if ((Section.find("__OBJC,") == 0) || |
| 572 | (Section.find("__DATA, __objc_") == 0)) { |
| 573 | DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G); |
| 574 | return false; |
| 575 | } |
| 576 | // See http://code.google.com/p/address-sanitizer/issues/detail?id=32 |
| 577 | // Constant CFString instances are compiled in the following way: |
| 578 | // -- the string buffer is emitted into |
| 579 | // __TEXT,__cstring,cstring_literals |
| 580 | // -- the constant NSConstantString structure referencing that buffer |
| 581 | // is placed into __DATA,__cfstring |
| 582 | // Therefore there's no point in placing redzones into __DATA,__cfstring. |
| 583 | // Moreover, it causes the linker to crash on OS X 10.7 |
| 584 | if (Section.find("__DATA,__cfstring") == 0) { |
| 585 | DEBUG(dbgs() << "Ignoring CFString: " << *G); |
| 586 | return false; |
| 587 | } |
| 588 | } |
| 589 | |
| 590 | return true; |
| 591 | } |
| 592 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 593 | // This function replaces all global variables with new variables that have |
| 594 | // trailing redzones. It also creates a function that poisons |
| 595 | // redzones and inserts this function into llvm.global_ctors. |
| 596 | bool AddressSanitizer::insertGlobalRedzones(Module &M) { |
| 597 | SmallVector<GlobalVariable *, 16> GlobalsToChange; |
| 598 | |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 599 | for (Module::GlobalListType::iterator G = M.global_begin(), |
| 600 | E = M.global_end(); G != E; ++G) { |
| 601 | if (ShouldInstrumentGlobal(G)) |
| 602 | GlobalsToChange.push_back(G); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 603 | } |
| 604 | |
| 605 | size_t n = GlobalsToChange.size(); |
| 606 | if (n == 0) return false; |
| 607 | |
| 608 | // A global is described by a structure |
| 609 | // size_t beg; |
| 610 | // size_t size; |
| 611 | // size_t size_with_redzone; |
| 612 | // const char *name; |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 613 | // size_t has_dynamic_init; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 614 | // We initialize an array of such structures and pass it to a run-time call. |
| 615 | StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy, |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 616 | IntptrTy, IntptrTy, |
| 617 | IntptrTy, NULL); |
| 618 | SmallVector<Constant *, 16> Initializers(n), DynamicInit; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 619 | |
| 620 | IRBuilder<> IRB(CtorInsertBefore); |
| 621 | |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 622 | if (ClInitializers) |
| 623 | FindDynamicInitializers(M); |
| 624 | |
| 625 | // The addresses of the first and last dynamically initialized globals in |
| 626 | // this TU. Used in initialization order checking. |
| 627 | Value *FirstDynamic = 0, *LastDynamic = 0; |
| 628 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 629 | for (size_t i = 0; i < n; i++) { |
| 630 | GlobalVariable *G = GlobalsToChange[i]; |
| 631 | PointerType *PtrTy = cast<PointerType>(G->getType()); |
| 632 | Type *Ty = PtrTy->getElementType(); |
Kostya Serebryany | 208a4ff | 2012-03-21 15:28:50 +0000 | [diff] [blame] | 633 | uint64_t SizeInBytes = TD->getTypeAllocSize(Ty); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 634 | uint64_t RightRedzoneSize = RedzoneSize + |
| 635 | (RedzoneSize - (SizeInBytes % RedzoneSize)); |
| 636 | Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize); |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 637 | // Determine whether this global should be poisoned in initialization. |
| 638 | bool GlobalHasDynamicInitializer = HasDynamicInitializer(G); |
Kostya Serebryany | 59a4a47 | 2012-09-05 07:29:56 +0000 | [diff] [blame] | 639 | // Don't check initialization order if this global is blacklisted. |
Kostya Serebryany | 7dadac6 | 2012-09-05 09:00:18 +0000 | [diff] [blame] | 640 | GlobalHasDynamicInitializer &= !BL->isInInit(*G); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 641 | |
| 642 | StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL); |
| 643 | Constant *NewInitializer = ConstantStruct::get( |
| 644 | NewTy, G->getInitializer(), |
| 645 | Constant::getNullValue(RightRedZoneTy), NULL); |
| 646 | |
Kostya Serebryany | a4b2b1d | 2011-12-15 22:55:55 +0000 | [diff] [blame] | 647 | SmallString<2048> DescriptionOfGlobal = G->getName(); |
| 648 | DescriptionOfGlobal += " ("; |
| 649 | DescriptionOfGlobal += M.getModuleIdentifier(); |
| 650 | DescriptionOfGlobal += ")"; |
| 651 | GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 652 | |
| 653 | // Create a new global variable with enough space for a redzone. |
| 654 | GlobalVariable *NewGlobal = new GlobalVariable( |
| 655 | M, NewTy, G->isConstant(), G->getLinkage(), |
Hans Wennborg | ce718ff | 2012-06-23 11:37:03 +0000 | [diff] [blame] | 656 | NewInitializer, "", G, G->getThreadLocalMode()); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 657 | NewGlobal->copyAttributesFrom(G); |
| 658 | NewGlobal->setAlignment(RedzoneSize); |
| 659 | |
| 660 | Value *Indices2[2]; |
| 661 | Indices2[0] = IRB.getInt32(0); |
| 662 | Indices2[1] = IRB.getInt32(0); |
| 663 | |
| 664 | G->replaceAllUsesWith( |
Kostya Serebryany | f1639ab | 2012-01-28 04:27:16 +0000 | [diff] [blame] | 665 | ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true)); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 666 | NewGlobal->takeName(G); |
| 667 | G->eraseFromParent(); |
| 668 | |
| 669 | Initializers[i] = ConstantStruct::get( |
| 670 | GlobalStructTy, |
| 671 | ConstantExpr::getPointerCast(NewGlobal, IntptrTy), |
| 672 | ConstantInt::get(IntptrTy, SizeInBytes), |
| 673 | ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize), |
| 674 | ConstantExpr::getPointerCast(Name, IntptrTy), |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 675 | ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer), |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 676 | NULL); |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 677 | |
| 678 | // Populate the first and last globals declared in this TU. |
| 679 | if (ClInitializers && GlobalHasDynamicInitializer) { |
| 680 | LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy); |
| 681 | if (FirstDynamic == 0) |
| 682 | FirstDynamic = LastDynamic; |
| 683 | } |
| 684 | |
Kostya Serebryany | 324d96b | 2012-10-17 13:40:06 +0000 | [diff] [blame] | 685 | DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n"); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 686 | } |
| 687 | |
| 688 | ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n); |
| 689 | GlobalVariable *AllGlobals = new GlobalVariable( |
| 690 | M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage, |
| 691 | ConstantArray::get(ArrayOfGlobalStructTy, Initializers), ""); |
| 692 | |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 693 | // Create calls for poisoning before initializers run and unpoisoning after. |
| 694 | if (ClInitializers && FirstDynamic && LastDynamic) |
| 695 | createInitializerPoisonCalls(M, FirstDynamic, LastDynamic); |
| 696 | |
Alexander Potapenko | 55cabae | 2012-04-23 10:47:31 +0000 | [diff] [blame] | 697 | Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction( |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 698 | kAsanRegisterGlobalsName, IRB.getVoidTy(), |
| 699 | IntptrTy, IntptrTy, NULL)); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 700 | AsanRegisterGlobals->setLinkage(Function::ExternalLinkage); |
| 701 | |
| 702 | IRB.CreateCall2(AsanRegisterGlobals, |
| 703 | IRB.CreatePointerCast(AllGlobals, IntptrTy), |
| 704 | ConstantInt::get(IntptrTy, n)); |
| 705 | |
Kostya Serebryany | 7bcfc99 | 2011-12-15 21:59:03 +0000 | [diff] [blame] | 706 | // We also need to unregister globals at the end, e.g. when a shared library |
| 707 | // gets closed. |
| 708 | Function *AsanDtorFunction = Function::Create( |
| 709 | FunctionType::get(Type::getVoidTy(*C), false), |
| 710 | GlobalValue::InternalLinkage, kAsanModuleDtorName, &M); |
| 711 | BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction); |
| 712 | IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB)); |
Alexander Potapenko | 55cabae | 2012-04-23 10:47:31 +0000 | [diff] [blame] | 713 | Function *AsanUnregisterGlobals = |
| 714 | checkInterfaceFunction(M.getOrInsertFunction( |
| 715 | kAsanUnregisterGlobalsName, |
| 716 | IRB.getVoidTy(), IntptrTy, IntptrTy, NULL)); |
Kostya Serebryany | 7bcfc99 | 2011-12-15 21:59:03 +0000 | [diff] [blame] | 717 | AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage); |
| 718 | |
| 719 | IRB_Dtor.CreateCall2(AsanUnregisterGlobals, |
| 720 | IRB.CreatePointerCast(AllGlobals, IntptrTy), |
| 721 | ConstantInt::get(IntptrTy, n)); |
| 722 | appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority); |
| 723 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 724 | DEBUG(dbgs() << M); |
| 725 | return true; |
| 726 | } |
| 727 | |
| 728 | // virtual |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 729 | bool AddressSanitizer::doInitialization(Module &M) { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 730 | // Initialize the private fields. No one has accessed them before. |
Micah Villmow | 3574eca | 2012-10-08 16:38:25 +0000 | [diff] [blame] | 731 | TD = getAnalysisIfAvailable<DataLayout>(); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 732 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 733 | if (!TD) |
| 734 | return false; |
Kostya Serebryany | b5b86d2 | 2012-08-24 16:44:47 +0000 | [diff] [blame] | 735 | BL.reset(new BlackList(ClBlackListFile)); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 736 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 737 | C = &(M.getContext()); |
Micah Villmow | 2c39b15 | 2012-10-15 16:24:29 +0000 | [diff] [blame] | 738 | LongSize = TD->getPointerSizeInBits(0); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 739 | IntptrTy = Type::getIntNTy(*C, LongSize); |
| 740 | IntptrPtrTy = PointerType::get(IntptrTy, 0); |
| 741 | |
| 742 | AsanCtorFunction = Function::Create( |
| 743 | FunctionType::get(Type::getVoidTy(*C), false), |
| 744 | GlobalValue::InternalLinkage, kAsanModuleCtorName, &M); |
| 745 | BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction); |
| 746 | CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB); |
| 747 | |
| 748 | // call __asan_init in the module ctor. |
| 749 | IRBuilder<> IRB(CtorInsertBefore); |
Alexander Potapenko | 55cabae | 2012-04-23 10:47:31 +0000 | [diff] [blame] | 750 | AsanInitFunction = checkInterfaceFunction( |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 751 | M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL)); |
| 752 | AsanInitFunction->setLinkage(Function::ExternalLinkage); |
| 753 | IRB.CreateCall(AsanInitFunction); |
| 754 | |
Kostya Serebryany | 9db5b5f | 2012-07-16 14:09:42 +0000 | [diff] [blame] | 755 | // Create __asan_report* callbacks. |
| 756 | for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) { |
| 757 | for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes; |
| 758 | AccessSizeIndex++) { |
| 759 | // IsWrite and TypeSize are encoded in the function name. |
| 760 | std::string FunctionName = std::string(kAsanReportErrorTemplate) + |
| 761 | (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex); |
Kostya Serebryany | 4f0c696 | 2012-07-17 11:04:12 +0000 | [diff] [blame] | 762 | // If we are merging crash callbacks, they have two parameters. |
Kostya Serebryany | 11c2a47 | 2012-08-13 14:08:46 +0000 | [diff] [blame] | 763 | AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>( |
Kostya Serebryany | 4f0c696 | 2012-07-17 11:04:12 +0000 | [diff] [blame] | 764 | M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy, NULL)); |
Kostya Serebryany | 9db5b5f | 2012-07-16 14:09:42 +0000 | [diff] [blame] | 765 | } |
| 766 | } |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 767 | |
| 768 | AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction( |
| 769 | kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL)); |
| 770 | AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction( |
| 771 | kAsanStackFreeName, IRB.getVoidTy(), |
| 772 | IntptrTy, IntptrTy, IntptrTy, NULL)); |
| 773 | AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction( |
| 774 | kAsanHandleNoReturnName, IRB.getVoidTy(), NULL)); |
| 775 | |
Kostya Serebryany | f7b0822 | 2012-07-20 09:54:50 +0000 | [diff] [blame] | 776 | // We insert an empty inline asm after __asan_report* to avoid callback merge. |
| 777 | EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false), |
| 778 | StringRef(""), StringRef(""), |
| 779 | /*hasSideEffects=*/true); |
Kostya Serebryany | 9db5b5f | 2012-07-16 14:09:42 +0000 | [diff] [blame] | 780 | |
Evgeniy Stepanov | 06fdbaa | 2012-05-23 11:52:12 +0000 | [diff] [blame] | 781 | llvm::Triple targetTriple(M.getTargetTriple()); |
Logan Chien | 43bf709 | 2012-09-02 09:29:46 +0000 | [diff] [blame] | 782 | bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android; |
Evgeniy Stepanov | 06fdbaa | 2012-05-23 11:52:12 +0000 | [diff] [blame] | 783 | |
| 784 | MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid : |
| 785 | (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 786 | if (ClMappingOffsetLog >= 0) { |
| 787 | if (ClMappingOffsetLog == 0) { |
| 788 | // special case |
| 789 | MappingOffset = 0; |
| 790 | } else { |
| 791 | MappingOffset = 1ULL << ClMappingOffsetLog; |
| 792 | } |
| 793 | } |
| 794 | MappingScale = kDefaultShadowScale; |
| 795 | if (ClMappingScale) { |
| 796 | MappingScale = ClMappingScale; |
| 797 | } |
| 798 | // Redzone used for stack and globals is at least 32 bytes. |
| 799 | // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively. |
| 800 | RedzoneSize = std::max(32, (int)(1 << MappingScale)); |
| 801 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 802 | |
Kostya Serebryany | 8c0134a | 2012-03-19 16:40:35 +0000 | [diff] [blame] | 803 | if (ClMappingOffsetLog >= 0) { |
| 804 | // Tell the run-time the current values of mapping offset and scale. |
| 805 | GlobalValue *asan_mapping_offset = |
| 806 | new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage, |
| 807 | ConstantInt::get(IntptrTy, MappingOffset), |
| 808 | kAsanMappingOffsetName); |
| 809 | // Read the global, otherwise it may be optimized away. |
| 810 | IRB.CreateLoad(asan_mapping_offset, true); |
| 811 | } |
| 812 | if (ClMappingScale) { |
| 813 | GlobalValue *asan_mapping_scale = |
| 814 | new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage, |
| 815 | ConstantInt::get(IntptrTy, MappingScale), |
| 816 | kAsanMappingScaleName); |
| 817 | // Read the global, otherwise it may be optimized away. |
| 818 | IRB.CreateLoad(asan_mapping_scale, true); |
| 819 | } |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 820 | |
Kostya Serebryany | 7bcfc99 | 2011-12-15 21:59:03 +0000 | [diff] [blame] | 821 | appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority); |
Kostya Serebryany | 9b02741 | 2011-12-12 18:01:46 +0000 | [diff] [blame] | 822 | |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 823 | return true; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 824 | } |
| 825 | |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 826 | bool AddressSanitizer::doFinalization(Module &M) { |
| 827 | // We transform the globals at the very end so that the optimization analysis |
| 828 | // works on the original globals. |
| 829 | if (ClGlobals) |
| 830 | return insertGlobalRedzones(M); |
| 831 | return false; |
| 832 | } |
| 833 | |
| 834 | |
Kostya Serebryany | a1a8a32 | 2012-01-30 23:50:10 +0000 | [diff] [blame] | 835 | bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) { |
| 836 | // For each NSObject descendant having a +load method, this method is invoked |
| 837 | // by the ObjC runtime before any of the static constructors is called. |
| 838 | // Therefore we need to instrument such methods with a call to __asan_init |
| 839 | // at the beginning in order to initialize our runtime before any access to |
| 840 | // the shadow memory. |
| 841 | // We cannot just ignore these methods, because they may call other |
| 842 | // instrumented functions. |
| 843 | if (F.getName().find(" load]") != std::string::npos) { |
| 844 | IRBuilder<> IRB(F.begin()->begin()); |
| 845 | IRB.CreateCall(AsanInitFunction); |
| 846 | return true; |
| 847 | } |
| 848 | return false; |
| 849 | } |
| 850 | |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 851 | bool AddressSanitizer::runOnFunction(Function &F) { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 852 | if (BL->isIn(F)) return false; |
| 853 | if (&F == AsanCtorFunction) return false; |
Kostya Serebryany | 324d96b | 2012-10-17 13:40:06 +0000 | [diff] [blame] | 854 | DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n"); |
Kostya Serebryany | a1a8a32 | 2012-01-30 23:50:10 +0000 | [diff] [blame] | 855 | |
| 856 | // If needed, insert __asan_init before checking for AddressSafety attr. |
| 857 | maybeInsertAsanInitAtFunctionEntry(F); |
| 858 | |
Bill Wendling | 6765834 | 2012-10-09 07:45:08 +0000 | [diff] [blame] | 859 | if (!F.getFnAttributes().hasAttribute(Attributes::AddressSafety)) |
| 860 | return false; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 861 | |
| 862 | if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) |
| 863 | return false; |
Bill Wendling | 6765834 | 2012-10-09 07:45:08 +0000 | [diff] [blame] | 864 | |
| 865 | // We want to instrument every address only once per basic block (unless there |
| 866 | // are calls between uses). |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 867 | SmallSet<Value*, 16> TempsToInstrument; |
| 868 | SmallVector<Instruction*, 16> ToInstrument; |
Kostya Serebryany | 95e3cf4 | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 869 | SmallVector<Instruction*, 8> NoReturnCalls; |
Kostya Serebryany | e6cf2e0 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 870 | bool IsWrite; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 871 | |
| 872 | // Fill the set of memory operations to instrument. |
| 873 | for (Function::iterator FI = F.begin(), FE = F.end(); |
| 874 | FI != FE; ++FI) { |
| 875 | TempsToInstrument.clear(); |
Kostya Serebryany | 324cbb8 | 2012-06-28 09:34:41 +0000 | [diff] [blame] | 876 | int NumInsnsPerBB = 0; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 877 | for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); |
| 878 | BI != BE; ++BI) { |
Kostya Serebryany | bcb55ce | 2012-01-11 18:15:23 +0000 | [diff] [blame] | 879 | if (LooksLikeCodeInBug11395(BI)) return false; |
Kostya Serebryany | e6cf2e0 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 880 | if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 881 | if (ClOpt && ClOptSameTemp) { |
| 882 | if (!TempsToInstrument.insert(Addr)) |
| 883 | continue; // We've seen this temp in the current BB. |
| 884 | } |
| 885 | } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) { |
| 886 | // ok, take it. |
| 887 | } else { |
Kostya Serebryany | 95e3cf4 | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 888 | if (CallInst *CI = dyn_cast<CallInst>(BI)) { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 889 | // A call inside BB. |
| 890 | TempsToInstrument.clear(); |
Kostya Serebryany | 95e3cf4 | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 891 | if (CI->doesNotReturn()) { |
| 892 | NoReturnCalls.push_back(CI); |
| 893 | } |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 894 | } |
| 895 | continue; |
| 896 | } |
| 897 | ToInstrument.push_back(BI); |
Kostya Serebryany | 324cbb8 | 2012-06-28 09:34:41 +0000 | [diff] [blame] | 898 | NumInsnsPerBB++; |
| 899 | if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) |
| 900 | break; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 901 | } |
| 902 | } |
| 903 | |
| 904 | // Instrument. |
| 905 | int NumInstrumented = 0; |
| 906 | for (size_t i = 0, n = ToInstrument.size(); i != n; i++) { |
| 907 | Instruction *Inst = ToInstrument[i]; |
| 908 | if (ClDebugMin < 0 || ClDebugMax < 0 || |
| 909 | (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) { |
Kostya Serebryany | e6cf2e0 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 910 | if (isInterestingMemoryAccess(Inst, &IsWrite)) |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 911 | instrumentMop(Inst); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 912 | else |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 913 | instrumentMemIntrinsic(cast<MemIntrinsic>(Inst)); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 914 | } |
| 915 | NumInstrumented++; |
| 916 | } |
| 917 | |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 918 | bool ChangedStack = poisonStackInFunction(F); |
Kostya Serebryany | 95e3cf4 | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 919 | |
| 920 | // We must unpoison the stack before every NoReturn call (throw, _exit, etc). |
| 921 | // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37 |
| 922 | for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) { |
| 923 | Instruction *CI = NoReturnCalls[i]; |
| 924 | IRBuilder<> IRB(CI); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 925 | IRB.CreateCall(AsanHandleNoReturnFunc); |
Kostya Serebryany | 95e3cf4 | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 926 | } |
Kostya Serebryany | 324d96b | 2012-10-17 13:40:06 +0000 | [diff] [blame] | 927 | DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n"); |
Kostya Serebryany | 95e3cf4 | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 928 | |
| 929 | return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty(); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 930 | } |
| 931 | |
| 932 | static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) { |
| 933 | if (ShadowRedzoneSize == 1) return PoisonByte; |
| 934 | if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte; |
| 935 | if (ShadowRedzoneSize == 4) |
| 936 | return (PoisonByte << 24) + (PoisonByte << 16) + |
| 937 | (PoisonByte << 8) + (PoisonByte); |
Craig Topper | 8581438 | 2012-02-07 05:05:23 +0000 | [diff] [blame] | 938 | llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4"); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 939 | } |
| 940 | |
| 941 | static void PoisonShadowPartialRightRedzone(uint8_t *Shadow, |
| 942 | size_t Size, |
| 943 | size_t RedzoneSize, |
| 944 | size_t ShadowGranularity, |
| 945 | uint8_t Magic) { |
| 946 | for (size_t i = 0; i < RedzoneSize; |
| 947 | i+= ShadowGranularity, Shadow++) { |
| 948 | if (i + ShadowGranularity <= Size) { |
| 949 | *Shadow = 0; // fully addressable |
| 950 | } else if (i >= Size) { |
| 951 | *Shadow = Magic; // unaddressable |
| 952 | } else { |
| 953 | *Shadow = Size - i; // first Size-i bytes are addressable |
| 954 | } |
| 955 | } |
| 956 | } |
| 957 | |
| 958 | void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, |
| 959 | IRBuilder<> IRB, |
| 960 | Value *ShadowBase, bool DoPoison) { |
| 961 | size_t ShadowRZSize = RedzoneSize >> MappingScale; |
| 962 | assert(ShadowRZSize >= 1 && ShadowRZSize <= 4); |
| 963 | Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8); |
| 964 | Type *RZPtrTy = PointerType::get(RZTy, 0); |
| 965 | |
| 966 | Value *PoisonLeft = ConstantInt::get(RZTy, |
| 967 | ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize)); |
| 968 | Value *PoisonMid = ConstantInt::get(RZTy, |
| 969 | ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize)); |
| 970 | Value *PoisonRight = ConstantInt::get(RZTy, |
| 971 | ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize)); |
| 972 | |
| 973 | // poison the first red zone. |
| 974 | IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy)); |
| 975 | |
| 976 | // poison all other red zones. |
| 977 | uint64_t Pos = RedzoneSize; |
| 978 | for (size_t i = 0, n = AllocaVec.size(); i < n; i++) { |
| 979 | AllocaInst *AI = AllocaVec[i]; |
| 980 | uint64_t SizeInBytes = getAllocaSizeInBytes(AI); |
| 981 | uint64_t AlignedSize = getAlignedAllocaSize(AI); |
| 982 | assert(AlignedSize - SizeInBytes < RedzoneSize); |
| 983 | Value *Ptr = NULL; |
| 984 | |
| 985 | Pos += AlignedSize; |
| 986 | |
| 987 | assert(ShadowBase->getType() == IntptrTy); |
| 988 | if (SizeInBytes < AlignedSize) { |
| 989 | // Poison the partial redzone at right |
| 990 | Ptr = IRB.CreateAdd( |
| 991 | ShadowBase, ConstantInt::get(IntptrTy, |
| 992 | (Pos >> MappingScale) - ShadowRZSize)); |
| 993 | size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes); |
| 994 | uint32_t Poison = 0; |
| 995 | if (DoPoison) { |
| 996 | PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes, |
| 997 | RedzoneSize, |
| 998 | 1ULL << MappingScale, |
| 999 | kAsanStackPartialRedzoneMagic); |
| 1000 | } |
| 1001 | Value *PartialPoison = ConstantInt::get(RZTy, Poison); |
| 1002 | IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy)); |
| 1003 | } |
| 1004 | |
| 1005 | // Poison the full redzone at right. |
| 1006 | Ptr = IRB.CreateAdd(ShadowBase, |
| 1007 | ConstantInt::get(IntptrTy, Pos >> MappingScale)); |
| 1008 | Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid; |
| 1009 | IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy)); |
| 1010 | |
| 1011 | Pos += RedzoneSize; |
| 1012 | } |
| 1013 | } |
| 1014 | |
Kostya Serebryany | 5a3a9c9 | 2011-11-18 01:41:06 +0000 | [diff] [blame] | 1015 | // Workaround for bug 11395: we don't want to instrument stack in functions |
| 1016 | // with large assembly blobs (32-bit only), otherwise reg alloc may crash. |
Kostya Serebryany | d2703de | 2011-11-23 02:10:54 +0000 | [diff] [blame] | 1017 | // FIXME: remove once the bug 11395 is fixed. |
Kostya Serebryany | 5a3a9c9 | 2011-11-18 01:41:06 +0000 | [diff] [blame] | 1018 | bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) { |
| 1019 | if (LongSize != 32) return false; |
| 1020 | CallInst *CI = dyn_cast<CallInst>(I); |
| 1021 | if (!CI || !CI->isInlineAsm()) return false; |
| 1022 | if (CI->getNumArgOperands() <= 5) return false; |
| 1023 | // We have inline assembly with quite a few arguments. |
| 1024 | return true; |
| 1025 | } |
| 1026 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1027 | // Find all static Alloca instructions and put |
| 1028 | // poisoned red zones around all of them. |
| 1029 | // Then unpoison everything back before the function returns. |
| 1030 | // |
| 1031 | // Stack poisoning does not play well with exception handling. |
| 1032 | // When an exception is thrown, we essentially bypass the code |
| 1033 | // that unpoisones the stack. This is why the run-time library has |
| 1034 | // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire |
| 1035 | // stack in the interceptor. This however does not work inside the |
| 1036 | // actual function which catches the exception. Most likely because the |
| 1037 | // compiler hoists the load of the shadow value somewhere too high. |
| 1038 | // This causes asan to report a non-existing bug on 453.povray. |
| 1039 | // It sounds like an LLVM bug. |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 1040 | bool AddressSanitizer::poisonStackInFunction(Function &F) { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1041 | if (!ClStack) return false; |
| 1042 | SmallVector<AllocaInst*, 16> AllocaVec; |
| 1043 | SmallVector<Instruction*, 8> RetVec; |
| 1044 | uint64_t TotalSize = 0; |
| 1045 | |
| 1046 | // Filter out Alloca instructions we want (and can) handle. |
| 1047 | // Collect Ret instructions. |
| 1048 | for (Function::iterator FI = F.begin(), FE = F.end(); |
| 1049 | FI != FE; ++FI) { |
| 1050 | BasicBlock &BB = *FI; |
| 1051 | for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); |
| 1052 | BI != BE; ++BI) { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1053 | if (isa<ReturnInst>(BI)) { |
| 1054 | RetVec.push_back(BI); |
| 1055 | continue; |
| 1056 | } |
| 1057 | |
| 1058 | AllocaInst *AI = dyn_cast<AllocaInst>(BI); |
| 1059 | if (!AI) continue; |
| 1060 | if (AI->isArrayAllocation()) continue; |
| 1061 | if (!AI->isStaticAlloca()) continue; |
| 1062 | if (!AI->getAllocatedType()->isSized()) continue; |
| 1063 | if (AI->getAlignment() > RedzoneSize) continue; |
| 1064 | AllocaVec.push_back(AI); |
| 1065 | uint64_t AlignedSize = getAlignedAllocaSize(AI); |
| 1066 | TotalSize += AlignedSize; |
| 1067 | } |
| 1068 | } |
| 1069 | |
| 1070 | if (AllocaVec.empty()) return false; |
| 1071 | |
| 1072 | uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize; |
| 1073 | |
| 1074 | bool DoStackMalloc = ClUseAfterReturn |
| 1075 | && LocalStackSize <= kMaxStackMallocSize; |
| 1076 | |
| 1077 | Instruction *InsBefore = AllocaVec[0]; |
| 1078 | IRBuilder<> IRB(InsBefore); |
| 1079 | |
| 1080 | |
| 1081 | Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize); |
| 1082 | AllocaInst *MyAlloca = |
| 1083 | new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore); |
| 1084 | MyAlloca->setAlignment(RedzoneSize); |
| 1085 | assert(MyAlloca->isStaticAlloca()); |
| 1086 | Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy); |
| 1087 | Value *LocalStackBase = OrigStackBase; |
| 1088 | |
| 1089 | if (DoStackMalloc) { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1090 | LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc, |
| 1091 | ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase); |
| 1092 | } |
| 1093 | |
| 1094 | // This string will be parsed by the run-time (DescribeStackAddress). |
| 1095 | SmallString<2048> StackDescriptionStorage; |
| 1096 | raw_svector_ostream StackDescription(StackDescriptionStorage); |
| 1097 | StackDescription << F.getName() << " " << AllocaVec.size() << " "; |
| 1098 | |
| 1099 | uint64_t Pos = RedzoneSize; |
| 1100 | // Replace Alloca instructions with base+offset. |
| 1101 | for (size_t i = 0, n = AllocaVec.size(); i < n; i++) { |
| 1102 | AllocaInst *AI = AllocaVec[i]; |
| 1103 | uint64_t SizeInBytes = getAllocaSizeInBytes(AI); |
| 1104 | StringRef Name = AI->getName(); |
| 1105 | StackDescription << Pos << " " << SizeInBytes << " " |
| 1106 | << Name.size() << " " << Name << " "; |
| 1107 | uint64_t AlignedSize = getAlignedAllocaSize(AI); |
| 1108 | assert((AlignedSize % RedzoneSize) == 0); |
| 1109 | AI->replaceAllUsesWith( |
| 1110 | IRB.CreateIntToPtr( |
| 1111 | IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)), |
| 1112 | AI->getType())); |
| 1113 | Pos += AlignedSize + RedzoneSize; |
| 1114 | } |
| 1115 | assert(Pos == LocalStackSize); |
| 1116 | |
| 1117 | // Write the Magic value and the frame description constant to the redzone. |
| 1118 | Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy); |
| 1119 | IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic), |
| 1120 | BasePlus0); |
| 1121 | Value *BasePlus1 = IRB.CreateAdd(LocalStackBase, |
| 1122 | ConstantInt::get(IntptrTy, LongSize/8)); |
| 1123 | BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy); |
| 1124 | Value *Description = IRB.CreatePointerCast( |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 1125 | createPrivateGlobalForString(*F.getParent(), StackDescription.str()), |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1126 | IntptrTy); |
| 1127 | IRB.CreateStore(Description, BasePlus1); |
| 1128 | |
| 1129 | // Poison the stack redzones at the entry. |
| 1130 | Value *ShadowBase = memToShadow(LocalStackBase, IRB); |
| 1131 | PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true); |
| 1132 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1133 | // Unpoison the stack before all ret instructions. |
| 1134 | for (size_t i = 0, n = RetVec.size(); i < n; i++) { |
| 1135 | Instruction *Ret = RetVec[i]; |
| 1136 | IRBuilder<> IRBRet(Ret); |
| 1137 | |
| 1138 | // Mark the current frame as retired. |
| 1139 | IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic), |
| 1140 | BasePlus0); |
| 1141 | // Unpoison the stack. |
| 1142 | PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false); |
| 1143 | |
| 1144 | if (DoStackMalloc) { |
| 1145 | IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase, |
| 1146 | ConstantInt::get(IntptrTy, LocalStackSize), |
| 1147 | OrigStackBase); |
| 1148 | } |
| 1149 | } |
| 1150 | |
Kostya Serebryany | bd0052a | 2012-10-19 06:20:53 +0000 | [diff] [blame^] | 1151 | // We are done. Remove the old unused alloca instructions. |
| 1152 | for (size_t i = 0, n = AllocaVec.size(); i < n; i++) |
| 1153 | AllocaVec[i]->eraseFromParent(); |
| 1154 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1155 | if (ClDebugStack) { |
| 1156 | DEBUG(dbgs() << F); |
| 1157 | } |
| 1158 | |
| 1159 | return true; |
| 1160 | } |