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