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