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