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