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