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