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