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