Kostya Serebryany | 6e6b03e | 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 | |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 16 | #include "llvm/Transforms/Instrumentation.h" |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/ArrayRef.h" |
Alexey Samsonov | 29dd7f2 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 18 | #include "llvm/ADT/DenseMap.h" |
Alexey Samsonov | 4f319cc | 2014-07-02 16:54:41 +0000 | [diff] [blame] | 19 | #include "llvm/ADT/DenseSet.h" |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 20 | #include "llvm/ADT/DepthFirstIterator.h" |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 21 | #include "llvm/ADT/SmallSet.h" |
| 22 | #include "llvm/ADT/SmallString.h" |
| 23 | #include "llvm/ADT/SmallVector.h" |
Kostya Serebryany | d3d23be | 2013-10-16 14:06:14 +0000 | [diff] [blame] | 24 | #include "llvm/ADT/Statistic.h" |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 25 | #include "llvm/ADT/StringExtras.h" |
Evgeniy Stepanov | 617232f | 2012-05-23 11:52:12 +0000 | [diff] [blame] | 26 | #include "llvm/ADT/Triple.h" |
Chandler Carruth | 219b89b | 2014-03-04 11:01:28 +0000 | [diff] [blame] | 27 | #include "llvm/IR/CallSite.h" |
Chandler Carruth | 12664a0 | 2014-03-06 00:22:06 +0000 | [diff] [blame] | 28 | #include "llvm/IR/DIBuilder.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 29 | #include "llvm/IR/DataLayout.h" |
Yury Gribov | 3ae427d | 2014-12-01 08:47:58 +0000 | [diff] [blame] | 30 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 31 | #include "llvm/IR/Function.h" |
| 32 | #include "llvm/IR/IRBuilder.h" |
| 33 | #include "llvm/IR/InlineAsm.h" |
Chandler Carruth | 7da14f1 | 2014-03-06 03:23:41 +0000 | [diff] [blame] | 34 | #include "llvm/IR/InstVisitor.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 35 | #include "llvm/IR/IntrinsicInst.h" |
| 36 | #include "llvm/IR/LLVMContext.h" |
Kostya Serebryany | 714c67c | 2014-01-17 11:00:30 +0000 | [diff] [blame] | 37 | #include "llvm/IR/MDBuilder.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 38 | #include "llvm/IR/Module.h" |
| 39 | #include "llvm/IR/Type.h" |
Kuba Brecka | 1001bb5 | 2014-12-05 22:19:18 +0000 | [diff] [blame] | 40 | #include "llvm/MC/MCSectionMachO.h" |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 41 | #include "llvm/Support/CommandLine.h" |
| 42 | #include "llvm/Support/DataTypes.h" |
| 43 | #include "llvm/Support/Debug.h" |
Kostya Serebryany | 9e62b30 | 2013-06-03 14:46:56 +0000 | [diff] [blame] | 44 | #include "llvm/Support/Endian.h" |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 45 | #include "llvm/Support/SwapByteOrder.h" |
Kostya Serebryany | 351b078 | 2014-09-03 22:37:37 +0000 | [diff] [blame] | 46 | #include "llvm/Transforms/Scalar.h" |
Kostya Serebryany | 4fb7801 | 2013-12-06 09:00:17 +0000 | [diff] [blame] | 47 | #include "llvm/Transforms/Utils/ASanStackFrameLayout.h" |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 48 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Kostya Serebryany | 9f5213f | 2013-06-26 09:18:17 +0000 | [diff] [blame] | 49 | #include "llvm/Transforms/Utils/Cloning.h" |
Alexey Samsonov | 3d43b63 | 2012-12-12 14:31:53 +0000 | [diff] [blame] | 50 | #include "llvm/Transforms/Utils/Local.h" |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 51 | #include "llvm/Transforms/Utils/ModuleUtils.h" |
Anna Zaks | 8ed1d81 | 2015-02-27 03:12:36 +0000 | [diff] [blame^] | 52 | #include "llvm/Transforms/Utils/PromoteMemToReg.h" |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 53 | #include <algorithm> |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 54 | #include <string> |
Rafael Espindola | a6e9c3e | 2014-06-12 17:38:55 +0000 | [diff] [blame] | 55 | #include <system_error> |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 56 | |
| 57 | using namespace llvm; |
| 58 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 59 | #define DEBUG_TYPE "asan" |
| 60 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 61 | static const uint64_t kDefaultShadowScale = 3; |
| 62 | static const uint64_t kDefaultShadowOffset32 = 1ULL << 29; |
Alexander Potapenko | a51e483 | 2014-04-23 17:14:45 +0000 | [diff] [blame] | 63 | static const uint64_t kIOSShadowOffset32 = 1ULL << 30; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 64 | static const uint64_t kDefaultShadowOffset64 = 1ULL << 44; |
Kostya Serebryany | cc92c79 | 2014-02-24 13:40:24 +0000 | [diff] [blame] | 65 | static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G. |
Kostya Serebryany | 4766fe6 | 2013-01-23 12:54:55 +0000 | [diff] [blame] | 66 | static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41; |
Kostya Serebryany | c5bd981 | 2014-11-04 19:46:15 +0000 | [diff] [blame] | 67 | static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000; |
Kumar Sukhani | 9559a5c | 2015-01-31 10:43:18 +0000 | [diff] [blame] | 68 | static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37; |
Renato Golin | af21372 | 2015-02-03 11:20:45 +0000 | [diff] [blame] | 69 | static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36; |
Kostya Serebryany | 8baa386 | 2014-02-10 07:37:04 +0000 | [diff] [blame] | 70 | static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30; |
| 71 | static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46; |
Timur Iskhodzhanov | b4b6b74 | 2015-01-22 12:24:21 +0000 | [diff] [blame] | 72 | static const uint64_t kWindowsShadowOffset32 = 3ULL << 28; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 73 | |
Kostya Serebryany | 6805de5 | 2013-09-10 13:16:56 +0000 | [diff] [blame] | 74 | static const size_t kMinStackMallocSize = 1 << 6; // 64B |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 75 | static const size_t kMaxStackMallocSize = 1 << 16; // 64K |
| 76 | static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3; |
| 77 | static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E; |
| 78 | |
Craig Topper | d3a34f8 | 2013-07-16 01:17:10 +0000 | [diff] [blame] | 79 | static const char *const kAsanModuleCtorName = "asan.module_ctor"; |
| 80 | static const char *const kAsanModuleDtorName = "asan.module_dtor"; |
Kostya Serebryany | 34ddf87 | 2014-09-24 22:41:55 +0000 | [diff] [blame] | 81 | static const uint64_t kAsanCtorAndDtorPriority = 1; |
Craig Topper | d3a34f8 | 2013-07-16 01:17:10 +0000 | [diff] [blame] | 82 | static const char *const kAsanReportErrorTemplate = "__asan_report_"; |
| 83 | static const char *const kAsanReportLoadN = "__asan_report_load_n"; |
| 84 | static const char *const kAsanReportStoreN = "__asan_report_store_n"; |
| 85 | static const char *const kAsanRegisterGlobalsName = "__asan_register_globals"; |
Alexey Samsonov | f52b717 | 2013-08-05 13:19:49 +0000 | [diff] [blame] | 86 | static const char *const kAsanUnregisterGlobalsName = |
| 87 | "__asan_unregister_globals"; |
Craig Topper | d3a34f8 | 2013-07-16 01:17:10 +0000 | [diff] [blame] | 88 | static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init"; |
| 89 | static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init"; |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 90 | static const char *const kAsanInitName = "__asan_init_v5"; |
Kostya Serebryany | 796f655 | 2014-02-27 12:45:36 +0000 | [diff] [blame] | 91 | static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp"; |
| 92 | static const char *const kAsanPtrSub = "__sanitizer_ptr_sub"; |
Craig Topper | d3a34f8 | 2013-07-16 01:17:10 +0000 | [diff] [blame] | 93 | static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return"; |
Kostya Serebryany | 6805de5 | 2013-09-10 13:16:56 +0000 | [diff] [blame] | 94 | static const int kMaxAsanStackMallocSizeClass = 10; |
| 95 | static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_"; |
| 96 | static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_"; |
Craig Topper | d3a34f8 | 2013-07-16 01:17:10 +0000 | [diff] [blame] | 97 | static const char *const kAsanGenPrefix = "__asan_gen_"; |
Kostya Serebryany | cb45b12 | 2014-11-19 00:22:58 +0000 | [diff] [blame] | 98 | static const char *const kSanCovGenPrefix = "__sancov_gen_"; |
Craig Topper | d3a34f8 | 2013-07-16 01:17:10 +0000 | [diff] [blame] | 99 | static const char *const kAsanPoisonStackMemoryName = |
| 100 | "__asan_poison_stack_memory"; |
| 101 | static const char *const kAsanUnpoisonStackMemoryName = |
Alexey Samsonov | 261177a | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 102 | "__asan_unpoison_stack_memory"; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 103 | |
Kostya Serebryany | f322382 | 2013-09-18 14:07:14 +0000 | [diff] [blame] | 104 | static const char *const kAsanOptionDetectUAR = |
| 105 | "__asan_option_detect_stack_use_after_return"; |
| 106 | |
David Blaikie | eacc287 | 2013-09-18 00:11:27 +0000 | [diff] [blame] | 107 | #ifndef NDEBUG |
Kostya Serebryany | bc86efb | 2013-09-17 12:14:50 +0000 | [diff] [blame] | 108 | static const int kAsanStackAfterReturnMagic = 0xf5; |
David Blaikie | eacc287 | 2013-09-18 00:11:27 +0000 | [diff] [blame] | 109 | #endif |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 110 | |
Kostya Serebryany | 874dae6 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 111 | // Accesses sizes are powers of two: 1, 2, 4, 8, 16. |
| 112 | static const size_t kNumberOfAccessSizes = 5; |
| 113 | |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 114 | static const unsigned kAllocaRzSize = 32; |
| 115 | static const unsigned kAsanAllocaLeftMagic = 0xcacacacaU; |
| 116 | static const unsigned kAsanAllocaRightMagic = 0xcbcbcbcbU; |
| 117 | static const unsigned kAsanAllocaPartialVal1 = 0xcbcbcb00U; |
| 118 | static const unsigned kAsanAllocaPartialVal2 = 0x000000cbU; |
| 119 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 120 | // Command-line flags. |
| 121 | |
| 122 | // This flag may need to be replaced with -f[no-]asan-reads. |
| 123 | static cl::opt<bool> ClInstrumentReads("asan-instrument-reads", |
| 124 | cl::desc("instrument read instructions"), cl::Hidden, cl::init(true)); |
| 125 | static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes", |
| 126 | cl::desc("instrument write instructions"), cl::Hidden, cl::init(true)); |
Kostya Serebryany | 9024160 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 127 | static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics", |
| 128 | cl::desc("instrument atomic instructions (rmw, cmpxchg)"), |
| 129 | cl::Hidden, cl::init(true)); |
Kostya Serebryany | 1e575ab | 2012-08-15 08:58:58 +0000 | [diff] [blame] | 130 | static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path", |
| 131 | cl::desc("use instrumentation with slow path for all accesses"), |
| 132 | cl::Hidden, cl::init(false)); |
Kostya Serebryany | 874dae6 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 133 | // This flag limits the number of instructions to be instrumented |
Kostya Serebryany | c387ca7 | 2012-06-28 09:34:41 +0000 | [diff] [blame] | 134 | // in any given BB. Normally, this should be set to unlimited (INT_MAX), |
| 135 | // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary |
| 136 | // set it to 10000. |
| 137 | static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb", |
| 138 | cl::init(10000), |
| 139 | cl::desc("maximal number of instructions to instrument in any given BB"), |
| 140 | cl::Hidden); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 141 | // This flag may need to be replaced with -f[no]asan-stack. |
| 142 | static cl::opt<bool> ClStack("asan-stack", |
| 143 | cl::desc("Handle stack memory"), cl::Hidden, cl::init(true)); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 144 | static cl::opt<bool> ClUseAfterReturn("asan-use-after-return", |
Alexey Samsonov | e595e1a | 2014-06-13 17:53:44 +0000 | [diff] [blame] | 145 | cl::desc("Check return-after-free"), cl::Hidden, cl::init(true)); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 146 | // This flag may need to be replaced with -f[no]asan-globals. |
| 147 | static cl::opt<bool> ClGlobals("asan-globals", |
| 148 | cl::desc("Handle global objects"), cl::Hidden, cl::init(true)); |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 149 | static cl::opt<bool> ClInitializers("asan-initialization-order", |
Alexey Samsonov | e595e1a | 2014-06-13 17:53:44 +0000 | [diff] [blame] | 150 | cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true)); |
Kostya Serebryany | 796f655 | 2014-02-27 12:45:36 +0000 | [diff] [blame] | 151 | static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair", |
| 152 | cl::desc("Instrument <, <=, >, >=, - with pointer operands"), |
Kostya Serebryany | ec34665 | 2014-02-27 12:56:20 +0000 | [diff] [blame] | 153 | cl::Hidden, cl::init(false)); |
Kostya Serebryany | 4fb7801 | 2013-12-06 09:00:17 +0000 | [diff] [blame] | 154 | static cl::opt<unsigned> ClRealignStack("asan-realign-stack", |
| 155 | cl::desc("Realign stack to the value of this flag (power of two)"), |
| 156 | cl::Hidden, cl::init(32)); |
Kostya Serebryany | 0c02d26 | 2014-04-16 12:12:19 +0000 | [diff] [blame] | 157 | static cl::opt<int> ClInstrumentationWithCallsThreshold( |
| 158 | "asan-instrumentation-with-call-threshold", |
| 159 | cl::desc("If the function being instrumented contains more than " |
| 160 | "this number of memory accesses, use callbacks instead of " |
| 161 | "inline checks (-1 means never use callbacks)."), |
Kostya Serebryany | 4d237a8 | 2014-05-26 11:57:16 +0000 | [diff] [blame] | 162 | cl::Hidden, cl::init(7000)); |
Kostya Serebryany | 0c02d26 | 2014-04-16 12:12:19 +0000 | [diff] [blame] | 163 | static cl::opt<std::string> ClMemoryAccessCallbackPrefix( |
| 164 | "asan-memory-access-callback-prefix", |
| 165 | cl::desc("Prefix for memory access callbacks"), cl::Hidden, |
| 166 | cl::init("__asan_")); |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 167 | static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas", |
| 168 | cl::desc("instrument dynamic allocas"), cl::Hidden, cl::init(false)); |
Anna Zaks | 8ed1d81 | 2015-02-27 03:12:36 +0000 | [diff] [blame^] | 169 | static cl::opt<bool> ClSkipPromotableAllocas("asan-skip-promotable-allocas", |
| 170 | cl::desc("Do not instrument promotable allocas"), |
| 171 | cl::Hidden, cl::init(true)); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 172 | |
| 173 | // These flags allow to change the shadow mapping. |
| 174 | // The shadow mapping looks like |
| 175 | // Shadow = (Mem >> scale) + (1 << offset_log) |
| 176 | static cl::opt<int> ClMappingScale("asan-mapping-scale", |
| 177 | cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0)); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 178 | |
| 179 | // Optimization flags. Not user visible, used mostly for testing |
| 180 | // and benchmarking the tool. |
| 181 | static cl::opt<bool> ClOpt("asan-opt", |
| 182 | cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true)); |
| 183 | static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp", |
| 184 | cl::desc("Instrument the same temp just once"), cl::Hidden, |
| 185 | cl::init(true)); |
| 186 | static cl::opt<bool> ClOptGlobals("asan-opt-globals", |
| 187 | cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true)); |
| 188 | |
Alexey Samsonov | df62452 | 2012-11-29 18:14:24 +0000 | [diff] [blame] | 189 | static cl::opt<bool> ClCheckLifetime("asan-check-lifetime", |
| 190 | cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), |
| 191 | cl::Hidden, cl::init(false)); |
| 192 | |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 193 | static cl::opt<bool> ClDynamicAllocaStack( |
| 194 | "asan-stack-dynamic-alloca", |
| 195 | cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden, |
Alexey Samsonov | 19763c4 | 2015-02-05 19:39:20 +0000 | [diff] [blame] | 196 | cl::init(true)); |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 197 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 198 | // Debug flags. |
| 199 | static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden, |
| 200 | cl::init(0)); |
| 201 | static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"), |
| 202 | cl::Hidden, cl::init(0)); |
| 203 | static cl::opt<std::string> ClDebugFunc("asan-debug-func", |
| 204 | cl::Hidden, cl::desc("Debug func")); |
| 205 | static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"), |
| 206 | cl::Hidden, cl::init(-1)); |
| 207 | static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"), |
| 208 | cl::Hidden, cl::init(-1)); |
| 209 | |
Kostya Serebryany | d3d23be | 2013-10-16 14:06:14 +0000 | [diff] [blame] | 210 | STATISTIC(NumInstrumentedReads, "Number of instrumented reads"); |
| 211 | STATISTIC(NumInstrumentedWrites, "Number of instrumented writes"); |
Kostya Serebryany | ea2cb6f | 2014-11-21 21:25:18 +0000 | [diff] [blame] | 212 | STATISTIC(NumInstrumentedDynamicAllocas, |
| 213 | "Number of instrumented dynamic allocas"); |
Kostya Serebryany | d3d23be | 2013-10-16 14:06:14 +0000 | [diff] [blame] | 214 | STATISTIC(NumOptimizedAccessesToGlobalArray, |
| 215 | "Number of optimized accesses to global arrays"); |
| 216 | STATISTIC(NumOptimizedAccessesToGlobalVar, |
| 217 | "Number of optimized accesses to global vars"); |
| 218 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 219 | namespace { |
Alexey Samsonov | d9ad5ce | 2014-08-02 00:35:50 +0000 | [diff] [blame] | 220 | /// Frontend-provided metadata for source location. |
| 221 | struct LocationMetadata { |
| 222 | StringRef Filename; |
| 223 | int LineNo; |
| 224 | int ColumnNo; |
| 225 | |
| 226 | LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {} |
| 227 | |
| 228 | bool empty() const { return Filename.empty(); } |
| 229 | |
| 230 | void parse(MDNode *MDN) { |
| 231 | assert(MDN->getNumOperands() == 3); |
| 232 | MDString *MDFilename = cast<MDString>(MDN->getOperand(0)); |
| 233 | Filename = MDFilename->getString(); |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 234 | LineNo = |
| 235 | mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue(); |
| 236 | ColumnNo = |
| 237 | mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue(); |
Alexey Samsonov | d9ad5ce | 2014-08-02 00:35:50 +0000 | [diff] [blame] | 238 | } |
| 239 | }; |
| 240 | |
Alexey Samsonov | 4f319cc | 2014-07-02 16:54:41 +0000 | [diff] [blame] | 241 | /// Frontend-provided metadata for global variables. |
| 242 | class GlobalsMetadata { |
Kostya Serebryany | b3bd605 | 2012-11-20 13:00:01 +0000 | [diff] [blame] | 243 | public: |
Alexey Samsonov | 08f022a | 2014-07-11 22:36:02 +0000 | [diff] [blame] | 244 | struct Entry { |
Alexey Samsonov | 15c9669 | 2014-07-12 00:42:52 +0000 | [diff] [blame] | 245 | Entry() |
Alexey Samsonov | d9ad5ce | 2014-08-02 00:35:50 +0000 | [diff] [blame] | 246 | : SourceLoc(), Name(), IsDynInit(false), |
Alexey Samsonov | 15c9669 | 2014-07-12 00:42:52 +0000 | [diff] [blame] | 247 | IsBlacklisted(false) {} |
Alexey Samsonov | d9ad5ce | 2014-08-02 00:35:50 +0000 | [diff] [blame] | 248 | LocationMetadata SourceLoc; |
| 249 | StringRef Name; |
Alexey Samsonov | 08f022a | 2014-07-11 22:36:02 +0000 | [diff] [blame] | 250 | bool IsDynInit; |
| 251 | bool IsBlacklisted; |
| 252 | }; |
| 253 | |
Alexey Samsonov | 0c5ecdd | 2014-07-02 20:25:42 +0000 | [diff] [blame] | 254 | GlobalsMetadata() : inited_(false) {} |
Alexey Samsonov | 08f022a | 2014-07-11 22:36:02 +0000 | [diff] [blame] | 255 | |
Alexey Samsonov | 4f319cc | 2014-07-02 16:54:41 +0000 | [diff] [blame] | 256 | void init(Module& M) { |
| 257 | assert(!inited_); |
| 258 | inited_ = true; |
| 259 | NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals"); |
| 260 | if (!Globals) |
Kostya Serebryany | b3bd605 | 2012-11-20 13:00:01 +0000 | [diff] [blame] | 261 | return; |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 262 | for (auto MDN : Globals->operands()) { |
Alexey Samsonov | 08f022a | 2014-07-11 22:36:02 +0000 | [diff] [blame] | 263 | // Metadata node contains the global and the fields of "Entry". |
Alexey Samsonov | 15c9669 | 2014-07-12 00:42:52 +0000 | [diff] [blame] | 264 | assert(MDN->getNumOperands() == 5); |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 265 | auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0)); |
Alexey Samsonov | 4f319cc | 2014-07-02 16:54:41 +0000 | [diff] [blame] | 266 | // The optimizer may optimize away a global entirely. |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 267 | if (!GV) |
Kostya Serebryany | b3bd605 | 2012-11-20 13:00:01 +0000 | [diff] [blame] | 268 | continue; |
Alexey Samsonov | 08f022a | 2014-07-11 22:36:02 +0000 | [diff] [blame] | 269 | // We can already have an entry for GV if it was merged with another |
| 270 | // global. |
| 271 | Entry &E = Entries[GV]; |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 272 | if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1))) |
| 273 | E.SourceLoc.parse(Loc); |
| 274 | if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2))) |
| 275 | E.Name = Name->getString(); |
| 276 | ConstantInt *IsDynInit = |
| 277 | mdconst::extract<ConstantInt>(MDN->getOperand(3)); |
Alexey Samsonov | 08f022a | 2014-07-11 22:36:02 +0000 | [diff] [blame] | 278 | E.IsDynInit |= IsDynInit->isOne(); |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 279 | ConstantInt *IsBlacklisted = |
| 280 | mdconst::extract<ConstantInt>(MDN->getOperand(4)); |
Alexey Samsonov | 08f022a | 2014-07-11 22:36:02 +0000 | [diff] [blame] | 281 | E.IsBlacklisted |= IsBlacklisted->isOne(); |
Kostya Serebryany | b3bd605 | 2012-11-20 13:00:01 +0000 | [diff] [blame] | 282 | } |
| 283 | } |
Alexey Samsonov | 4f319cc | 2014-07-02 16:54:41 +0000 | [diff] [blame] | 284 | |
Alexey Samsonov | 08f022a | 2014-07-11 22:36:02 +0000 | [diff] [blame] | 285 | /// Returns metadata entry for a given global. |
| 286 | Entry get(GlobalVariable *G) const { |
| 287 | auto Pos = Entries.find(G); |
| 288 | return (Pos != Entries.end()) ? Pos->second : Entry(); |
Alexey Samsonov | 4f319cc | 2014-07-02 16:54:41 +0000 | [diff] [blame] | 289 | } |
| 290 | |
Kostya Serebryany | b3bd605 | 2012-11-20 13:00:01 +0000 | [diff] [blame] | 291 | private: |
Alexey Samsonov | 0c5ecdd | 2014-07-02 20:25:42 +0000 | [diff] [blame] | 292 | bool inited_; |
Alexey Samsonov | 08f022a | 2014-07-11 22:36:02 +0000 | [diff] [blame] | 293 | DenseMap<GlobalVariable*, Entry> Entries; |
Kostya Serebryany | b3bd605 | 2012-11-20 13:00:01 +0000 | [diff] [blame] | 294 | }; |
| 295 | |
Alexey Samsonov | 1345d35 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 296 | /// This struct defines the shadow mapping using the rule: |
Kostya Serebryany | 4766fe6 | 2013-01-23 12:54:55 +0000 | [diff] [blame] | 297 | /// shadow = (mem >> Scale) ADD-or-OR Offset. |
Alexey Samsonov | 1345d35 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 298 | struct ShadowMapping { |
| 299 | int Scale; |
| 300 | uint64_t Offset; |
Kostya Serebryany | 4766fe6 | 2013-01-23 12:54:55 +0000 | [diff] [blame] | 301 | bool OrShadowOffset; |
Alexey Samsonov | 1345d35 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 302 | }; |
| 303 | |
Kuba Brecka | 1001bb5 | 2014-12-05 22:19:18 +0000 | [diff] [blame] | 304 | static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize) { |
Alexey Samsonov | 347bcd3 | 2013-01-17 11:12:32 +0000 | [diff] [blame] | 305 | bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android; |
Bob Wilson | 9868d71 | 2014-10-09 05:43:30 +0000 | [diff] [blame] | 306 | bool IsIOS = TargetTriple.isiOS(); |
Simon Pilgrim | a279410 | 2014-11-22 19:12:10 +0000 | [diff] [blame] | 307 | bool IsFreeBSD = TargetTriple.isOSFreeBSD(); |
| 308 | bool IsLinux = TargetTriple.isOSLinux(); |
Bill Schmidt | 0a9170d | 2013-07-26 01:35:43 +0000 | [diff] [blame] | 309 | bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 || |
| 310 | TargetTriple.getArch() == llvm::Triple::ppc64le; |
Kostya Serebryany | be73337 | 2013-02-12 11:11:02 +0000 | [diff] [blame] | 311 | bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64; |
Kostya Serebryany | 9e62b30 | 2013-06-03 14:46:56 +0000 | [diff] [blame] | 312 | bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips || |
| 313 | TargetTriple.getArch() == llvm::Triple::mipsel; |
Kostya Serebryany | 231bd08 | 2014-11-11 23:02:57 +0000 | [diff] [blame] | 314 | bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 || |
| 315 | TargetTriple.getArch() == llvm::Triple::mips64el; |
Renato Golin | af21372 | 2015-02-03 11:20:45 +0000 | [diff] [blame] | 316 | bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64; |
Timur Iskhodzhanov | 00ede84 | 2015-01-12 17:38:58 +0000 | [diff] [blame] | 317 | bool IsWindows = TargetTriple.isOSWindows(); |
Alexey Samsonov | 1345d35 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 318 | |
| 319 | ShadowMapping Mapping; |
| 320 | |
Kostya Serebryany | cc92c79 | 2014-02-24 13:40:24 +0000 | [diff] [blame] | 321 | if (LongSize == 32) { |
| 322 | if (IsAndroid) |
| 323 | Mapping.Offset = 0; |
| 324 | else if (IsMIPS32) |
| 325 | Mapping.Offset = kMIPS32_ShadowOffset32; |
| 326 | else if (IsFreeBSD) |
| 327 | Mapping.Offset = kFreeBSD_ShadowOffset32; |
Alexander Potapenko | a51e483 | 2014-04-23 17:14:45 +0000 | [diff] [blame] | 328 | else if (IsIOS) |
| 329 | Mapping.Offset = kIOSShadowOffset32; |
Timur Iskhodzhanov | 00ede84 | 2015-01-12 17:38:58 +0000 | [diff] [blame] | 330 | else if (IsWindows) |
| 331 | Mapping.Offset = kWindowsShadowOffset32; |
Kostya Serebryany | cc92c79 | 2014-02-24 13:40:24 +0000 | [diff] [blame] | 332 | else |
| 333 | Mapping.Offset = kDefaultShadowOffset32; |
| 334 | } else { // LongSize == 64 |
| 335 | if (IsPPC64) |
| 336 | Mapping.Offset = kPPC64_ShadowOffset64; |
| 337 | else if (IsFreeBSD) |
| 338 | Mapping.Offset = kFreeBSD_ShadowOffset64; |
| 339 | else if (IsLinux && IsX86_64) |
| 340 | Mapping.Offset = kSmallX86_64ShadowOffset; |
Kostya Serebryany | 231bd08 | 2014-11-11 23:02:57 +0000 | [diff] [blame] | 341 | else if (IsMIPS64) |
| 342 | Mapping.Offset = kMIPS64_ShadowOffset64; |
Renato Golin | af21372 | 2015-02-03 11:20:45 +0000 | [diff] [blame] | 343 | else if (IsAArch64) |
| 344 | Mapping.Offset = kAArch64_ShadowOffset64; |
Kostya Serebryany | cc92c79 | 2014-02-24 13:40:24 +0000 | [diff] [blame] | 345 | else |
| 346 | Mapping.Offset = kDefaultShadowOffset64; |
Alexey Samsonov | 1345d35 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 347 | } |
| 348 | |
| 349 | Mapping.Scale = kDefaultShadowScale; |
| 350 | if (ClMappingScale) { |
| 351 | Mapping.Scale = ClMappingScale; |
| 352 | } |
| 353 | |
Kostya Serebryany | cc92c79 | 2014-02-24 13:40:24 +0000 | [diff] [blame] | 354 | // OR-ing shadow offset if more efficient (at least on x86) if the offset |
| 355 | // is a power of two, but on ppc64 we have to use add since the shadow |
| 356 | // offset is not necessary 1/8-th of the address space. |
| 357 | Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1)); |
| 358 | |
Alexey Samsonov | 1345d35 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 359 | return Mapping; |
Kostya Serebryany | 20a7997 | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 360 | } |
| 361 | |
Alexey Samsonov | 1345d35 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 362 | static size_t RedzoneSizeForScale(int MappingScale) { |
Kostya Serebryany | 20a7997 | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 363 | // Redzone used for stack and globals is at least 32 bytes. |
| 364 | // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively. |
Alexey Samsonov | 1345d35 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 365 | return std::max(32U, 1U << MappingScale); |
Kostya Serebryany | 20a7997 | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 366 | } |
Kostya Serebryany | b3bd605 | 2012-11-20 13:00:01 +0000 | [diff] [blame] | 367 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 368 | /// AddressSanitizer: instrument the code in module to find memory bugs. |
Kostya Serebryany | b0e2506 | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 369 | struct AddressSanitizer : public FunctionPass { |
Yury Gribov | 3ae427d | 2014-12-01 08:47:58 +0000 | [diff] [blame] | 370 | AddressSanitizer() : FunctionPass(ID) { |
| 371 | initializeAddressSanitizerPass(*PassRegistry::getPassRegistry()); |
| 372 | } |
Craig Topper | 3e4c697 | 2014-03-05 09:10:37 +0000 | [diff] [blame] | 373 | const char *getPassName() const override { |
Kostya Serebryany | dfe9e79 | 2012-11-28 10:31:36 +0000 | [diff] [blame] | 374 | return "AddressSanitizerFunctionPass"; |
| 375 | } |
Yury Gribov | 3ae427d | 2014-12-01 08:47:58 +0000 | [diff] [blame] | 376 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 377 | AU.addRequired<DominatorTreeWrapperPass>(); |
| 378 | } |
Anna Zaks | 8ed1d81 | 2015-02-27 03:12:36 +0000 | [diff] [blame^] | 379 | uint64_t getAllocaSizeInBytes(AllocaInst *AI) const { |
| 380 | Type *Ty = AI->getAllocatedType(); |
| 381 | uint64_t SizeInBytes = DL->getTypeAllocSize(Ty); |
| 382 | return SizeInBytes; |
| 383 | } |
| 384 | /// Check if we want (and can) handle this alloca. |
| 385 | bool isInterestingAlloca(AllocaInst &AI) const; |
| 386 | /// If it is an interesting memory access, return the PointerOperand |
| 387 | /// and set IsWrite/Alignment. Otherwise return nullptr. |
| 388 | Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite, |
| 389 | unsigned *Alignment) const; |
Kostya Serebryany | 0c02d26 | 2014-04-16 12:12:19 +0000 | [diff] [blame] | 390 | void instrumentMop(Instruction *I, bool UseCalls); |
Kostya Serebryany | 796f655 | 2014-02-27 12:45:36 +0000 | [diff] [blame] | 391 | void instrumentPointerComparisonOrSubtraction(Instruction *I); |
Kostya Serebryany | 3ece9bea | 2013-02-19 11:29:21 +0000 | [diff] [blame] | 392 | void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore, |
| 393 | Value *Addr, uint32_t TypeSize, bool IsWrite, |
Kostya Serebryany | 0c02d26 | 2014-04-16 12:12:19 +0000 | [diff] [blame] | 394 | Value *SizeArgument, bool UseCalls); |
Kostya Serebryany | 874dae6 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 395 | Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong, |
| 396 | Value *ShadowValue, uint32_t TypeSize); |
Kostya Serebryany | fda7a13 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 397 | Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr, |
Kostya Serebryany | 3ece9bea | 2013-02-19 11:29:21 +0000 | [diff] [blame] | 398 | bool IsWrite, size_t AccessSizeIndex, |
| 399 | Value *SizeArgument); |
Kostya Serebryany | 94c81ca | 2014-04-21 11:50:42 +0000 | [diff] [blame] | 400 | void instrumentMemIntrinsic(MemIntrinsic *MI); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 401 | Value *memToShadow(Value *Shadow, IRBuilder<> &IRB); |
Craig Topper | 3e4c697 | 2014-03-05 09:10:37 +0000 | [diff] [blame] | 402 | bool runOnFunction(Function &F) override; |
Kostya Serebryany | 22ddcfd | 2012-01-30 23:50:10 +0000 | [diff] [blame] | 403 | bool maybeInsertAsanInitAtFunctionEntry(Function &F); |
Craig Topper | 3e4c697 | 2014-03-05 09:10:37 +0000 | [diff] [blame] | 404 | bool doInitialization(Module &M) override; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 405 | static char ID; // Pass identification, replacement for typeid |
| 406 | |
Yury Gribov | 3ae427d | 2014-12-01 08:47:58 +0000 | [diff] [blame] | 407 | DominatorTree &getDominatorTree() const { return *DT; } |
| 408 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 409 | private: |
Kostya Serebryany | 4b929da | 2012-11-29 09:54:21 +0000 | [diff] [blame] | 410 | void initializeCallbacks(Module &M); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 411 | |
Kostya Serebryany | 1cdc6e9 | 2011-11-18 01:41:06 +0000 | [diff] [blame] | 412 | bool LooksLikeCodeInBug11395(Instruction *I); |
Kostya Serebryany | d3d23be | 2013-10-16 14:06:14 +0000 | [diff] [blame] | 413 | bool GlobalIsLinkerInitialized(GlobalVariable *G); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 414 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 415 | LLVMContext *C; |
Rafael Espindola | aeff8a9 | 2014-02-24 23:12:18 +0000 | [diff] [blame] | 416 | const DataLayout *DL; |
Kuba Brecka | 1001bb5 | 2014-12-05 22:19:18 +0000 | [diff] [blame] | 417 | Triple TargetTriple; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 418 | int LongSize; |
| 419 | Type *IntptrTy; |
Alexey Samsonov | 1345d35 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 420 | ShadowMapping Mapping; |
Yury Gribov | 3ae427d | 2014-12-01 08:47:58 +0000 | [diff] [blame] | 421 | DominatorTree *DT; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 422 | Function *AsanCtorFunction; |
| 423 | Function *AsanInitFunction; |
Kostya Serebryany | b0e2506 | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 424 | Function *AsanHandleNoReturnFunc; |
Kostya Serebryany | 796f655 | 2014-02-27 12:45:36 +0000 | [diff] [blame] | 425 | Function *AsanPtrCmpFunction, *AsanPtrSubFunction; |
Kostya Serebryany | 4273bb0 | 2012-07-16 14:09:42 +0000 | [diff] [blame] | 426 | // This array is indexed by AccessIsWrite and log2(AccessSize). |
| 427 | Function *AsanErrorCallback[2][kNumberOfAccessSizes]; |
Kostya Serebryany | 0c02d26 | 2014-04-16 12:12:19 +0000 | [diff] [blame] | 428 | Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes]; |
Kostya Serebryany | 3ece9bea | 2013-02-19 11:29:21 +0000 | [diff] [blame] | 429 | // This array is indexed by AccessIsWrite. |
Kostya Serebryany | 86332c0 | 2014-04-21 07:10:43 +0000 | [diff] [blame] | 430 | Function *AsanErrorCallbackSized[2], |
| 431 | *AsanMemoryAccessCallbackSized[2]; |
Kostya Serebryany | 94c81ca | 2014-04-21 11:50:42 +0000 | [diff] [blame] | 432 | Function *AsanMemmove, *AsanMemcpy, *AsanMemset; |
Kostya Serebryany | f02c606 | 2012-07-20 09:54:50 +0000 | [diff] [blame] | 433 | InlineAsm *EmptyAsm; |
Alexey Samsonov | 4f319cc | 2014-07-02 16:54:41 +0000 | [diff] [blame] | 434 | GlobalsMetadata GlobalsMD; |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 435 | |
| 436 | friend struct FunctionStackPoisoner; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 437 | }; |
Kostya Serebryany | 874dae6 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 438 | |
Kostya Serebryany | dfe9e79 | 2012-11-28 10:31:36 +0000 | [diff] [blame] | 439 | class AddressSanitizerModule : public ModulePass { |
Kostya Serebryany | 20a7997 | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 440 | public: |
Alexey Samsonov | c94285a | 2014-07-08 00:50:49 +0000 | [diff] [blame] | 441 | AddressSanitizerModule() : ModulePass(ID) {} |
Craig Topper | 3e4c697 | 2014-03-05 09:10:37 +0000 | [diff] [blame] | 442 | bool runOnModule(Module &M) override; |
Kostya Serebryany | dfe9e79 | 2012-11-28 10:31:36 +0000 | [diff] [blame] | 443 | static char ID; // Pass identification, replacement for typeid |
Craig Topper | 3e4c697 | 2014-03-05 09:10:37 +0000 | [diff] [blame] | 444 | const char *getPassName() const override { |
Kostya Serebryany | dfe9e79 | 2012-11-28 10:31:36 +0000 | [diff] [blame] | 445 | return "AddressSanitizerModule"; |
| 446 | } |
Alexey Samsonov | 261177a | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 447 | |
Kostya Serebryany | 20a7997 | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 448 | private: |
Alexey Samsonov | 788381b | 2012-12-25 12:28:20 +0000 | [diff] [blame] | 449 | void initializeCallbacks(Module &M); |
| 450 | |
Evgeniy Stepanov | 19f75fc | 2014-06-03 14:16:00 +0000 | [diff] [blame] | 451 | bool InstrumentGlobals(IRBuilder<> &IRB, Module &M); |
Kostya Serebryany | 20a7997 | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 452 | bool ShouldInstrumentGlobal(GlobalVariable *G); |
Alexey Samsonov | 96e239f | 2014-05-29 00:51:15 +0000 | [diff] [blame] | 453 | void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName); |
Alexey Samsonov | e1e26bf | 2013-03-26 13:05:41 +0000 | [diff] [blame] | 454 | void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName); |
Kostya Serebryany | 4fb7801 | 2013-12-06 09:00:17 +0000 | [diff] [blame] | 455 | size_t MinRedzoneSizeForGlobal() const { |
Alexey Samsonov | 1345d35 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 456 | return RedzoneSizeForScale(Mapping.Scale); |
| 457 | } |
Kostya Serebryany | 20a7997 | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 458 | |
Alexey Samsonov | 4f319cc | 2014-07-02 16:54:41 +0000 | [diff] [blame] | 459 | GlobalsMetadata GlobalsMD; |
Kostya Serebryany | 20a7997 | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 460 | Type *IntptrTy; |
| 461 | LLVMContext *C; |
Rafael Espindola | aeff8a9 | 2014-02-24 23:12:18 +0000 | [diff] [blame] | 462 | const DataLayout *DL; |
Kuba Brecka | 1001bb5 | 2014-12-05 22:19:18 +0000 | [diff] [blame] | 463 | Triple TargetTriple; |
Alexey Samsonov | 1345d35 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 464 | ShadowMapping Mapping; |
Alexey Samsonov | 788381b | 2012-12-25 12:28:20 +0000 | [diff] [blame] | 465 | Function *AsanPoisonGlobals; |
| 466 | Function *AsanUnpoisonGlobals; |
| 467 | Function *AsanRegisterGlobals; |
| 468 | Function *AsanUnregisterGlobals; |
Kostya Serebryany | 20a7997 | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 469 | }; |
| 470 | |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 471 | // Stack poisoning does not play well with exception handling. |
| 472 | // When an exception is thrown, we essentially bypass the code |
| 473 | // that unpoisones the stack. This is why the run-time library has |
| 474 | // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire |
| 475 | // stack in the interceptor. This however does not work inside the |
| 476 | // actual function which catches the exception. Most likely because the |
| 477 | // compiler hoists the load of the shadow value somewhere too high. |
| 478 | // This causes asan to report a non-existing bug on 453.povray. |
| 479 | // It sounds like an LLVM bug. |
| 480 | struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> { |
| 481 | Function &F; |
| 482 | AddressSanitizer &ASan; |
| 483 | DIBuilder DIB; |
| 484 | LLVMContext *C; |
| 485 | Type *IntptrTy; |
| 486 | Type *IntptrPtrTy; |
Alexey Samsonov | 1345d35 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 487 | ShadowMapping Mapping; |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 488 | |
| 489 | SmallVector<AllocaInst*, 16> AllocaVec; |
| 490 | SmallVector<Instruction*, 8> RetVec; |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 491 | unsigned StackAlignment; |
| 492 | |
Kostya Serebryany | 6805de5 | 2013-09-10 13:16:56 +0000 | [diff] [blame] | 493 | Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1], |
| 494 | *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1]; |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 495 | Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc; |
| 496 | |
Alexey Samsonov | 29dd7f2 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 497 | // Stores a place and arguments of poisoning/unpoisoning call for alloca. |
| 498 | struct AllocaPoisonCall { |
| 499 | IntrinsicInst *InsBefore; |
Alexey Samsonov | a788b94 | 2013-11-18 14:53:55 +0000 | [diff] [blame] | 500 | AllocaInst *AI; |
Alexey Samsonov | 29dd7f2 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 501 | uint64_t Size; |
| 502 | bool DoPoison; |
| 503 | }; |
| 504 | SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec; |
| 505 | |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 506 | // Stores left and right redzone shadow addresses for dynamic alloca |
| 507 | // and pointer to alloca instruction itself. |
| 508 | // LeftRzAddr is a shadow address for alloca left redzone. |
| 509 | // RightRzAddr is a shadow address for alloca right redzone. |
| 510 | struct DynamicAllocaCall { |
| 511 | AllocaInst *AI; |
| 512 | Value *LeftRzAddr; |
| 513 | Value *RightRzAddr; |
Yury Gribov | 3ae427d | 2014-12-01 08:47:58 +0000 | [diff] [blame] | 514 | bool Poison; |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 515 | explicit DynamicAllocaCall(AllocaInst *AI, |
| 516 | Value *LeftRzAddr = nullptr, |
| 517 | Value *RightRzAddr = nullptr) |
Yury Gribov | 3ae427d | 2014-12-01 08:47:58 +0000 | [diff] [blame] | 518 | : AI(AI), LeftRzAddr(LeftRzAddr), RightRzAddr(RightRzAddr), Poison(true) |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 519 | {} |
| 520 | }; |
| 521 | SmallVector<DynamicAllocaCall, 1> DynamicAllocaVec; |
| 522 | |
Alexey Samsonov | 29dd7f2 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 523 | // Maps Value to an AllocaInst from which the Value is originated. |
| 524 | typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy; |
| 525 | AllocaForValueMapTy AllocaForValue; |
| 526 | |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 527 | bool HasNonEmptyInlineAsm; |
| 528 | std::unique_ptr<CallInst> EmptyInlineAsm; |
| 529 | |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 530 | FunctionStackPoisoner(Function &F, AddressSanitizer &ASan) |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 531 | : F(F), ASan(ASan), DIB(*F.getParent(), /*AllowUnresolved*/ false), |
| 532 | C(ASan.C), IntptrTy(ASan.IntptrTy), |
| 533 | IntptrPtrTy(PointerType::get(IntptrTy, 0)), Mapping(ASan.Mapping), |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 534 | StackAlignment(1 << Mapping.Scale), HasNonEmptyInlineAsm(false), |
| 535 | EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {} |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 536 | |
| 537 | bool runOnFunction() { |
| 538 | if (!ClStack) return false; |
| 539 | // Collect alloca, ret, lifetime instructions etc. |
David Blaikie | ceec2bd | 2014-04-11 01:50:01 +0000 | [diff] [blame] | 540 | for (BasicBlock *BB : depth_first(&F.getEntryBlock())) |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 541 | visit(*BB); |
David Blaikie | ceec2bd | 2014-04-11 01:50:01 +0000 | [diff] [blame] | 542 | |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 543 | if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false; |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 544 | |
| 545 | initializeCallbacks(*F.getParent()); |
| 546 | |
| 547 | poisonStack(); |
| 548 | |
| 549 | if (ClDebugStack) { |
| 550 | DEBUG(dbgs() << F); |
| 551 | } |
| 552 | return true; |
| 553 | } |
| 554 | |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 555 | // Finds all Alloca instructions and puts |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 556 | // poisoned red zones around all of them. |
| 557 | // Then unpoison everything back before the function returns. |
| 558 | void poisonStack(); |
| 559 | |
| 560 | // ----------------------- Visitors. |
| 561 | /// \brief Collect all Ret instructions. |
| 562 | void visitReturnInst(ReturnInst &RI) { |
| 563 | RetVec.push_back(&RI); |
| 564 | } |
| 565 | |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 566 | // Unpoison dynamic allocas redzones. |
| 567 | void unpoisonDynamicAlloca(DynamicAllocaCall &AllocaCall) { |
Yury Gribov | 3ae427d | 2014-12-01 08:47:58 +0000 | [diff] [blame] | 568 | if (!AllocaCall.Poison) |
| 569 | return; |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 570 | for (auto Ret : RetVec) { |
| 571 | IRBuilder<> IRBRet(Ret); |
| 572 | PointerType *Int32PtrTy = PointerType::getUnqual(IRBRet.getInt32Ty()); |
| 573 | Value *Zero = Constant::getNullValue(IRBRet.getInt32Ty()); |
| 574 | Value *PartialRzAddr = IRBRet.CreateSub(AllocaCall.RightRzAddr, |
| 575 | ConstantInt::get(IntptrTy, 4)); |
| 576 | IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.LeftRzAddr, |
| 577 | Int32PtrTy)); |
| 578 | IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(PartialRzAddr, |
| 579 | Int32PtrTy)); |
| 580 | IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.RightRzAddr, |
| 581 | Int32PtrTy)); |
| 582 | } |
| 583 | } |
| 584 | |
| 585 | // Right shift for BigEndian and left shift for LittleEndian. |
| 586 | Value *shiftAllocaMagic(Value *Val, IRBuilder<> &IRB, Value *Shift) { |
| 587 | return ASan.DL->isLittleEndian() ? IRB.CreateShl(Val, Shift) |
| 588 | : IRB.CreateLShr(Val, Shift); |
| 589 | } |
| 590 | |
| 591 | // Compute PartialRzMagic for dynamic alloca call. Since we don't know the |
| 592 | // size of requested memory until runtime, we should compute it dynamically. |
| 593 | // If PartialSize is 0, PartialRzMagic would contain kAsanAllocaRightMagic, |
| 594 | // otherwise it would contain the value that we will use to poison the |
| 595 | // partial redzone for alloca call. |
| 596 | Value *computePartialRzMagic(Value *PartialSize, IRBuilder<> &IRB); |
| 597 | |
| 598 | // Deploy and poison redzones around dynamic alloca call. To do this, we |
| 599 | // should replace this call with another one with changed parameters and |
| 600 | // replace all its uses with new address, so |
| 601 | // addr = alloca type, old_size, align |
| 602 | // is replaced by |
| 603 | // new_size = (old_size + additional_size) * sizeof(type) |
| 604 | // tmp = alloca i8, new_size, max(align, 32) |
| 605 | // addr = tmp + 32 (first 32 bytes are for the left redzone). |
| 606 | // Additional_size is added to make new memory allocation contain not only |
| 607 | // requested memory, but also left, partial and right redzones. |
| 608 | // After that, we should poison redzones: |
| 609 | // (1) Left redzone with kAsanAllocaLeftMagic. |
| 610 | // (2) Partial redzone with the value, computed in runtime by |
| 611 | // computePartialRzMagic function. |
| 612 | // (3) Right redzone with kAsanAllocaRightMagic. |
| 613 | void handleDynamicAllocaCall(DynamicAllocaCall &AllocaCall); |
| 614 | |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 615 | /// \brief Collect Alloca instructions we want (and can) handle. |
| 616 | void visitAllocaInst(AllocaInst &AI) { |
Anna Zaks | 8ed1d81 | 2015-02-27 03:12:36 +0000 | [diff] [blame^] | 617 | if (!ASan.isInterestingAlloca(AI)) return; |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 618 | |
| 619 | StackAlignment = std::max(StackAlignment, AI.getAlignment()); |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 620 | if (isDynamicAlloca(AI)) |
| 621 | DynamicAllocaVec.push_back(DynamicAllocaCall(&AI)); |
| 622 | else |
| 623 | AllocaVec.push_back(&AI); |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 624 | } |
| 625 | |
Alexey Samsonov | 29dd7f2 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 626 | /// \brief Collect lifetime intrinsic calls to check for use-after-scope |
| 627 | /// errors. |
| 628 | void visitIntrinsicInst(IntrinsicInst &II) { |
Alexey Samsonov | e595e1a | 2014-06-13 17:53:44 +0000 | [diff] [blame] | 629 | if (!ClCheckLifetime) return; |
Alexey Samsonov | 29dd7f2 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 630 | Intrinsic::ID ID = II.getIntrinsicID(); |
| 631 | if (ID != Intrinsic::lifetime_start && |
| 632 | ID != Intrinsic::lifetime_end) |
| 633 | return; |
| 634 | // Found lifetime intrinsic, add ASan instrumentation if necessary. |
| 635 | ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0)); |
| 636 | // If size argument is undefined, don't do anything. |
| 637 | if (Size->isMinusOne()) return; |
| 638 | // Check that size doesn't saturate uint64_t and can |
| 639 | // be stored in IntptrTy. |
| 640 | const uint64_t SizeValue = Size->getValue().getLimitedValue(); |
| 641 | if (SizeValue == ~0ULL || |
| 642 | !ConstantInt::isValueValidForType(IntptrTy, SizeValue)) |
| 643 | return; |
| 644 | // Find alloca instruction that corresponds to llvm.lifetime argument. |
| 645 | AllocaInst *AI = findAllocaForValue(II.getArgOperand(1)); |
| 646 | if (!AI) return; |
| 647 | bool DoPoison = (ID == Intrinsic::lifetime_end); |
Alexey Samsonov | a788b94 | 2013-11-18 14:53:55 +0000 | [diff] [blame] | 648 | AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison}; |
Alexey Samsonov | 29dd7f2 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 649 | AllocaPoisonCallVec.push_back(APC); |
| 650 | } |
| 651 | |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 652 | void visitCallInst(CallInst &CI) { |
| 653 | HasNonEmptyInlineAsm |= |
| 654 | CI.isInlineAsm() && !CI.isIdenticalTo(EmptyInlineAsm.get()); |
| 655 | } |
| 656 | |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 657 | // ---------------------- Helpers. |
| 658 | void initializeCallbacks(Module &M); |
| 659 | |
Yury Gribov | 3ae427d | 2014-12-01 08:47:58 +0000 | [diff] [blame] | 660 | bool doesDominateAllExits(const Instruction *I) const { |
| 661 | for (auto Ret : RetVec) { |
| 662 | if (!ASan.getDominatorTree().dominates(I, Ret)) |
| 663 | return false; |
| 664 | } |
| 665 | return true; |
| 666 | } |
| 667 | |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 668 | bool isDynamicAlloca(AllocaInst &AI) const { |
| 669 | return AI.isArrayAllocation() || !AI.isStaticAlloca(); |
| 670 | } |
Alexey Samsonov | 29dd7f2 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 671 | /// Finds alloca where the value comes from. |
| 672 | AllocaInst *findAllocaForValue(Value *V); |
Craig Topper | 3af9722 | 2014-08-27 05:25:00 +0000 | [diff] [blame] | 673 | void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB, |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 674 | Value *ShadowBase, bool DoPoison); |
Jakub Staszak | 23ec6a9 | 2013-08-09 20:53:48 +0000 | [diff] [blame] | 675 | void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison); |
Kostya Serebryany | bc86efb | 2013-09-17 12:14:50 +0000 | [diff] [blame] | 676 | |
| 677 | void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase, |
| 678 | int Size); |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 679 | Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L, |
| 680 | bool Dynamic); |
| 681 | PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue, |
| 682 | Instruction *ThenTerm, Value *ValueIfFalse); |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 683 | }; |
| 684 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 685 | } // namespace |
| 686 | |
| 687 | char AddressSanitizer::ID = 0; |
Yury Gribov | 3ae427d | 2014-12-01 08:47:58 +0000 | [diff] [blame] | 688 | INITIALIZE_PASS_BEGIN(AddressSanitizer, "asan", |
| 689 | "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", |
| 690 | false, false) |
| 691 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 692 | INITIALIZE_PASS_END(AddressSanitizer, "asan", |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 693 | "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", |
| 694 | false, false) |
Alexey Samsonov | e595e1a | 2014-06-13 17:53:44 +0000 | [diff] [blame] | 695 | FunctionPass *llvm::createAddressSanitizerFunctionPass() { |
| 696 | return new AddressSanitizer(); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 697 | } |
| 698 | |
Kostya Serebryany | dfe9e79 | 2012-11-28 10:31:36 +0000 | [diff] [blame] | 699 | char AddressSanitizerModule::ID = 0; |
| 700 | INITIALIZE_PASS(AddressSanitizerModule, "asan-module", |
| 701 | "AddressSanitizer: detects use-after-free and out-of-bounds bugs." |
| 702 | "ModulePass", false, false) |
Alexey Samsonov | c94285a | 2014-07-08 00:50:49 +0000 | [diff] [blame] | 703 | ModulePass *llvm::createAddressSanitizerModulePass() { |
| 704 | return new AddressSanitizerModule(); |
Alexander Potapenko | c94cf8f | 2012-01-23 11:22:43 +0000 | [diff] [blame] | 705 | } |
| 706 | |
Kostya Serebryany | c4ce5df | 2012-07-16 17:12:07 +0000 | [diff] [blame] | 707 | static size_t TypeSizeToSizeIndex(uint32_t TypeSize) { |
Michael J. Spencer | df1ecbd7 | 2013-05-24 22:23:49 +0000 | [diff] [blame] | 708 | size_t Res = countTrailingZeros(TypeSize / 8); |
Kostya Serebryany | c4ce5df | 2012-07-16 17:12:07 +0000 | [diff] [blame] | 709 | assert(Res < kNumberOfAccessSizes); |
| 710 | return Res; |
| 711 | } |
| 712 | |
Bill Wendling | 58f8cef | 2013-08-06 22:52:42 +0000 | [diff] [blame] | 713 | // \brief Create a constant for Str so that we can pass it to the run-time lib. |
Alexander Potapenko | daf96ae | 2013-12-25 14:22:15 +0000 | [diff] [blame] | 714 | static GlobalVariable *createPrivateGlobalForString( |
| 715 | Module &M, StringRef Str, bool AllowMerging) { |
Chris Lattner | cf9e8f6 | 2012-02-05 02:29:43 +0000 | [diff] [blame] | 716 | Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str); |
Rafael Espindola | daeafb4 | 2014-02-19 17:23:20 +0000 | [diff] [blame] | 717 | // We use private linkage for module-local strings. If they can be merged |
| 718 | // with another one, we set the unnamed_addr attribute. |
Alexander Potapenko | daf96ae | 2013-12-25 14:22:15 +0000 | [diff] [blame] | 719 | GlobalVariable *GV = |
| 720 | new GlobalVariable(M, StrConst->getType(), true, |
Rafael Espindola | daeafb4 | 2014-02-19 17:23:20 +0000 | [diff] [blame] | 721 | GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix); |
| 722 | if (AllowMerging) |
| 723 | GV->setUnnamedAddr(true); |
Kostya Serebryany | 10cc12f | 2013-03-18 09:38:39 +0000 | [diff] [blame] | 724 | GV->setAlignment(1); // Strings may not be merged w/o setting align 1. |
| 725 | return GV; |
Kostya Serebryany | 139a937 | 2012-11-20 14:16:08 +0000 | [diff] [blame] | 726 | } |
| 727 | |
Alexey Samsonov | d9ad5ce | 2014-08-02 00:35:50 +0000 | [diff] [blame] | 728 | /// \brief Create a global describing a source location. |
| 729 | static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M, |
| 730 | LocationMetadata MD) { |
| 731 | Constant *LocData[] = { |
| 732 | createPrivateGlobalForString(M, MD.Filename, true), |
| 733 | ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo), |
| 734 | ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo), |
| 735 | }; |
| 736 | auto LocStruct = ConstantStruct::getAnon(LocData); |
| 737 | auto GV = new GlobalVariable(M, LocStruct->getType(), true, |
| 738 | GlobalValue::PrivateLinkage, LocStruct, |
| 739 | kAsanGenPrefix); |
| 740 | GV->setUnnamedAddr(true); |
| 741 | return GV; |
| 742 | } |
| 743 | |
Kostya Serebryany | 139a937 | 2012-11-20 14:16:08 +0000 | [diff] [blame] | 744 | static bool GlobalWasGeneratedByAsan(GlobalVariable *G) { |
Kostya Serebryany | cb45b12 | 2014-11-19 00:22:58 +0000 | [diff] [blame] | 745 | return G->getName().find(kAsanGenPrefix) == 0 || |
| 746 | G->getName().find(kSanCovGenPrefix) == 0; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 747 | } |
| 748 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 749 | Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) { |
| 750 | // Shadow >> scale |
Alexey Samsonov | 1345d35 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 751 | Shadow = IRB.CreateLShr(Shadow, Mapping.Scale); |
| 752 | if (Mapping.Offset == 0) |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 753 | return Shadow; |
| 754 | // (Shadow >> scale) | offset |
Kostya Serebryany | 4766fe6 | 2013-01-23 12:54:55 +0000 | [diff] [blame] | 755 | if (Mapping.OrShadowOffset) |
| 756 | return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset)); |
| 757 | else |
| 758 | return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset)); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 759 | } |
| 760 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 761 | // Instrument memset/memmove/memcpy |
Kostya Serebryany | 94c81ca | 2014-04-21 11:50:42 +0000 | [diff] [blame] | 762 | void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) { |
| 763 | IRBuilder<> IRB(MI); |
Kostya Serebryany | 94c81ca | 2014-04-21 11:50:42 +0000 | [diff] [blame] | 764 | if (isa<MemTransferInst>(MI)) { |
Evgeniy Stepanov | ed31ca4 | 2014-05-14 10:56:19 +0000 | [diff] [blame] | 765 | IRB.CreateCall3( |
Kostya Serebryany | 94c81ca | 2014-04-21 11:50:42 +0000 | [diff] [blame] | 766 | isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy, |
| 767 | IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()), |
| 768 | IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()), |
| 769 | IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)); |
| 770 | } else if (isa<MemSetInst>(MI)) { |
Evgeniy Stepanov | ed31ca4 | 2014-05-14 10:56:19 +0000 | [diff] [blame] | 771 | IRB.CreateCall3( |
Kostya Serebryany | 94c81ca | 2014-04-21 11:50:42 +0000 | [diff] [blame] | 772 | AsanMemset, |
| 773 | IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()), |
| 774 | IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false), |
| 775 | IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 776 | } |
Kostya Serebryany | 94c81ca | 2014-04-21 11:50:42 +0000 | [diff] [blame] | 777 | MI->eraseFromParent(); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 778 | } |
| 779 | |
Anna Zaks | 8ed1d81 | 2015-02-27 03:12:36 +0000 | [diff] [blame^] | 780 | /// Check if we want (and can) handle this alloca. |
| 781 | bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) const { |
| 782 | return (AI.getAllocatedType()->isSized() && |
| 783 | // alloca() may be called with 0 size, ignore it. |
| 784 | getAllocaSizeInBytes(&AI) > 0 && |
| 785 | // We are only interested in allocas not promotable to registers. |
| 786 | // Promotable allocas are common under -O0. |
| 787 | (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI))); |
| 788 | } |
| 789 | |
| 790 | /// If I is an interesting memory access, return the PointerOperand |
| 791 | /// and set IsWrite/Alignment. Otherwise return nullptr. |
| 792 | Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I, |
| 793 | bool *IsWrite, |
| 794 | unsigned *Alignment) const { |
Alexey Samsonov | 535b6f9 | 2014-07-17 18:48:12 +0000 | [diff] [blame] | 795 | // Skip memory accesses inserted by another instrumentation. |
| 796 | if (I->getMetadata("nosanitize")) |
| 797 | return nullptr; |
Anna Zaks | 8ed1d81 | 2015-02-27 03:12:36 +0000 | [diff] [blame^] | 798 | |
| 799 | Value *PtrOperand = nullptr; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 800 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 801 | if (!ClInstrumentReads) return nullptr; |
Kostya Serebryany | 9024160 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 802 | *IsWrite = false; |
Kostya Serebryany | c7895a8 | 2014-05-23 11:52:07 +0000 | [diff] [blame] | 803 | *Alignment = LI->getAlignment(); |
Anna Zaks | 8ed1d81 | 2015-02-27 03:12:36 +0000 | [diff] [blame^] | 804 | PtrOperand = LI->getPointerOperand(); |
| 805 | } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 806 | if (!ClInstrumentWrites) return nullptr; |
Kostya Serebryany | 9024160 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 807 | *IsWrite = true; |
Kostya Serebryany | c7895a8 | 2014-05-23 11:52:07 +0000 | [diff] [blame] | 808 | *Alignment = SI->getAlignment(); |
Anna Zaks | 8ed1d81 | 2015-02-27 03:12:36 +0000 | [diff] [blame^] | 809 | PtrOperand = SI->getPointerOperand(); |
| 810 | } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 811 | if (!ClInstrumentAtomics) return nullptr; |
Kostya Serebryany | 9024160 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 812 | *IsWrite = true; |
Kostya Serebryany | c7895a8 | 2014-05-23 11:52:07 +0000 | [diff] [blame] | 813 | *Alignment = 0; |
Anna Zaks | 8ed1d81 | 2015-02-27 03:12:36 +0000 | [diff] [blame^] | 814 | PtrOperand = RMW->getPointerOperand(); |
| 815 | } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 816 | if (!ClInstrumentAtomics) return nullptr; |
Kostya Serebryany | 9024160 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 817 | *IsWrite = true; |
Kostya Serebryany | c7895a8 | 2014-05-23 11:52:07 +0000 | [diff] [blame] | 818 | *Alignment = 0; |
Anna Zaks | 8ed1d81 | 2015-02-27 03:12:36 +0000 | [diff] [blame^] | 819 | PtrOperand = XCHG->getPointerOperand(); |
Kostya Serebryany | 9024160 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 820 | } |
Anna Zaks | 8ed1d81 | 2015-02-27 03:12:36 +0000 | [diff] [blame^] | 821 | |
| 822 | // Treat memory accesses to promotable allocas as non-interesting since they |
| 823 | // will not cause memory violations. This greatly speeds up the instrumented |
| 824 | // executable at -O0. |
| 825 | if (ClSkipPromotableAllocas) |
| 826 | if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand)) |
| 827 | return isInterestingAlloca(*AI) ? AI : nullptr; |
| 828 | |
| 829 | return PtrOperand; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 830 | } |
| 831 | |
Kostya Serebryany | 796f655 | 2014-02-27 12:45:36 +0000 | [diff] [blame] | 832 | static bool isPointerOperand(Value *V) { |
| 833 | return V->getType()->isPointerTy() || isa<PtrToIntInst>(V); |
| 834 | } |
| 835 | |
| 836 | // This is a rough heuristic; it may cause both false positives and |
| 837 | // false negatives. The proper implementation requires cooperation with |
| 838 | // the frontend. |
| 839 | static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) { |
| 840 | if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) { |
| 841 | if (!Cmp->isRelational()) |
| 842 | return false; |
| 843 | } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) { |
Kostya Serebryany | cb3f6e1 | 2014-02-27 13:13:59 +0000 | [diff] [blame] | 844 | if (BO->getOpcode() != Instruction::Sub) |
Kostya Serebryany | 796f655 | 2014-02-27 12:45:36 +0000 | [diff] [blame] | 845 | return false; |
| 846 | } else { |
| 847 | return false; |
| 848 | } |
| 849 | if (!isPointerOperand(I->getOperand(0)) || |
| 850 | !isPointerOperand(I->getOperand(1))) |
| 851 | return false; |
| 852 | return true; |
| 853 | } |
| 854 | |
Kostya Serebryany | d3d23be | 2013-10-16 14:06:14 +0000 | [diff] [blame] | 855 | bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) { |
| 856 | // If a global variable does not have dynamic initialization we don't |
| 857 | // have to instrument it. However, if a global does not have initializer |
| 858 | // at all, we assume it has dynamic initializer (in other TU). |
Alexey Samsonov | 08f022a | 2014-07-11 22:36:02 +0000 | [diff] [blame] | 859 | return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit; |
Kostya Serebryany | d3d23be | 2013-10-16 14:06:14 +0000 | [diff] [blame] | 860 | } |
| 861 | |
Kostya Serebryany | 796f655 | 2014-02-27 12:45:36 +0000 | [diff] [blame] | 862 | void |
| 863 | AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) { |
| 864 | IRBuilder<> IRB(I); |
| 865 | Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction; |
| 866 | Value *Param[2] = {I->getOperand(0), I->getOperand(1)}; |
| 867 | for (int i = 0; i < 2; i++) { |
| 868 | if (Param[i]->getType()->isPointerTy()) |
| 869 | Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy); |
| 870 | } |
| 871 | IRB.CreateCall2(F, Param[0], Param[1]); |
| 872 | } |
| 873 | |
Kostya Serebryany | 0c02d26 | 2014-04-16 12:12:19 +0000 | [diff] [blame] | 874 | void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) { |
Axel Naumann | 4a12706 | 2012-09-17 14:20:57 +0000 | [diff] [blame] | 875 | bool IsWrite = false; |
Kostya Serebryany | c7895a8 | 2014-05-23 11:52:07 +0000 | [diff] [blame] | 876 | unsigned Alignment = 0; |
| 877 | Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment); |
Kostya Serebryany | 9024160 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 878 | assert(Addr); |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 879 | if (ClOpt && ClOptGlobals) { |
| 880 | if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) { |
| 881 | // If initialization order checking is disabled, a simple access to a |
| 882 | // dynamically initialized global is always valid. |
Alexey Samsonov | e595e1a | 2014-06-13 17:53:44 +0000 | [diff] [blame] | 883 | if (!ClInitializers || GlobalIsLinkerInitialized(G)) { |
Kostya Serebryany | d3d23be | 2013-10-16 14:06:14 +0000 | [diff] [blame] | 884 | NumOptimizedAccessesToGlobalVar++; |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 885 | return; |
Kostya Serebryany | d3d23be | 2013-10-16 14:06:14 +0000 | [diff] [blame] | 886 | } |
| 887 | } |
| 888 | ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr); |
| 889 | if (CE && CE->isGEPWithNoNotionalOverIndexing()) { |
| 890 | if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) { |
| 891 | if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) { |
| 892 | NumOptimizedAccessesToGlobalArray++; |
| 893 | return; |
| 894 | } |
| 895 | } |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 896 | } |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 897 | } |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 898 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 899 | Type *OrigPtrTy = Addr->getType(); |
| 900 | Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType(); |
| 901 | |
| 902 | assert(OrigTy->isSized()); |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 903 | uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 904 | |
Kostya Serebryany | 3ece9bea | 2013-02-19 11:29:21 +0000 | [diff] [blame] | 905 | assert((TypeSize % 8) == 0); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 906 | |
Kostya Serebryany | d3d23be | 2013-10-16 14:06:14 +0000 | [diff] [blame] | 907 | if (IsWrite) |
| 908 | NumInstrumentedWrites++; |
| 909 | else |
| 910 | NumInstrumentedReads++; |
| 911 | |
Kostya Serebryany | c7895a8 | 2014-05-23 11:52:07 +0000 | [diff] [blame] | 912 | unsigned Granularity = 1 << Mapping.Scale; |
| 913 | // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check |
| 914 | // if the data is properly aligned. |
| 915 | if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 || |
| 916 | TypeSize == 128) && |
| 917 | (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 918 | return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls); |
Kostya Serebryany | c7895a8 | 2014-05-23 11:52:07 +0000 | [diff] [blame] | 919 | // Instrument unusual size or unusual alignment. |
Kostya Serebryany | 3ece9bea | 2013-02-19 11:29:21 +0000 | [diff] [blame] | 920 | // We can not do it with a single check, so we do 1-byte check for the first |
| 921 | // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able |
| 922 | // to report the actual access size. |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 923 | IRBuilder<> IRB(I); |
Kostya Serebryany | 3ece9bea | 2013-02-19 11:29:21 +0000 | [diff] [blame] | 924 | Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8); |
Kostya Serebryany | c9a2c17 | 2014-04-22 11:19:45 +0000 | [diff] [blame] | 925 | Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy); |
| 926 | if (UseCalls) { |
Evgeniy Stepanov | ed31ca4 | 2014-05-14 10:56:19 +0000 | [diff] [blame] | 927 | IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size); |
Kostya Serebryany | c9a2c17 | 2014-04-22 11:19:45 +0000 | [diff] [blame] | 928 | } else { |
| 929 | Value *LastByte = IRB.CreateIntToPtr( |
| 930 | IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)), |
| 931 | OrigPtrTy); |
| 932 | instrumentAddress(I, I, Addr, 8, IsWrite, Size, false); |
| 933 | instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false); |
| 934 | } |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 935 | } |
| 936 | |
Alexander Potapenko | 056e27e | 2012-04-23 10:47:31 +0000 | [diff] [blame] | 937 | // Validate the result of Module::getOrInsertFunction called for an interface |
| 938 | // function of AddressSanitizer. If the instrumented module defines a function |
| 939 | // with the same name, their prototypes must match, otherwise |
| 940 | // getOrInsertFunction returns a bitcast. |
Kostya Serebryany | 20a7997 | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 941 | static Function *checkInterfaceFunction(Constant *FuncOrBitcast) { |
Alexander Potapenko | 056e27e | 2012-04-23 10:47:31 +0000 | [diff] [blame] | 942 | if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast); |
| 943 | FuncOrBitcast->dump(); |
| 944 | report_fatal_error("trying to redefine an AddressSanitizer " |
| 945 | "interface function"); |
| 946 | } |
| 947 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 948 | Instruction *AddressSanitizer::generateCrashCode( |
Kostya Serebryany | fda7a13 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 949 | Instruction *InsertBefore, Value *Addr, |
Kostya Serebryany | 3ece9bea | 2013-02-19 11:29:21 +0000 | [diff] [blame] | 950 | bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) { |
Kostya Serebryany | fda7a13 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 951 | IRBuilder<> IRB(InsertBefore); |
Kostya Serebryany | 3ece9bea | 2013-02-19 11:29:21 +0000 | [diff] [blame] | 952 | CallInst *Call = SizeArgument |
| 953 | ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument) |
| 954 | : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr); |
| 955 | |
Kostya Serebryany | f02c606 | 2012-07-20 09:54:50 +0000 | [diff] [blame] | 956 | // We don't do Call->setDoesNotReturn() because the BB already has |
| 957 | // UnreachableInst at the end. |
| 958 | // This EmptyAsm is required to avoid callback merge. |
| 959 | IRB.CreateCall(EmptyAsm); |
Kostya Serebryany | 3411f2e | 2012-01-06 18:09:21 +0000 | [diff] [blame] | 960 | return Call; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 961 | } |
| 962 | |
Kostya Serebryany | c4ce5df | 2012-07-16 17:12:07 +0000 | [diff] [blame] | 963 | Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong, |
Kostya Serebryany | 874dae6 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 964 | Value *ShadowValue, |
| 965 | uint32_t TypeSize) { |
Alexey Samsonov | 1345d35 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 966 | size_t Granularity = 1 << Mapping.Scale; |
Kostya Serebryany | 874dae6 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 967 | // Addr & (Granularity - 1) |
| 968 | Value *LastAccessedByte = IRB.CreateAnd( |
| 969 | AddrLong, ConstantInt::get(IntptrTy, Granularity - 1)); |
| 970 | // (Addr & (Granularity - 1)) + size - 1 |
| 971 | if (TypeSize / 8 > 1) |
| 972 | LastAccessedByte = IRB.CreateAdd( |
| 973 | LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)); |
| 974 | // (uint8_t) ((Addr & (Granularity-1)) + size - 1) |
| 975 | LastAccessedByte = IRB.CreateIntCast( |
Kostya Serebryany | 1e575ab | 2012-08-15 08:58:58 +0000 | [diff] [blame] | 976 | LastAccessedByte, ShadowValue->getType(), false); |
Kostya Serebryany | 874dae6 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 977 | // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue |
| 978 | return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue); |
| 979 | } |
| 980 | |
Kostya Serebryany | b0e2506 | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 981 | void AddressSanitizer::instrumentAddress(Instruction *OrigIns, |
Kostya Serebryany | 0c02d26 | 2014-04-16 12:12:19 +0000 | [diff] [blame] | 982 | Instruction *InsertBefore, Value *Addr, |
| 983 | uint32_t TypeSize, bool IsWrite, |
| 984 | Value *SizeArgument, bool UseCalls) { |
Kostya Serebryany | 3ece9bea | 2013-02-19 11:29:21 +0000 | [diff] [blame] | 985 | IRBuilder<> IRB(InsertBefore); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 986 | Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy); |
Kostya Serebryany | 0c02d26 | 2014-04-16 12:12:19 +0000 | [diff] [blame] | 987 | size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize); |
| 988 | |
| 989 | if (UseCalls) { |
Kostya Serebryany | 94f57d19 | 2014-04-21 10:28:13 +0000 | [diff] [blame] | 990 | IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex], |
| 991 | AddrLong); |
Kostya Serebryany | 0c02d26 | 2014-04-16 12:12:19 +0000 | [diff] [blame] | 992 | return; |
| 993 | } |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 994 | |
| 995 | Type *ShadowTy = IntegerType::get( |
Alexey Samsonov | 1345d35 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 996 | *C, std::max(8U, TypeSize >> Mapping.Scale)); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 997 | Type *ShadowPtrTy = PointerType::get(ShadowTy, 0); |
| 998 | Value *ShadowPtr = memToShadow(AddrLong, IRB); |
| 999 | Value *CmpVal = Constant::getNullValue(ShadowTy); |
| 1000 | Value *ShadowValue = IRB.CreateLoad( |
| 1001 | IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy)); |
| 1002 | |
| 1003 | Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal); |
Alexey Samsonov | 1345d35 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 1004 | size_t Granularity = 1 << Mapping.Scale; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1005 | TerminatorInst *CrashTerm = nullptr; |
Kostya Serebryany | fda7a13 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 1006 | |
Kostya Serebryany | 1e575ab | 2012-08-15 08:58:58 +0000 | [diff] [blame] | 1007 | if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) { |
Kostya Serebryany | ad23852 | 2014-09-02 21:46:51 +0000 | [diff] [blame] | 1008 | // We use branch weights for the slow path check, to indicate that the slow |
| 1009 | // path is rarely taken. This seems to be the case for SPEC benchmarks. |
Evgeniy Stepanov | 8eb77d8 | 2012-10-19 10:48:31 +0000 | [diff] [blame] | 1010 | TerminatorInst *CheckTerm = |
Kostya Serebryany | ad23852 | 2014-09-02 21:46:51 +0000 | [diff] [blame] | 1011 | SplitBlockAndInsertIfThen(Cmp, InsertBefore, false, |
| 1012 | MDBuilder(*C).createBranchWeights(1, 100000)); |
Kostya Serebryany | fda7a13 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 1013 | assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional()); |
Kostya Serebryany | f02c606 | 2012-07-20 09:54:50 +0000 | [diff] [blame] | 1014 | BasicBlock *NextBB = CheckTerm->getSuccessor(0); |
Kostya Serebryany | 874dae6 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 1015 | IRB.SetInsertPoint(CheckTerm); |
| 1016 | Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize); |
Kostya Serebryany | b0e2506 | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 1017 | BasicBlock *CrashBlock = |
| 1018 | BasicBlock::Create(*C, "", NextBB->getParent(), NextBB); |
Kostya Serebryany | fda7a13 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 1019 | CrashTerm = new UnreachableInst(*C, CrashBlock); |
Kostya Serebryany | f02c606 | 2012-07-20 09:54:50 +0000 | [diff] [blame] | 1020 | BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2); |
| 1021 | ReplaceInstWithInst(CheckTerm, NewTerm); |
Kostya Serebryany | 874dae6 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 1022 | } else { |
Evgeniy Stepanov | a9164e9 | 2013-12-19 13:29:56 +0000 | [diff] [blame] | 1023 | CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1024 | } |
Kostya Serebryany | fda7a13 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 1025 | |
Kostya Serebryany | 3ece9bea | 2013-02-19 11:29:21 +0000 | [diff] [blame] | 1026 | Instruction *Crash = generateCrashCode( |
| 1027 | CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument); |
Kostya Serebryany | fda7a13 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 1028 | Crash->setDebugLoc(OrigIns->getDebugLoc()); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1029 | } |
| 1030 | |
Alexey Samsonov | 96e239f | 2014-05-29 00:51:15 +0000 | [diff] [blame] | 1031 | void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit, |
| 1032 | GlobalValue *ModuleName) { |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1033 | // Set up the arguments to our poison/unpoison functions. |
Alexey Samsonov | 96e239f | 2014-05-29 00:51:15 +0000 | [diff] [blame] | 1034 | IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt()); |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1035 | |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1036 | // Add a call to poison all external globals before the given function starts. |
Alexey Samsonov | e1e26bf | 2013-03-26 13:05:41 +0000 | [diff] [blame] | 1037 | Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy); |
| 1038 | IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr); |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1039 | |
| 1040 | // Add calls to unpoison all globals before each return instruction. |
Alexey Samsonov | 96e239f | 2014-05-29 00:51:15 +0000 | [diff] [blame] | 1041 | for (auto &BB : GlobalInit.getBasicBlockList()) |
| 1042 | if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1043 | CallInst::Create(AsanUnpoisonGlobals, "", RI); |
Alexey Samsonov | 96e239f | 2014-05-29 00:51:15 +0000 | [diff] [blame] | 1044 | } |
| 1045 | |
| 1046 | void AddressSanitizerModule::createInitializerPoisonCalls( |
| 1047 | Module &M, GlobalValue *ModuleName) { |
| 1048 | GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors"); |
| 1049 | |
| 1050 | ConstantArray *CA = cast<ConstantArray>(GV->getInitializer()); |
| 1051 | for (Use &OP : CA->operands()) { |
| 1052 | if (isa<ConstantAggregateZero>(OP)) |
| 1053 | continue; |
| 1054 | ConstantStruct *CS = cast<ConstantStruct>(OP); |
| 1055 | |
| 1056 | // Must have a function or null ptr. |
Alexey Samsonov | 96e239f | 2014-05-29 00:51:15 +0000 | [diff] [blame] | 1057 | if (Function* F = dyn_cast<Function>(CS->getOperand(1))) { |
Kostya Serebryany | 34ddf87 | 2014-09-24 22:41:55 +0000 | [diff] [blame] | 1058 | if (F->getName() == kAsanModuleCtorName) continue; |
| 1059 | ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0)); |
| 1060 | // Don't instrument CTORs that will run before asan.module_ctor. |
| 1061 | if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue; |
| 1062 | poisonOneInitializer(*F, ModuleName); |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1063 | } |
| 1064 | } |
| 1065 | } |
| 1066 | |
Kostya Serebryany | dfe9e79 | 2012-11-28 10:31:36 +0000 | [diff] [blame] | 1067 | bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) { |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1068 | Type *Ty = cast<PointerType>(G->getType())->getElementType(); |
Kostya Serebryany | 2034335 | 2012-10-17 13:40:06 +0000 | [diff] [blame] | 1069 | DEBUG(dbgs() << "GLOBAL: " << *G << "\n"); |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1070 | |
Alexey Samsonov | 08f022a | 2014-07-11 22:36:02 +0000 | [diff] [blame] | 1071 | if (GlobalsMD.get(G).IsBlacklisted) return false; |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1072 | if (!Ty->isSized()) return false; |
| 1073 | if (!G->hasInitializer()) return false; |
Kostya Serebryany | 139a937 | 2012-11-20 14:16:08 +0000 | [diff] [blame] | 1074 | if (GlobalWasGeneratedByAsan(G)) return false; // Our own global. |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1075 | // Touch only those globals that will not be defined in other modules. |
Timur Iskhodzhanov | e40fb37 | 2014-07-09 08:35:33 +0000 | [diff] [blame] | 1076 | // Don't handle ODR linkage types and COMDATs since other modules may be built |
| 1077 | // without ASan. |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1078 | if (G->getLinkage() != GlobalVariable::ExternalLinkage && |
| 1079 | G->getLinkage() != GlobalVariable::PrivateLinkage && |
| 1080 | G->getLinkage() != GlobalVariable::InternalLinkage) |
| 1081 | return false; |
Timur Iskhodzhanov | e40fb37 | 2014-07-09 08:35:33 +0000 | [diff] [blame] | 1082 | if (G->hasComdat()) |
| 1083 | return false; |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1084 | // Two problems with thread-locals: |
| 1085 | // - The address of the main thread's copy can't be computed at link-time. |
| 1086 | // - Need to poison all copies, not just the main thread's one. |
| 1087 | if (G->isThreadLocal()) |
| 1088 | return false; |
Kostya Serebryany | 4fb7801 | 2013-12-06 09:00:17 +0000 | [diff] [blame] | 1089 | // For now, just ignore this Global if the alignment is large. |
| 1090 | if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false; |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1091 | |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1092 | if (G->hasSection()) { |
| 1093 | StringRef Section(G->getSection()); |
Kuba Brecka | 086e34b | 2014-12-05 21:32:46 +0000 | [diff] [blame] | 1094 | |
Kuba Brecka | 1001bb5 | 2014-12-05 22:19:18 +0000 | [diff] [blame] | 1095 | if (TargetTriple.isOSBinFormatMachO()) { |
| 1096 | StringRef ParsedSegment, ParsedSection; |
| 1097 | unsigned TAA = 0, StubSize = 0; |
| 1098 | bool TAAParsed; |
| 1099 | std::string ErrorCode = |
| 1100 | MCSectionMachO::ParseSectionSpecifier(Section, ParsedSegment, |
| 1101 | ParsedSection, TAA, TAAParsed, |
| 1102 | StubSize); |
| 1103 | if (!ErrorCode.empty()) { |
| 1104 | report_fatal_error("Invalid section specifier '" + ParsedSection + |
| 1105 | "': " + ErrorCode + "."); |
| 1106 | } |
| 1107 | |
| 1108 | // Ignore the globals from the __OBJC section. The ObjC runtime assumes |
| 1109 | // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to |
| 1110 | // them. |
| 1111 | if (ParsedSegment == "__OBJC" || |
| 1112 | (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) { |
| 1113 | DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n"); |
| 1114 | return false; |
| 1115 | } |
| 1116 | // See http://code.google.com/p/address-sanitizer/issues/detail?id=32 |
| 1117 | // Constant CFString instances are compiled in the following way: |
| 1118 | // -- the string buffer is emitted into |
| 1119 | // __TEXT,__cstring,cstring_literals |
| 1120 | // -- the constant NSConstantString structure referencing that buffer |
| 1121 | // is placed into __DATA,__cfstring |
| 1122 | // Therefore there's no point in placing redzones into __DATA,__cfstring. |
| 1123 | // Moreover, it causes the linker to crash on OS X 10.7 |
| 1124 | if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") { |
| 1125 | DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n"); |
| 1126 | return false; |
| 1127 | } |
| 1128 | // The linker merges the contents of cstring_literals and removes the |
| 1129 | // trailing zeroes. |
| 1130 | if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) { |
| 1131 | DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n"); |
| 1132 | return false; |
| 1133 | } |
| 1134 | } |
Timur Iskhodzhanov | 9dbc206 | 2014-05-05 14:28:38 +0000 | [diff] [blame] | 1135 | |
| 1136 | // Callbacks put into the CRT initializer/terminator sections |
| 1137 | // should not be instrumented. |
| 1138 | // See https://code.google.com/p/address-sanitizer/issues/detail?id=305 |
| 1139 | // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx |
| 1140 | if (Section.startswith(".CRT")) { |
| 1141 | DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n"); |
| 1142 | return false; |
| 1143 | } |
| 1144 | |
Alexander Potapenko | 04969e8 | 2014-03-20 10:48:34 +0000 | [diff] [blame] | 1145 | // Globals from llvm.metadata aren't emitted, do not instrument them. |
| 1146 | if (Section == "llvm.metadata") return false; |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1147 | } |
| 1148 | |
| 1149 | return true; |
| 1150 | } |
| 1151 | |
Alexey Samsonov | 788381b | 2012-12-25 12:28:20 +0000 | [diff] [blame] | 1152 | void AddressSanitizerModule::initializeCallbacks(Module &M) { |
| 1153 | IRBuilder<> IRB(*C); |
| 1154 | // Declare our poisoning and unpoisoning functions. |
| 1155 | AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction( |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1156 | kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr)); |
Alexey Samsonov | 788381b | 2012-12-25 12:28:20 +0000 | [diff] [blame] | 1157 | AsanPoisonGlobals->setLinkage(Function::ExternalLinkage); |
| 1158 | AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction( |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1159 | kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr)); |
Alexey Samsonov | 788381b | 2012-12-25 12:28:20 +0000 | [diff] [blame] | 1160 | AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage); |
| 1161 | // Declare functions that register/unregister globals. |
| 1162 | AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction( |
| 1163 | kAsanRegisterGlobalsName, IRB.getVoidTy(), |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1164 | IntptrTy, IntptrTy, nullptr)); |
Alexey Samsonov | 788381b | 2012-12-25 12:28:20 +0000 | [diff] [blame] | 1165 | AsanRegisterGlobals->setLinkage(Function::ExternalLinkage); |
| 1166 | AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction( |
| 1167 | kAsanUnregisterGlobalsName, |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1168 | IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr)); |
Alexey Samsonov | 788381b | 2012-12-25 12:28:20 +0000 | [diff] [blame] | 1169 | AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage); |
| 1170 | } |
| 1171 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1172 | // This function replaces all global variables with new variables that have |
| 1173 | // trailing redzones. It also creates a function that poisons |
| 1174 | // redzones and inserts this function into llvm.global_ctors. |
Evgeniy Stepanov | 19f75fc | 2014-06-03 14:16:00 +0000 | [diff] [blame] | 1175 | bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) { |
Alexey Samsonov | 4f319cc | 2014-07-02 16:54:41 +0000 | [diff] [blame] | 1176 | GlobalsMD.init(M); |
Kostya Serebryany | 20a7997 | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 1177 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1178 | SmallVector<GlobalVariable *, 16> GlobalsToChange; |
| 1179 | |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1180 | for (auto &G : M.globals()) { |
| 1181 | if (ShouldInstrumentGlobal(&G)) |
| 1182 | GlobalsToChange.push_back(&G); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1183 | } |
| 1184 | |
| 1185 | size_t n = GlobalsToChange.size(); |
| 1186 | if (n == 0) return false; |
| 1187 | |
| 1188 | // A global is described by a structure |
| 1189 | // size_t beg; |
| 1190 | // size_t size; |
| 1191 | // size_t size_with_redzone; |
| 1192 | // const char *name; |
Kostya Serebryany | bd016bb | 2013-03-18 08:05:29 +0000 | [diff] [blame] | 1193 | // const char *module_name; |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1194 | // size_t has_dynamic_init; |
Alexey Samsonov | 4f319cc | 2014-07-02 16:54:41 +0000 | [diff] [blame] | 1195 | // void *source_location; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1196 | // We initialize an array of such structures and pass it to a run-time call. |
Alexey Samsonov | 4f319cc | 2014-07-02 16:54:41 +0000 | [diff] [blame] | 1197 | StructType *GlobalStructTy = |
| 1198 | StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy, |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1199 | IntptrTy, IntptrTy, nullptr); |
Rafael Espindola | 44fee4e | 2013-10-01 13:32:03 +0000 | [diff] [blame] | 1200 | SmallVector<Constant *, 16> Initializers(n); |
Kostya Serebryany | 20a7997 | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 1201 | |
Alexey Samsonov | e1e26bf | 2013-03-26 13:05:41 +0000 | [diff] [blame] | 1202 | bool HasDynamicallyInitializedGlobals = false; |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1203 | |
Alexey Samsonov | e1e26bf | 2013-03-26 13:05:41 +0000 | [diff] [blame] | 1204 | // We shouldn't merge same module names, as this string serves as unique |
| 1205 | // module ID in runtime. |
Alexander Potapenko | daf96ae | 2013-12-25 14:22:15 +0000 | [diff] [blame] | 1206 | GlobalVariable *ModuleName = createPrivateGlobalForString( |
| 1207 | M, M.getModuleIdentifier(), /*AllowMerging*/false); |
Kostya Serebryany | bd016bb | 2013-03-18 08:05:29 +0000 | [diff] [blame] | 1208 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1209 | for (size_t i = 0; i < n; i++) { |
Kostya Serebryany | e35d59a | 2013-01-24 10:43:50 +0000 | [diff] [blame] | 1210 | static const uint64_t kMaxGlobalRedzone = 1 << 18; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1211 | GlobalVariable *G = GlobalsToChange[i]; |
Alexey Samsonov | 15c9669 | 2014-07-12 00:42:52 +0000 | [diff] [blame] | 1212 | |
| 1213 | auto MD = GlobalsMD.get(G); |
Alexey Samsonov | d9ad5ce | 2014-08-02 00:35:50 +0000 | [diff] [blame] | 1214 | // Create string holding the global name (use global name from metadata |
| 1215 | // if it's available, otherwise just write the name of global variable). |
| 1216 | GlobalVariable *Name = createPrivateGlobalForString( |
| 1217 | M, MD.Name.empty() ? G->getName() : MD.Name, |
| 1218 | /*AllowMerging*/ true); |
Alexey Samsonov | 15c9669 | 2014-07-12 00:42:52 +0000 | [diff] [blame] | 1219 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1220 | PointerType *PtrTy = cast<PointerType>(G->getType()); |
| 1221 | Type *Ty = PtrTy->getElementType(); |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 1222 | uint64_t SizeInBytes = DL->getTypeAllocSize(Ty); |
Kostya Serebryany | 4fb7801 | 2013-12-06 09:00:17 +0000 | [diff] [blame] | 1223 | uint64_t MinRZ = MinRedzoneSizeForGlobal(); |
Kostya Serebryany | 87191f6 | 2013-01-24 10:35:40 +0000 | [diff] [blame] | 1224 | // MinRZ <= RZ <= kMaxGlobalRedzone |
| 1225 | // and trying to make RZ to be ~ 1/4 of SizeInBytes. |
Kostya Serebryany | e35d59a | 2013-01-24 10:43:50 +0000 | [diff] [blame] | 1226 | uint64_t RZ = std::max(MinRZ, |
Kostya Serebryany | 87191f6 | 2013-01-24 10:35:40 +0000 | [diff] [blame] | 1227 | std::min(kMaxGlobalRedzone, |
| 1228 | (SizeInBytes / MinRZ / 4) * MinRZ)); |
| 1229 | uint64_t RightRedzoneSize = RZ; |
| 1230 | // Round up to MinRZ |
| 1231 | if (SizeInBytes % MinRZ) |
| 1232 | RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ); |
| 1233 | assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1234 | Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize); |
| 1235 | |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1236 | StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1237 | Constant *NewInitializer = ConstantStruct::get( |
| 1238 | NewTy, G->getInitializer(), |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1239 | Constant::getNullValue(RightRedZoneTy), nullptr); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1240 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1241 | // Create a new global variable with enough space for a redzone. |
Bill Wendling | 58f8cef | 2013-08-06 22:52:42 +0000 | [diff] [blame] | 1242 | GlobalValue::LinkageTypes Linkage = G->getLinkage(); |
| 1243 | if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage) |
| 1244 | Linkage = GlobalValue::InternalLinkage; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1245 | GlobalVariable *NewGlobal = new GlobalVariable( |
Bill Wendling | 58f8cef | 2013-08-06 22:52:42 +0000 | [diff] [blame] | 1246 | M, NewTy, G->isConstant(), Linkage, |
Hans Wennborg | cbe34b4 | 2012-06-23 11:37:03 +0000 | [diff] [blame] | 1247 | NewInitializer, "", G, G->getThreadLocalMode()); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1248 | NewGlobal->copyAttributesFrom(G); |
Kostya Serebryany | 87191f6 | 2013-01-24 10:35:40 +0000 | [diff] [blame] | 1249 | NewGlobal->setAlignment(MinRZ); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1250 | |
| 1251 | Value *Indices2[2]; |
| 1252 | Indices2[0] = IRB.getInt32(0); |
| 1253 | Indices2[1] = IRB.getInt32(0); |
| 1254 | |
| 1255 | G->replaceAllUsesWith( |
Kostya Serebryany | 7471d13 | 2012-01-28 04:27:16 +0000 | [diff] [blame] | 1256 | ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true)); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1257 | NewGlobal->takeName(G); |
| 1258 | G->eraseFromParent(); |
| 1259 | |
Alexey Samsonov | d9ad5ce | 2014-08-02 00:35:50 +0000 | [diff] [blame] | 1260 | Constant *SourceLoc; |
| 1261 | if (!MD.SourceLoc.empty()) { |
| 1262 | auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc); |
| 1263 | SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy); |
| 1264 | } else { |
| 1265 | SourceLoc = ConstantInt::get(IntptrTy, 0); |
| 1266 | } |
| 1267 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1268 | Initializers[i] = ConstantStruct::get( |
Alexey Samsonov | 4f319cc | 2014-07-02 16:54:41 +0000 | [diff] [blame] | 1269 | GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy), |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1270 | ConstantInt::get(IntptrTy, SizeInBytes), |
| 1271 | ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize), |
| 1272 | ConstantExpr::getPointerCast(Name, IntptrTy), |
Kostya Serebryany | bd016bb | 2013-03-18 08:05:29 +0000 | [diff] [blame] | 1273 | ConstantExpr::getPointerCast(ModuleName, IntptrTy), |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1274 | ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr); |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1275 | |
Alexey Samsonov | 08f022a | 2014-07-11 22:36:02 +0000 | [diff] [blame] | 1276 | if (ClInitializers && MD.IsDynInit) |
Alexey Samsonov | e1e26bf | 2013-03-26 13:05:41 +0000 | [diff] [blame] | 1277 | HasDynamicallyInitializedGlobals = true; |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1278 | |
Kostya Serebryany | 2034335 | 2012-10-17 13:40:06 +0000 | [diff] [blame] | 1279 | DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n"); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1280 | } |
| 1281 | |
| 1282 | ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n); |
| 1283 | GlobalVariable *AllGlobals = new GlobalVariable( |
Bill Wendling | 58f8cef | 2013-08-06 22:52:42 +0000 | [diff] [blame] | 1284 | M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage, |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1285 | ConstantArray::get(ArrayOfGlobalStructTy, Initializers), ""); |
| 1286 | |
Kostya Serebryany | f4be019 | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 1287 | // Create calls for poisoning before initializers run and unpoisoning after. |
Alexey Samsonov | e595e1a | 2014-06-13 17:53:44 +0000 | [diff] [blame] | 1288 | if (HasDynamicallyInitializedGlobals) |
Alexey Samsonov | e1e26bf | 2013-03-26 13:05:41 +0000 | [diff] [blame] | 1289 | createInitializerPoisonCalls(M, ModuleName); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1290 | IRB.CreateCall2(AsanRegisterGlobals, |
| 1291 | IRB.CreatePointerCast(AllGlobals, IntptrTy), |
| 1292 | ConstantInt::get(IntptrTy, n)); |
| 1293 | |
Kostya Serebryany | cd1aba8 | 2011-12-15 21:59:03 +0000 | [diff] [blame] | 1294 | // We also need to unregister globals at the end, e.g. when a shared library |
| 1295 | // gets closed. |
| 1296 | Function *AsanDtorFunction = Function::Create( |
| 1297 | FunctionType::get(Type::getVoidTy(*C), false), |
| 1298 | GlobalValue::InternalLinkage, kAsanModuleDtorName, &M); |
| 1299 | BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction); |
| 1300 | IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB)); |
Kostya Serebryany | cd1aba8 | 2011-12-15 21:59:03 +0000 | [diff] [blame] | 1301 | IRB_Dtor.CreateCall2(AsanUnregisterGlobals, |
| 1302 | IRB.CreatePointerCast(AllGlobals, IntptrTy), |
| 1303 | ConstantInt::get(IntptrTy, n)); |
Alexey Samsonov | 1f64750 | 2014-05-29 01:10:14 +0000 | [diff] [blame] | 1304 | appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority); |
Kostya Serebryany | cd1aba8 | 2011-12-15 21:59:03 +0000 | [diff] [blame] | 1305 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1306 | DEBUG(dbgs() << M); |
| 1307 | return true; |
| 1308 | } |
| 1309 | |
Evgeniy Stepanov | 19f75fc | 2014-06-03 14:16:00 +0000 | [diff] [blame] | 1310 | bool AddressSanitizerModule::runOnModule(Module &M) { |
| 1311 | DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); |
| 1312 | if (!DLP) |
| 1313 | return false; |
| 1314 | DL = &DLP->getDataLayout(); |
Evgeniy Stepanov | 19f75fc | 2014-06-03 14:16:00 +0000 | [diff] [blame] | 1315 | C = &(M.getContext()); |
| 1316 | int LongSize = DL->getPointerSizeInBits(); |
| 1317 | IntptrTy = Type::getIntNTy(*C, LongSize); |
Kuba Brecka | 1001bb5 | 2014-12-05 22:19:18 +0000 | [diff] [blame] | 1318 | TargetTriple = Triple(M.getTargetTriple()); |
| 1319 | Mapping = getShadowMapping(TargetTriple, LongSize); |
Evgeniy Stepanov | 19f75fc | 2014-06-03 14:16:00 +0000 | [diff] [blame] | 1320 | initializeCallbacks(M); |
| 1321 | |
| 1322 | bool Changed = false; |
| 1323 | |
| 1324 | Function *CtorFunc = M.getFunction(kAsanModuleCtorName); |
| 1325 | assert(CtorFunc); |
| 1326 | IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator()); |
| 1327 | |
Alexey Samsonov | c94285a | 2014-07-08 00:50:49 +0000 | [diff] [blame] | 1328 | if (ClGlobals) |
| 1329 | Changed |= InstrumentGlobals(IRB, M); |
Evgeniy Stepanov | 19f75fc | 2014-06-03 14:16:00 +0000 | [diff] [blame] | 1330 | |
| 1331 | return Changed; |
| 1332 | } |
| 1333 | |
Kostya Serebryany | 4b929da | 2012-11-29 09:54:21 +0000 | [diff] [blame] | 1334 | void AddressSanitizer::initializeCallbacks(Module &M) { |
| 1335 | IRBuilder<> IRB(*C); |
Kostya Serebryany | 4273bb0 | 2012-07-16 14:09:42 +0000 | [diff] [blame] | 1336 | // Create __asan_report* callbacks. |
| 1337 | for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) { |
| 1338 | for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes; |
| 1339 | AccessSizeIndex++) { |
| 1340 | // IsWrite and TypeSize are encoded in the function name. |
Kostya Serebryany | 0c02d26 | 2014-04-16 12:12:19 +0000 | [diff] [blame] | 1341 | std::string Suffix = |
Kostya Serebryany | 4273bb0 | 2012-07-16 14:09:42 +0000 | [diff] [blame] | 1342 | (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex); |
Kostya Serebryany | 157a515 | 2012-11-07 12:42:18 +0000 | [diff] [blame] | 1343 | AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = |
Kostya Serebryany | 0c02d26 | 2014-04-16 12:12:19 +0000 | [diff] [blame] | 1344 | checkInterfaceFunction( |
| 1345 | M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix, |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1346 | IRB.getVoidTy(), IntptrTy, nullptr)); |
Kostya Serebryany | 0c02d26 | 2014-04-16 12:12:19 +0000 | [diff] [blame] | 1347 | AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] = |
| 1348 | checkInterfaceFunction( |
| 1349 | M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix, |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1350 | IRB.getVoidTy(), IntptrTy, nullptr)); |
Kostya Serebryany | 4273bb0 | 2012-07-16 14:09:42 +0000 | [diff] [blame] | 1351 | } |
| 1352 | } |
Kostya Serebryany | 3ece9bea | 2013-02-19 11:29:21 +0000 | [diff] [blame] | 1353 | AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction( |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1354 | kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr)); |
Kostya Serebryany | 3ece9bea | 2013-02-19 11:29:21 +0000 | [diff] [blame] | 1355 | AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction( |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1356 | kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr)); |
Kostya Serebryany | b0e2506 | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 1357 | |
Kostya Serebryany | 86332c0 | 2014-04-21 07:10:43 +0000 | [diff] [blame] | 1358 | AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction( |
| 1359 | M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN", |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1360 | IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr)); |
Kostya Serebryany | 86332c0 | 2014-04-21 07:10:43 +0000 | [diff] [blame] | 1361 | AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction( |
| 1362 | M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN", |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1363 | IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr)); |
Kostya Serebryany | 86332c0 | 2014-04-21 07:10:43 +0000 | [diff] [blame] | 1364 | |
Kostya Serebryany | 94c81ca | 2014-04-21 11:50:42 +0000 | [diff] [blame] | 1365 | AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction( |
| 1366 | ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(), |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1367 | IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr)); |
Kostya Serebryany | 94c81ca | 2014-04-21 11:50:42 +0000 | [diff] [blame] | 1368 | AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction( |
| 1369 | ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(), |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1370 | IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr)); |
Kostya Serebryany | 94c81ca | 2014-04-21 11:50:42 +0000 | [diff] [blame] | 1371 | AsanMemset = checkInterfaceFunction(M.getOrInsertFunction( |
| 1372 | ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(), |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1373 | IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr)); |
Kostya Serebryany | 94c81ca | 2014-04-21 11:50:42 +0000 | [diff] [blame] | 1374 | |
| 1375 | AsanHandleNoReturnFunc = checkInterfaceFunction( |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1376 | M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr)); |
Kostya Serebryany | 4f8f0c5 | 2014-10-27 18:13:56 +0000 | [diff] [blame] | 1377 | |
Kostya Serebryany | 796f655 | 2014-02-27 12:45:36 +0000 | [diff] [blame] | 1378 | AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction( |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1379 | kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr)); |
Kostya Serebryany | 796f655 | 2014-02-27 12:45:36 +0000 | [diff] [blame] | 1380 | AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction( |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1381 | kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr)); |
Kostya Serebryany | f02c606 | 2012-07-20 09:54:50 +0000 | [diff] [blame] | 1382 | // We insert an empty inline asm after __asan_report* to avoid callback merge. |
| 1383 | EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false), |
| 1384 | StringRef(""), StringRef(""), |
| 1385 | /*hasSideEffects=*/true); |
Kostya Serebryany | 4b929da | 2012-11-29 09:54:21 +0000 | [diff] [blame] | 1386 | } |
| 1387 | |
| 1388 | // virtual |
| 1389 | bool AddressSanitizer::doInitialization(Module &M) { |
| 1390 | // Initialize the private fields. No one has accessed them before. |
Rafael Espindola | 9351251 | 2014-02-25 17:30:31 +0000 | [diff] [blame] | 1391 | DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); |
| 1392 | if (!DLP) |
Evgeniy Stepanov | 119cb2e | 2014-04-23 12:51:32 +0000 | [diff] [blame] | 1393 | report_fatal_error("data layout missing"); |
Rafael Espindola | 9351251 | 2014-02-25 17:30:31 +0000 | [diff] [blame] | 1394 | DL = &DLP->getDataLayout(); |
| 1395 | |
Alexey Samsonov | 4f319cc | 2014-07-02 16:54:41 +0000 | [diff] [blame] | 1396 | GlobalsMD.init(M); |
Kostya Serebryany | 4b929da | 2012-11-29 09:54:21 +0000 | [diff] [blame] | 1397 | |
| 1398 | C = &(M.getContext()); |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 1399 | LongSize = DL->getPointerSizeInBits(); |
Kostya Serebryany | 4b929da | 2012-11-29 09:54:21 +0000 | [diff] [blame] | 1400 | IntptrTy = Type::getIntNTy(*C, LongSize); |
Kuba Brecka | 1001bb5 | 2014-12-05 22:19:18 +0000 | [diff] [blame] | 1401 | TargetTriple = Triple(M.getTargetTriple()); |
Kostya Serebryany | 4b929da | 2012-11-29 09:54:21 +0000 | [diff] [blame] | 1402 | |
| 1403 | AsanCtorFunction = Function::Create( |
| 1404 | FunctionType::get(Type::getVoidTy(*C), false), |
| 1405 | GlobalValue::InternalLinkage, kAsanModuleCtorName, &M); |
| 1406 | BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction); |
| 1407 | // call __asan_init in the module ctor. |
| 1408 | IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB)); |
| 1409 | AsanInitFunction = checkInterfaceFunction( |
Reid Kleckner | 971c3ea | 2014-11-13 22:55:19 +0000 | [diff] [blame] | 1410 | M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), nullptr)); |
Kostya Serebryany | 4b929da | 2012-11-29 09:54:21 +0000 | [diff] [blame] | 1411 | AsanInitFunction->setLinkage(Function::ExternalLinkage); |
| 1412 | IRB.CreateCall(AsanInitFunction); |
Kostya Serebryany | 4273bb0 | 2012-07-16 14:09:42 +0000 | [diff] [blame] | 1413 | |
Kuba Brecka | 1001bb5 | 2014-12-05 22:19:18 +0000 | [diff] [blame] | 1414 | Mapping = getShadowMapping(TargetTriple, LongSize); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1415 | |
Alexey Samsonov | 1f64750 | 2014-05-29 01:10:14 +0000 | [diff] [blame] | 1416 | appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority); |
Kostya Serebryany | b0e2506 | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 1417 | return true; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1418 | } |
| 1419 | |
Kostya Serebryany | 22ddcfd | 2012-01-30 23:50:10 +0000 | [diff] [blame] | 1420 | bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) { |
| 1421 | // For each NSObject descendant having a +load method, this method is invoked |
| 1422 | // by the ObjC runtime before any of the static constructors is called. |
| 1423 | // Therefore we need to instrument such methods with a call to __asan_init |
| 1424 | // at the beginning in order to initialize our runtime before any access to |
| 1425 | // the shadow memory. |
| 1426 | // We cannot just ignore these methods, because they may call other |
| 1427 | // instrumented functions. |
| 1428 | if (F.getName().find(" load]") != std::string::npos) { |
| 1429 | IRBuilder<> IRB(F.begin()->begin()); |
| 1430 | IRB.CreateCall(AsanInitFunction); |
| 1431 | return true; |
| 1432 | } |
| 1433 | return false; |
| 1434 | } |
| 1435 | |
Kostya Serebryany | b0e2506 | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 1436 | bool AddressSanitizer::runOnFunction(Function &F) { |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1437 | if (&F == AsanCtorFunction) return false; |
Kostya Serebryany | 6b5b58d | 2013-03-18 07:33:49 +0000 | [diff] [blame] | 1438 | if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false; |
Kostya Serebryany | 2034335 | 2012-10-17 13:40:06 +0000 | [diff] [blame] | 1439 | DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n"); |
Kostya Serebryany | 4b929da | 2012-11-29 09:54:21 +0000 | [diff] [blame] | 1440 | initializeCallbacks(*F.getParent()); |
Kostya Serebryany | 22ddcfd | 2012-01-30 23:50:10 +0000 | [diff] [blame] | 1441 | |
Yury Gribov | 3ae427d | 2014-12-01 08:47:58 +0000 | [diff] [blame] | 1442 | DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 1443 | |
Kostya Serebryany | cf880b9 | 2013-02-26 06:58:09 +0000 | [diff] [blame] | 1444 | // If needed, insert __asan_init before checking for SanitizeAddress attr. |
Kostya Serebryany | 22ddcfd | 2012-01-30 23:50:10 +0000 | [diff] [blame] | 1445 | maybeInsertAsanInitAtFunctionEntry(F); |
| 1446 | |
Alexey Samsonov | 6d8bab8 | 2014-06-02 18:08:27 +0000 | [diff] [blame] | 1447 | if (!F.hasFnAttribute(Attribute::SanitizeAddress)) |
Bill Wendling | c9b22d7 | 2012-10-09 07:45:08 +0000 | [diff] [blame] | 1448 | return false; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1449 | |
| 1450 | if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) |
| 1451 | return false; |
Bill Wendling | c9b22d7 | 2012-10-09 07:45:08 +0000 | [diff] [blame] | 1452 | |
| 1453 | // We want to instrument every address only once per basic block (unless there |
| 1454 | // are calls between uses). |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1455 | SmallSet<Value*, 16> TempsToInstrument; |
| 1456 | SmallVector<Instruction*, 16> ToInstrument; |
Kostya Serebryany | 154a54d | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 1457 | SmallVector<Instruction*, 8> NoReturnCalls; |
Kostya Serebryany | 714c67c | 2014-01-17 11:00:30 +0000 | [diff] [blame] | 1458 | SmallVector<BasicBlock*, 16> AllBlocks; |
Kostya Serebryany | 796f655 | 2014-02-27 12:45:36 +0000 | [diff] [blame] | 1459 | SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts; |
Kostya Serebryany | 9f5213f | 2013-06-26 09:18:17 +0000 | [diff] [blame] | 1460 | int NumAllocas = 0; |
Kostya Serebryany | 9024160 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 1461 | bool IsWrite; |
Kostya Serebryany | c7895a8 | 2014-05-23 11:52:07 +0000 | [diff] [blame] | 1462 | unsigned Alignment; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1463 | |
| 1464 | // Fill the set of memory operations to instrument. |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1465 | for (auto &BB : F) { |
| 1466 | AllBlocks.push_back(&BB); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1467 | TempsToInstrument.clear(); |
Kostya Serebryany | c387ca7 | 2012-06-28 09:34:41 +0000 | [diff] [blame] | 1468 | int NumInsnsPerBB = 0; |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1469 | for (auto &Inst : BB) { |
| 1470 | if (LooksLikeCodeInBug11395(&Inst)) return false; |
| 1471 | if (Value *Addr = |
| 1472 | isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) { |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1473 | if (ClOpt && ClOptSameTemp) { |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 1474 | if (!TempsToInstrument.insert(Addr).second) |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1475 | continue; // We've seen this temp in the current BB. |
| 1476 | } |
Kostya Serebryany | cb3f6e1 | 2014-02-27 13:13:59 +0000 | [diff] [blame] | 1477 | } else if (ClInvalidPointerPairs && |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1478 | isInterestingPointerComparisonOrSubtraction(&Inst)) { |
| 1479 | PointerComparisonsOrSubtracts.push_back(&Inst); |
Kostya Serebryany | 796f655 | 2014-02-27 12:45:36 +0000 | [diff] [blame] | 1480 | continue; |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1481 | } else if (isa<MemIntrinsic>(Inst)) { |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1482 | // ok, take it. |
| 1483 | } else { |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1484 | if (isa<AllocaInst>(Inst)) |
Kostya Serebryany | 9f5213f | 2013-06-26 09:18:17 +0000 | [diff] [blame] | 1485 | NumAllocas++; |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1486 | CallSite CS(&Inst); |
Kostya Serebryany | 699ac28 | 2013-02-20 12:35:15 +0000 | [diff] [blame] | 1487 | if (CS) { |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1488 | // A call inside BB. |
| 1489 | TempsToInstrument.clear(); |
Kostya Serebryany | 699ac28 | 2013-02-20 12:35:15 +0000 | [diff] [blame] | 1490 | if (CS.doesNotReturn()) |
| 1491 | NoReturnCalls.push_back(CS.getInstruction()); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1492 | } |
| 1493 | continue; |
| 1494 | } |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1495 | ToInstrument.push_back(&Inst); |
Kostya Serebryany | c387ca7 | 2012-06-28 09:34:41 +0000 | [diff] [blame] | 1496 | NumInsnsPerBB++; |
| 1497 | if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) |
| 1498 | break; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1499 | } |
| 1500 | } |
| 1501 | |
Kostya Serebryany | 0c02d26 | 2014-04-16 12:12:19 +0000 | [diff] [blame] | 1502 | bool UseCalls = false; |
| 1503 | if (ClInstrumentationWithCallsThreshold >= 0 && |
| 1504 | ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold) |
| 1505 | UseCalls = true; |
| 1506 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1507 | // Instrument. |
| 1508 | int NumInstrumented = 0; |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1509 | for (auto Inst : ToInstrument) { |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1510 | if (ClDebugMin < 0 || ClDebugMax < 0 || |
| 1511 | (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) { |
Kostya Serebryany | c7895a8 | 2014-05-23 11:52:07 +0000 | [diff] [blame] | 1512 | if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment)) |
Kostya Serebryany | 0c02d26 | 2014-04-16 12:12:19 +0000 | [diff] [blame] | 1513 | instrumentMop(Inst, UseCalls); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1514 | else |
Kostya Serebryany | 94c81ca | 2014-04-21 11:50:42 +0000 | [diff] [blame] | 1515 | instrumentMemIntrinsic(cast<MemIntrinsic>(Inst)); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1516 | } |
| 1517 | NumInstrumented++; |
| 1518 | } |
| 1519 | |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1520 | FunctionStackPoisoner FSP(F, *this); |
| 1521 | bool ChangedStack = FSP.runOnFunction(); |
Kostya Serebryany | 154a54d | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 1522 | |
| 1523 | // We must unpoison the stack before every NoReturn call (throw, _exit, etc). |
| 1524 | // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37 |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1525 | for (auto CI : NoReturnCalls) { |
Kostya Serebryany | 154a54d | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 1526 | IRBuilder<> IRB(CI); |
Kostya Serebryany | b0e2506 | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 1527 | IRB.CreateCall(AsanHandleNoReturnFunc); |
Kostya Serebryany | 154a54d | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 1528 | } |
| 1529 | |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1530 | for (auto Inst : PointerComparisonsOrSubtracts) { |
| 1531 | instrumentPointerComparisonOrSubtraction(Inst); |
Kostya Serebryany | 796f655 | 2014-02-27 12:45:36 +0000 | [diff] [blame] | 1532 | NumInstrumented++; |
| 1533 | } |
| 1534 | |
Kostya Serebryany | 9f5213f | 2013-06-26 09:18:17 +0000 | [diff] [blame] | 1535 | bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty(); |
Bob Wilson | da4147c | 2013-11-15 07:16:09 +0000 | [diff] [blame] | 1536 | |
Kostya Serebryany | 9f5213f | 2013-06-26 09:18:17 +0000 | [diff] [blame] | 1537 | DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n"); |
| 1538 | |
Kostya Serebryany | 9f5213f | 2013-06-26 09:18:17 +0000 | [diff] [blame] | 1539 | return res; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1540 | } |
| 1541 | |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1542 | // Workaround for bug 11395: we don't want to instrument stack in functions |
| 1543 | // with large assembly blobs (32-bit only), otherwise reg alloc may crash. |
| 1544 | // FIXME: remove once the bug 11395 is fixed. |
| 1545 | bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) { |
| 1546 | if (LongSize != 32) return false; |
| 1547 | CallInst *CI = dyn_cast<CallInst>(I); |
| 1548 | if (!CI || !CI->isInlineAsm()) return false; |
| 1549 | if (CI->getNumArgOperands() <= 5) return false; |
| 1550 | // We have inline assembly with quite a few arguments. |
| 1551 | return true; |
| 1552 | } |
| 1553 | |
| 1554 | void FunctionStackPoisoner::initializeCallbacks(Module &M) { |
| 1555 | IRBuilder<> IRB(*C); |
Kostya Serebryany | 6805de5 | 2013-09-10 13:16:56 +0000 | [diff] [blame] | 1556 | for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) { |
| 1557 | std::string Suffix = itostr(i); |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 1558 | AsanStackMallocFunc[i] = checkInterfaceFunction(M.getOrInsertFunction( |
| 1559 | kAsanStackMallocNameTemplate + Suffix, IntptrTy, IntptrTy, nullptr)); |
| 1560 | AsanStackFreeFunc[i] = checkInterfaceFunction( |
| 1561 | M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix, |
| 1562 | IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr)); |
Kostya Serebryany | 6805de5 | 2013-09-10 13:16:56 +0000 | [diff] [blame] | 1563 | } |
David Blaikie | a92765c | 2014-11-14 00:41:42 +0000 | [diff] [blame] | 1564 | AsanPoisonStackMemoryFunc = checkInterfaceFunction( |
| 1565 | M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(), |
| 1566 | IntptrTy, IntptrTy, nullptr)); |
| 1567 | AsanUnpoisonStackMemoryFunc = checkInterfaceFunction( |
| 1568 | M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), |
| 1569 | IntptrTy, IntptrTy, nullptr)); |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1570 | } |
| 1571 | |
Kostya Serebryany | 4fb7801 | 2013-12-06 09:00:17 +0000 | [diff] [blame] | 1572 | void |
Craig Topper | 3af9722 | 2014-08-27 05:25:00 +0000 | [diff] [blame] | 1573 | FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes, |
Kostya Serebryany | 4fb7801 | 2013-12-06 09:00:17 +0000 | [diff] [blame] | 1574 | IRBuilder<> &IRB, Value *ShadowBase, |
| 1575 | bool DoPoison) { |
| 1576 | size_t n = ShadowBytes.size(); |
Kostya Serebryany | ff7bde1 | 2013-12-23 09:24:36 +0000 | [diff] [blame] | 1577 | size_t i = 0; |
| 1578 | // We need to (un)poison n bytes of stack shadow. Poison as many as we can |
| 1579 | // using 64-bit stores (if we are on 64-bit arch), then poison the rest |
| 1580 | // with 32-bit stores, then with 16-byte stores, then with 8-byte stores. |
| 1581 | for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8; |
| 1582 | LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) { |
| 1583 | for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) { |
| 1584 | uint64_t Val = 0; |
| 1585 | for (size_t j = 0; j < LargeStoreSizeInBytes; j++) { |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 1586 | if (ASan.DL->isLittleEndian()) |
Kostya Serebryany | ff7bde1 | 2013-12-23 09:24:36 +0000 | [diff] [blame] | 1587 | Val |= (uint64_t)ShadowBytes[i + j] << (8 * j); |
| 1588 | else |
| 1589 | Val = (Val << 8) | ShadowBytes[i + j]; |
| 1590 | } |
| 1591 | if (!Val) continue; |
| 1592 | Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)); |
| 1593 | Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8); |
| 1594 | Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0); |
| 1595 | IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo())); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1596 | } |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1597 | } |
| 1598 | } |
| 1599 | |
Kostya Serebryany | 6805de5 | 2013-09-10 13:16:56 +0000 | [diff] [blame] | 1600 | // Fake stack allocator (asan_fake_stack.h) has 11 size classes |
| 1601 | // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass |
| 1602 | static int StackMallocSizeClass(uint64_t LocalStackSize) { |
| 1603 | assert(LocalStackSize <= kMaxStackMallocSize); |
| 1604 | uint64_t MaxSize = kMinStackMallocSize; |
| 1605 | for (int i = 0; ; i++, MaxSize *= 2) |
| 1606 | if (LocalStackSize <= MaxSize) |
| 1607 | return i; |
| 1608 | llvm_unreachable("impossible LocalStackSize"); |
| 1609 | } |
| 1610 | |
Kostya Serebryany | bc86efb | 2013-09-17 12:14:50 +0000 | [diff] [blame] | 1611 | // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic. |
| 1612 | // We can not use MemSet intrinsic because it may end up calling the actual |
| 1613 | // memset. Size is a multiple of 8. |
| 1614 | // Currently this generates 8-byte stores on x86_64; it may be better to |
| 1615 | // generate wider stores. |
| 1616 | void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined( |
| 1617 | IRBuilder<> &IRB, Value *ShadowBase, int Size) { |
| 1618 | assert(!(Size % 8)); |
| 1619 | assert(kAsanStackAfterReturnMagic == 0xf5); |
| 1620 | for (int i = 0; i < Size; i += 8) { |
| 1621 | Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)); |
| 1622 | IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL), |
| 1623 | IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo())); |
| 1624 | } |
| 1625 | } |
| 1626 | |
Evgeniy Stepanov | aaf4bb2 | 2014-05-14 10:30:15 +0000 | [diff] [blame] | 1627 | static DebugLoc getFunctionEntryDebugLocation(Function &F) { |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1628 | for (const auto &Inst : F.getEntryBlock()) |
| 1629 | if (!isa<AllocaInst>(Inst)) |
| 1630 | return Inst.getDebugLoc(); |
| 1631 | return DebugLoc(); |
Evgeniy Stepanov | aaf4bb2 | 2014-05-14 10:30:15 +0000 | [diff] [blame] | 1632 | } |
| 1633 | |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 1634 | PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond, |
| 1635 | Value *ValueIfTrue, |
| 1636 | Instruction *ThenTerm, |
| 1637 | Value *ValueIfFalse) { |
| 1638 | PHINode *PHI = IRB.CreatePHI(IntptrTy, 2); |
| 1639 | BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent(); |
| 1640 | PHI->addIncoming(ValueIfFalse, CondBlock); |
| 1641 | BasicBlock *ThenBlock = ThenTerm->getParent(); |
| 1642 | PHI->addIncoming(ValueIfTrue, ThenBlock); |
| 1643 | return PHI; |
| 1644 | } |
| 1645 | |
| 1646 | Value *FunctionStackPoisoner::createAllocaForLayout( |
| 1647 | IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) { |
| 1648 | AllocaInst *Alloca; |
| 1649 | if (Dynamic) { |
| 1650 | Alloca = IRB.CreateAlloca(IRB.getInt8Ty(), |
| 1651 | ConstantInt::get(IRB.getInt64Ty(), L.FrameSize), |
| 1652 | "MyAlloca"); |
| 1653 | } else { |
| 1654 | Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize), |
| 1655 | nullptr, "MyAlloca"); |
| 1656 | assert(Alloca->isStaticAlloca()); |
| 1657 | } |
| 1658 | assert((ClRealignStack & (ClRealignStack - 1)) == 0); |
| 1659 | size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack); |
| 1660 | Alloca->setAlignment(FrameAlignment); |
| 1661 | return IRB.CreatePointerCast(Alloca, IntptrTy); |
| 1662 | } |
| 1663 | |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1664 | void FunctionStackPoisoner::poisonStack() { |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 1665 | assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0); |
| 1666 | |
Kuba Brecka | f5875d3 | 2015-02-24 09:47:05 +0000 | [diff] [blame] | 1667 | if (ClInstrumentAllocas) { |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 1668 | // Handle dynamic allocas. |
Kuba Brecka | f5875d3 | 2015-02-24 09:47:05 +0000 | [diff] [blame] | 1669 | for (auto &AllocaCall : DynamicAllocaVec) { |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 1670 | handleDynamicAllocaCall(AllocaCall); |
Kuba Brecka | f5875d3 | 2015-02-24 09:47:05 +0000 | [diff] [blame] | 1671 | unpoisonDynamicAlloca(AllocaCall); |
| 1672 | } |
| 1673 | } |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 1674 | |
| 1675 | if (AllocaVec.size() == 0) return; |
| 1676 | |
Kostya Serebryany | 6805de5 | 2013-09-10 13:16:56 +0000 | [diff] [blame] | 1677 | int StackMallocIdx = -1; |
Evgeniy Stepanov | aaf4bb2 | 2014-05-14 10:30:15 +0000 | [diff] [blame] | 1678 | DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1679 | |
| 1680 | Instruction *InsBefore = AllocaVec[0]; |
| 1681 | IRBuilder<> IRB(InsBefore); |
Evgeniy Stepanov | aaf4bb2 | 2014-05-14 10:30:15 +0000 | [diff] [blame] | 1682 | IRB.SetCurrentDebugLocation(EntryDebugLocation); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1683 | |
Kostya Serebryany | 4fb7801 | 2013-12-06 09:00:17 +0000 | [diff] [blame] | 1684 | SmallVector<ASanStackVariableDescription, 16> SVD; |
| 1685 | SVD.reserve(AllocaVec.size()); |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1686 | for (AllocaInst *AI : AllocaVec) { |
Kostya Serebryany | 4fb7801 | 2013-12-06 09:00:17 +0000 | [diff] [blame] | 1687 | ASanStackVariableDescription D = { AI->getName().data(), |
Anna Zaks | 8ed1d81 | 2015-02-27 03:12:36 +0000 | [diff] [blame^] | 1688 | ASan.getAllocaSizeInBytes(AI), |
Kostya Serebryany | 4fb7801 | 2013-12-06 09:00:17 +0000 | [diff] [blame] | 1689 | AI->getAlignment(), AI, 0}; |
| 1690 | SVD.push_back(D); |
| 1691 | } |
| 1692 | // Minimal header size (left redzone) is 4 pointers, |
| 1693 | // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms. |
| 1694 | size_t MinHeaderSize = ASan.LongSize / 2; |
| 1695 | ASanStackFrameLayout L; |
| 1696 | ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L); |
| 1697 | DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n"); |
| 1698 | uint64_t LocalStackSize = L.FrameSize; |
| 1699 | bool DoStackMalloc = |
Alexey Samsonov | e595e1a | 2014-06-13 17:53:44 +0000 | [diff] [blame] | 1700 | ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize; |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 1701 | // Don't do dynamic alloca in presence of inline asm: too often it |
| 1702 | // makes assumptions on which registers are available. |
| 1703 | bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1704 | |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 1705 | Value *StaticAlloca = |
| 1706 | DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false); |
| 1707 | |
| 1708 | Value *FakeStack; |
| 1709 | Value *LocalStackBase; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1710 | |
| 1711 | if (DoStackMalloc) { |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 1712 | // void *FakeStack = __asan_option_detect_stack_use_after_return |
| 1713 | // ? __asan_stack_malloc_N(LocalStackSize) |
| 1714 | // : nullptr; |
| 1715 | // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize); |
Kostya Serebryany | f322382 | 2013-09-18 14:07:14 +0000 | [diff] [blame] | 1716 | Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal( |
| 1717 | kAsanOptionDetectUAR, IRB.getInt32Ty()); |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 1718 | Value *UARIsEnabled = |
| 1719 | IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR), |
| 1720 | Constant::getNullValue(IRB.getInt32Ty())); |
| 1721 | Instruction *Term = |
| 1722 | SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false); |
Kostya Serebryany | f322382 | 2013-09-18 14:07:14 +0000 | [diff] [blame] | 1723 | IRBuilder<> IRBIf(Term); |
Evgeniy Stepanov | aaf4bb2 | 2014-05-14 10:30:15 +0000 | [diff] [blame] | 1724 | IRBIf.SetCurrentDebugLocation(EntryDebugLocation); |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 1725 | StackMallocIdx = StackMallocSizeClass(LocalStackSize); |
| 1726 | assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass); |
| 1727 | Value *FakeStackValue = |
| 1728 | IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx], |
| 1729 | ConstantInt::get(IntptrTy, LocalStackSize)); |
Kostya Serebryany | f322382 | 2013-09-18 14:07:14 +0000 | [diff] [blame] | 1730 | IRB.SetInsertPoint(InsBefore); |
Evgeniy Stepanov | aaf4bb2 | 2014-05-14 10:30:15 +0000 | [diff] [blame] | 1731 | IRB.SetCurrentDebugLocation(EntryDebugLocation); |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 1732 | FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term, |
| 1733 | ConstantInt::get(IntptrTy, 0)); |
| 1734 | |
| 1735 | Value *NoFakeStack = |
| 1736 | IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy)); |
| 1737 | Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false); |
| 1738 | IRBIf.SetInsertPoint(Term); |
| 1739 | IRBIf.SetCurrentDebugLocation(EntryDebugLocation); |
| 1740 | Value *AllocaValue = |
| 1741 | DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca; |
| 1742 | IRB.SetInsertPoint(InsBefore); |
| 1743 | IRB.SetCurrentDebugLocation(EntryDebugLocation); |
| 1744 | LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack); |
| 1745 | } else { |
| 1746 | // void *FakeStack = nullptr; |
| 1747 | // void *LocalStackBase = alloca(LocalStackSize); |
| 1748 | FakeStack = ConstantInt::get(IntptrTy, 0); |
| 1749 | LocalStackBase = |
| 1750 | DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca; |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1751 | } |
| 1752 | |
Alexey Samsonov | 29dd7f2 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 1753 | // Insert poison calls for lifetime intrinsics for alloca. |
| 1754 | bool HavePoisonedAllocas = false; |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1755 | for (const auto &APC : AllocaPoisonCallVec) { |
Alexey Samsonov | a788b94 | 2013-11-18 14:53:55 +0000 | [diff] [blame] | 1756 | assert(APC.InsBefore); |
| 1757 | assert(APC.AI); |
| 1758 | IRBuilder<> IRB(APC.InsBefore); |
| 1759 | poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison); |
Alexey Samsonov | 29dd7f2 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 1760 | HavePoisonedAllocas |= APC.DoPoison; |
| 1761 | } |
| 1762 | |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1763 | // Replace Alloca instructions with base+offset. |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1764 | for (const auto &Desc : SVD) { |
| 1765 | AllocaInst *AI = Desc.AI; |
Alexey Samsonov | 261177a | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 1766 | Value *NewAllocaPtr = IRB.CreateIntToPtr( |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1767 | IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)), |
Kostya Serebryany | 4fb7801 | 2013-12-06 09:00:17 +0000 | [diff] [blame] | 1768 | AI->getType()); |
Adrian Prantl | 3e2659e | 2015-01-30 19:37:48 +0000 | [diff] [blame] | 1769 | replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true); |
Alexey Samsonov | 261177a | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 1770 | AI->replaceAllUsesWith(NewAllocaPtr); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1771 | } |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1772 | |
Kostya Serebryany | cdd35a9 | 2013-03-22 10:37:20 +0000 | [diff] [blame] | 1773 | // The left-most redzone has enough space for at least 4 pointers. |
| 1774 | // Write the Magic value to redzone[0]. |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1775 | Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy); |
| 1776 | IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic), |
| 1777 | BasePlus0); |
Kostya Serebryany | cdd35a9 | 2013-03-22 10:37:20 +0000 | [diff] [blame] | 1778 | // Write the frame description constant to redzone[1]. |
| 1779 | Value *BasePlus1 = IRB.CreateIntToPtr( |
| 1780 | IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)), |
| 1781 | IntptrPtrTy); |
Alexey Samsonov | 9bdb63a | 2012-11-02 12:20:34 +0000 | [diff] [blame] | 1782 | GlobalVariable *StackDescriptionGlobal = |
Alexander Potapenko | daf96ae | 2013-12-25 14:22:15 +0000 | [diff] [blame] | 1783 | createPrivateGlobalForString(*F.getParent(), L.DescriptionString, |
| 1784 | /*AllowMerging*/true); |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1785 | Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, |
| 1786 | IntptrTy); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1787 | IRB.CreateStore(Description, BasePlus1); |
Kostya Serebryany | cdd35a9 | 2013-03-22 10:37:20 +0000 | [diff] [blame] | 1788 | // Write the PC to redzone[2]. |
| 1789 | Value *BasePlus2 = IRB.CreateIntToPtr( |
| 1790 | IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, |
| 1791 | 2 * ASan.LongSize/8)), |
| 1792 | IntptrPtrTy); |
| 1793 | IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1794 | |
| 1795 | // Poison the stack redzones at the entry. |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1796 | Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB); |
Kostya Serebryany | 4fb7801 | 2013-12-06 09:00:17 +0000 | [diff] [blame] | 1797 | poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1798 | |
Kostya Serebryany | 530e207 | 2013-12-23 14:15:08 +0000 | [diff] [blame] | 1799 | // (Un)poison the stack before all ret instructions. |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1800 | for (auto Ret : RetVec) { |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1801 | IRBuilder<> IRBRet(Ret); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1802 | // Mark the current frame as retired. |
| 1803 | IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic), |
| 1804 | BasePlus0); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1805 | if (DoStackMalloc) { |
Kostya Serebryany | 6805de5 | 2013-09-10 13:16:56 +0000 | [diff] [blame] | 1806 | assert(StackMallocIdx >= 0); |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 1807 | // if FakeStack != 0 // LocalStackBase == FakeStack |
Kostya Serebryany | 530e207 | 2013-12-23 14:15:08 +0000 | [diff] [blame] | 1808 | // // In use-after-return mode, poison the whole stack frame. |
| 1809 | // if StackMallocIdx <= 4 |
| 1810 | // // For small sizes inline the whole thing: |
| 1811 | // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize); |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 1812 | // **SavedFlagPtr(FakeStack) = 0 |
Kostya Serebryany | 530e207 | 2013-12-23 14:15:08 +0000 | [diff] [blame] | 1813 | // else |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 1814 | // __asan_stack_free_N(FakeStack, LocalStackSize) |
Kostya Serebryany | 530e207 | 2013-12-23 14:15:08 +0000 | [diff] [blame] | 1815 | // else |
| 1816 | // <This is not a fake stack; unpoison the redzones> |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 1817 | Value *Cmp = |
| 1818 | IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy)); |
Kostya Serebryany | 530e207 | 2013-12-23 14:15:08 +0000 | [diff] [blame] | 1819 | TerminatorInst *ThenTerm, *ElseTerm; |
| 1820 | SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm); |
| 1821 | |
| 1822 | IRBuilder<> IRBPoison(ThenTerm); |
Kostya Serebryany | bc86efb | 2013-09-17 12:14:50 +0000 | [diff] [blame] | 1823 | if (StackMallocIdx <= 4) { |
Kostya Serebryany | bc86efb | 2013-09-17 12:14:50 +0000 | [diff] [blame] | 1824 | int ClassSize = kMinStackMallocSize << StackMallocIdx; |
| 1825 | SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase, |
| 1826 | ClassSize >> Mapping.Scale); |
| 1827 | Value *SavedFlagPtrPtr = IRBPoison.CreateAdd( |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 1828 | FakeStack, |
Kostya Serebryany | bc86efb | 2013-09-17 12:14:50 +0000 | [diff] [blame] | 1829 | ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8)); |
| 1830 | Value *SavedFlagPtr = IRBPoison.CreateLoad( |
| 1831 | IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy)); |
| 1832 | IRBPoison.CreateStore( |
| 1833 | Constant::getNullValue(IRBPoison.getInt8Ty()), |
| 1834 | IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy())); |
| 1835 | } else { |
| 1836 | // For larger frames call __asan_stack_free_*. |
Alexey Samsonov | 4b7f413 | 2014-12-11 21:53:03 +0000 | [diff] [blame] | 1837 | IRBPoison.CreateCall2(AsanStackFreeFunc[StackMallocIdx], FakeStack, |
| 1838 | ConstantInt::get(IntptrTy, LocalStackSize)); |
Kostya Serebryany | bc86efb | 2013-09-17 12:14:50 +0000 | [diff] [blame] | 1839 | } |
Kostya Serebryany | 530e207 | 2013-12-23 14:15:08 +0000 | [diff] [blame] | 1840 | |
| 1841 | IRBuilder<> IRBElse(ElseTerm); |
| 1842 | poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false); |
Alexey Samsonov | 261177a | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 1843 | } else if (HavePoisonedAllocas) { |
| 1844 | // If we poisoned some allocas in llvm.lifetime analysis, |
| 1845 | // unpoison whole stack frame now. |
Alexey Samsonov | 261177a | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 1846 | poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false); |
Kostya Serebryany | 530e207 | 2013-12-23 14:15:08 +0000 | [diff] [blame] | 1847 | } else { |
| 1848 | poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1849 | } |
| 1850 | } |
| 1851 | |
Kostya Serebryany | 0995994 | 2012-10-19 06:20:53 +0000 | [diff] [blame] | 1852 | // We are done. Remove the old unused alloca instructions. |
Alexey Samsonov | a02e664 | 2014-05-29 18:40:48 +0000 | [diff] [blame] | 1853 | for (auto AI : AllocaVec) |
| 1854 | AI->eraseFromParent(); |
Kostya Serebryany | 6e6b03e | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1855 | } |
Alexey Samsonov | 261177a | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 1856 | |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1857 | void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size, |
Jakub Staszak | 23ec6a9 | 2013-08-09 20:53:48 +0000 | [diff] [blame] | 1858 | IRBuilder<> &IRB, bool DoPoison) { |
Alexey Samsonov | 261177a | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 1859 | // For now just insert the call to ASan runtime. |
| 1860 | Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy); |
| 1861 | Value *SizeArg = ConstantInt::get(IntptrTy, Size); |
| 1862 | IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc |
| 1863 | : AsanUnpoisonStackMemoryFunc, |
| 1864 | AddrArg, SizeArg); |
| 1865 | } |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1866 | |
| 1867 | // Handling llvm.lifetime intrinsics for a given %alloca: |
| 1868 | // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca. |
| 1869 | // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect |
| 1870 | // invalid accesses) and unpoison it for llvm.lifetime.start (the memory |
| 1871 | // could be poisoned by previous llvm.lifetime.end instruction, as the |
| 1872 | // variable may go in and out of scope several times, e.g. in loops). |
| 1873 | // (3) if we poisoned at least one %alloca in a function, |
| 1874 | // unpoison the whole stack frame at function exit. |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1875 | |
Alexey Samsonov | 29dd7f2 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 1876 | AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) { |
| 1877 | if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) |
| 1878 | // We're intested only in allocas we can handle. |
Anna Zaks | 8ed1d81 | 2015-02-27 03:12:36 +0000 | [diff] [blame^] | 1879 | return ASan.isInterestingAlloca(*AI) ? AI : nullptr; |
Alexey Samsonov | 29dd7f2 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 1880 | // See if we've already calculated (or started to calculate) alloca for a |
| 1881 | // given value. |
| 1882 | AllocaForValueMapTy::iterator I = AllocaForValue.find(V); |
| 1883 | if (I != AllocaForValue.end()) |
| 1884 | return I->second; |
| 1885 | // Store 0 while we're calculating alloca for value V to avoid |
| 1886 | // infinite recursion if the value references itself. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1887 | AllocaForValue[V] = nullptr; |
| 1888 | AllocaInst *Res = nullptr; |
Alexey Samsonov | 29dd7f2 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 1889 | if (CastInst *CI = dyn_cast<CastInst>(V)) |
| 1890 | Res = findAllocaForValue(CI->getOperand(0)); |
| 1891 | else if (PHINode *PN = dyn_cast<PHINode>(V)) { |
| 1892 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 1893 | Value *IncValue = PN->getIncomingValue(i); |
| 1894 | // Allow self-referencing phi-nodes. |
| 1895 | if (IncValue == PN) continue; |
| 1896 | AllocaInst *IncValueAI = findAllocaForValue(IncValue); |
| 1897 | // AI for incoming values should exist and should all be equal. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1898 | if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res)) |
| 1899 | return nullptr; |
Alexey Samsonov | 29dd7f2 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 1900 | Res = IncValueAI; |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1901 | } |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1902 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1903 | if (Res) |
Alexey Samsonov | 29dd7f2 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 1904 | AllocaForValue[V] = Res; |
Alexey Samsonov | 1e3f7ba | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1905 | return Res; |
| 1906 | } |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 1907 | |
| 1908 | // Compute PartialRzMagic for dynamic alloca call. PartialRzMagic is |
| 1909 | // constructed from two separate 32-bit numbers: PartialRzMagic = Val1 | Val2. |
| 1910 | // (1) Val1 is resposible for forming base value for PartialRzMagic, containing |
| 1911 | // only 00 for fully addressable and 0xcb for fully poisoned bytes for each |
| 1912 | // 8-byte chunk of user memory respectively. |
| 1913 | // (2) Val2 forms the value for marking first poisoned byte in shadow memory |
| 1914 | // with appropriate value (0x01 - 0x07 or 0xcb if Padding % 8 == 0). |
| 1915 | |
| 1916 | // Shift = Padding & ~7; // the number of bits we need to shift to access first |
| 1917 | // chunk in shadow memory, containing nonzero bytes. |
| 1918 | // Example: |
| 1919 | // Padding = 21 Padding = 16 |
| 1920 | // Shadow: |00|00|05|cb| Shadow: |00|00|cb|cb| |
| 1921 | // ^ ^ |
| 1922 | // | | |
| 1923 | // Shift = 21 & ~7 = 16 Shift = 16 & ~7 = 16 |
| 1924 | // |
| 1925 | // Val1 = 0xcbcbcbcb << Shift; |
| 1926 | // PartialBits = Padding ? Padding & 7 : 0xcb; |
| 1927 | // Val2 = PartialBits << Shift; |
| 1928 | // Result = Val1 | Val2; |
| 1929 | Value *FunctionStackPoisoner::computePartialRzMagic(Value *PartialSize, |
| 1930 | IRBuilder<> &IRB) { |
| 1931 | PartialSize = IRB.CreateIntCast(PartialSize, IRB.getInt32Ty(), false); |
| 1932 | Value *Shift = IRB.CreateAnd(PartialSize, IRB.getInt32(~7)); |
| 1933 | unsigned Val1Int = kAsanAllocaPartialVal1; |
| 1934 | unsigned Val2Int = kAsanAllocaPartialVal2; |
| 1935 | if (!ASan.DL->isLittleEndian()) { |
| 1936 | Val1Int = sys::getSwappedBytes(Val1Int); |
| 1937 | Val2Int = sys::getSwappedBytes(Val2Int); |
| 1938 | } |
| 1939 | Value *Val1 = shiftAllocaMagic(IRB.getInt32(Val1Int), IRB, Shift); |
| 1940 | Value *PartialBits = IRB.CreateAnd(PartialSize, IRB.getInt32(7)); |
| 1941 | // For BigEndian get 0x000000YZ -> 0xYZ000000. |
| 1942 | if (ASan.DL->isBigEndian()) |
| 1943 | PartialBits = IRB.CreateShl(PartialBits, IRB.getInt32(24)); |
| 1944 | Value *Val2 = IRB.getInt32(Val2Int); |
| 1945 | Value *Cond = |
| 1946 | IRB.CreateICmpNE(PartialBits, Constant::getNullValue(IRB.getInt32Ty())); |
| 1947 | Val2 = IRB.CreateSelect(Cond, shiftAllocaMagic(PartialBits, IRB, Shift), |
| 1948 | shiftAllocaMagic(Val2, IRB, Shift)); |
| 1949 | return IRB.CreateOr(Val1, Val2); |
| 1950 | } |
| 1951 | |
| 1952 | void FunctionStackPoisoner::handleDynamicAllocaCall( |
| 1953 | DynamicAllocaCall &AllocaCall) { |
| 1954 | AllocaInst *AI = AllocaCall.AI; |
Yury Gribov | 3ae427d | 2014-12-01 08:47:58 +0000 | [diff] [blame] | 1955 | if (!doesDominateAllExits(AI)) { |
| 1956 | // We do not yet handle complex allocas |
| 1957 | AllocaCall.Poison = false; |
| 1958 | return; |
| 1959 | } |
| 1960 | |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 1961 | IRBuilder<> IRB(AI); |
| 1962 | |
| 1963 | PointerType *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty()); |
| 1964 | const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment()); |
| 1965 | const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1; |
| 1966 | |
| 1967 | Value *Zero = Constant::getNullValue(IntptrTy); |
| 1968 | Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize); |
| 1969 | Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask); |
| 1970 | Value *NotAllocaRzMask = ConstantInt::get(IntptrTy, ~AllocaRedzoneMask); |
| 1971 | |
| 1972 | // Since we need to extend alloca with additional memory to locate |
| 1973 | // redzones, and OldSize is number of allocated blocks with |
| 1974 | // ElementSize size, get allocated memory size in bytes by |
| 1975 | // OldSize * ElementSize. |
| 1976 | unsigned ElementSize = ASan.DL->getTypeAllocSize(AI->getAllocatedType()); |
| 1977 | Value *OldSize = IRB.CreateMul(AI->getArraySize(), |
| 1978 | ConstantInt::get(IntptrTy, ElementSize)); |
| 1979 | |
| 1980 | // PartialSize = OldSize % 32 |
| 1981 | Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask); |
| 1982 | |
| 1983 | // Misalign = kAllocaRzSize - PartialSize; |
| 1984 | Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize); |
| 1985 | |
| 1986 | // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0; |
| 1987 | Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize); |
| 1988 | Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero); |
| 1989 | |
| 1990 | // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize |
| 1991 | // Align is added to locate left redzone, PartialPadding for possible |
| 1992 | // partial redzone and kAllocaRzSize for right redzone respectively. |
| 1993 | Value *AdditionalChunkSize = IRB.CreateAdd( |
| 1994 | ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding); |
| 1995 | |
| 1996 | Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize); |
| 1997 | |
| 1998 | // Insert new alloca with new NewSize and Align params. |
| 1999 | AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize); |
| 2000 | NewAlloca->setAlignment(Align); |
| 2001 | |
| 2002 | // NewAddress = Address + Align |
| 2003 | Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy), |
| 2004 | ConstantInt::get(IntptrTy, Align)); |
| 2005 | |
| 2006 | Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType()); |
| 2007 | |
| 2008 | // LeftRzAddress = NewAddress - kAllocaRzSize |
| 2009 | Value *LeftRzAddress = IRB.CreateSub(NewAddress, AllocaRzSize); |
| 2010 | |
| 2011 | // Poisoning left redzone. |
| 2012 | AllocaCall.LeftRzAddr = ASan.memToShadow(LeftRzAddress, IRB); |
| 2013 | IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaLeftMagic), |
| 2014 | IRB.CreateIntToPtr(AllocaCall.LeftRzAddr, Int32PtrTy)); |
| 2015 | |
| 2016 | // PartialRzAligned = PartialRzAddr & ~AllocaRzMask |
| 2017 | Value *PartialRzAddr = IRB.CreateAdd(NewAddress, OldSize); |
| 2018 | Value *PartialRzAligned = IRB.CreateAnd(PartialRzAddr, NotAllocaRzMask); |
| 2019 | |
| 2020 | // Poisoning partial redzone. |
| 2021 | Value *PartialRzMagic = computePartialRzMagic(PartialSize, IRB); |
| 2022 | Value *PartialRzShadowAddr = ASan.memToShadow(PartialRzAligned, IRB); |
| 2023 | IRB.CreateStore(PartialRzMagic, |
| 2024 | IRB.CreateIntToPtr(PartialRzShadowAddr, Int32PtrTy)); |
| 2025 | |
| 2026 | // RightRzAddress |
| 2027 | // = (PartialRzAddr + AllocaRzMask) & ~AllocaRzMask |
| 2028 | Value *RightRzAddress = IRB.CreateAnd( |
| 2029 | IRB.CreateAdd(PartialRzAddr, AllocaRzMask), NotAllocaRzMask); |
| 2030 | |
| 2031 | // Poisoning right redzone. |
| 2032 | AllocaCall.RightRzAddr = ASan.memToShadow(RightRzAddress, IRB); |
| 2033 | IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaRightMagic), |
| 2034 | IRB.CreateIntToPtr(AllocaCall.RightRzAddr, Int32PtrTy)); |
| 2035 | |
| 2036 | // Replace all uses of AddessReturnedByAlloca with NewAddress. |
| 2037 | AI->replaceAllUsesWith(NewAddressPtr); |
| 2038 | |
| 2039 | // We are done. Erase old alloca and store left, partial and right redzones |
| 2040 | // shadow addresses for future unpoisoning. |
| 2041 | AI->eraseFromParent(); |
Kostya Serebryany | ea2cb6f | 2014-11-21 21:25:18 +0000 | [diff] [blame] | 2042 | NumInstrumentedDynamicAllocas++; |
Yury Gribov | 55441bb | 2014-11-21 10:29:50 +0000 | [diff] [blame] | 2043 | } |