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