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