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