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