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