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