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