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