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