Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1 | //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file is a part of AddressSanitizer, an address sanity checker. |
| 11 | // Details of the algorithm: |
| 12 | // http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm |
| 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
| 16 | #define DEBUG_TYPE "asan" |
| 17 | |
Chandler Carruth | d04a8d4 | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 18 | #include "llvm/Transforms/Instrumentation.h" |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 19 | #include "llvm/ADT/ArrayRef.h" |
Alexey Samsonov | 1c8b825 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 20 | #include "llvm/ADT/DenseMap.h" |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 21 | #include "llvm/ADT/DepthFirstIterator.h" |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 22 | #include "llvm/ADT/OwningPtr.h" |
| 23 | #include "llvm/ADT/SmallSet.h" |
| 24 | #include "llvm/ADT/SmallString.h" |
| 25 | #include "llvm/ADT/SmallVector.h" |
| 26 | #include "llvm/ADT/StringExtras.h" |
Evgeniy Stepanov | 06fdbaa | 2012-05-23 11:52:12 +0000 | [diff] [blame] | 27 | #include "llvm/ADT/Triple.h" |
Alexey Samsonov | 1afbb51 | 2012-12-12 14:31:53 +0000 | [diff] [blame] | 28 | #include "llvm/DIBuilder.h" |
Chandler Carruth | 0b8c9a8 | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 29 | #include "llvm/IR/DataLayout.h" |
| 30 | #include "llvm/IR/Function.h" |
| 31 | #include "llvm/IR/IRBuilder.h" |
| 32 | #include "llvm/IR/InlineAsm.h" |
| 33 | #include "llvm/IR/IntrinsicInst.h" |
| 34 | #include "llvm/IR/LLVMContext.h" |
| 35 | #include "llvm/IR/Module.h" |
| 36 | #include "llvm/IR/Type.h" |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 37 | #include "llvm/InstVisitor.h" |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 38 | #include "llvm/Support/CommandLine.h" |
| 39 | #include "llvm/Support/DataTypes.h" |
| 40 | #include "llvm/Support/Debug.h" |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 41 | #include "llvm/Support/raw_ostream.h" |
| 42 | #include "llvm/Support/system_error.h" |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 43 | #include "llvm/Target/TargetMachine.h" |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 44 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Chandler Carruth | 90230c8 | 2013-01-19 08:03:47 +0000 | [diff] [blame] | 45 | #include "llvm/Transforms/Utils/BlackList.h" |
Alexey Samsonov | 1afbb51 | 2012-12-12 14:31:53 +0000 | [diff] [blame] | 46 | #include "llvm/Transforms/Utils/Local.h" |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 47 | #include "llvm/Transforms/Utils/ModuleUtils.h" |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 48 | #include <algorithm> |
Chandler Carruth | d04a8d4 | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 49 | #include <string> |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 50 | |
| 51 | using namespace llvm; |
| 52 | |
| 53 | static const uint64_t kDefaultShadowScale = 3; |
| 54 | static const uint64_t kDefaultShadowOffset32 = 1ULL << 29; |
| 55 | static const uint64_t kDefaultShadowOffset64 = 1ULL << 44; |
Kostya Serebryany | 48a615f | 2013-01-23 12:54:55 +0000 | [diff] [blame] | 56 | static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 57 | |
| 58 | static const size_t kMaxStackMallocSize = 1 << 16; // 64K |
| 59 | static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3; |
| 60 | static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E; |
| 61 | |
| 62 | static const char *kAsanModuleCtorName = "asan.module_ctor"; |
Kostya Serebryany | 7bcfc99 | 2011-12-15 21:59:03 +0000 | [diff] [blame] | 63 | static const char *kAsanModuleDtorName = "asan.module_dtor"; |
| 64 | static const int kAsanCtorAndCtorPriority = 1; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 65 | static const char *kAsanReportErrorTemplate = "__asan_report_"; |
| 66 | static const char *kAsanRegisterGlobalsName = "__asan_register_globals"; |
Kostya Serebryany | 7bcfc99 | 2011-12-15 21:59:03 +0000 | [diff] [blame] | 67 | static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals"; |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 68 | static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init"; |
| 69 | static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init"; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 70 | static const char *kAsanInitName = "__asan_init"; |
Kostya Serebryany | 95e3cf4 | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 71 | static const char *kAsanHandleNoReturnName = "__asan_handle_no_return"; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 72 | static const char *kAsanMappingOffsetName = "__asan_mapping_offset"; |
| 73 | static const char *kAsanMappingScaleName = "__asan_mapping_scale"; |
| 74 | static const char *kAsanStackMallocName = "__asan_stack_malloc"; |
| 75 | static const char *kAsanStackFreeName = "__asan_stack_free"; |
Kostya Serebryany | 51c7c65 | 2012-11-20 14:16:08 +0000 | [diff] [blame] | 76 | static const char *kAsanGenPrefix = "__asan_gen_"; |
Alexey Samsonov | f985f44 | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 77 | static const char *kAsanPoisonStackMemoryName = "__asan_poison_stack_memory"; |
| 78 | static const char *kAsanUnpoisonStackMemoryName = |
| 79 | "__asan_unpoison_stack_memory"; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 80 | |
| 81 | static const int kAsanStackLeftRedzoneMagic = 0xf1; |
| 82 | static const int kAsanStackMidRedzoneMagic = 0xf2; |
| 83 | static const int kAsanStackRightRedzoneMagic = 0xf3; |
| 84 | static const int kAsanStackPartialRedzoneMagic = 0xf4; |
| 85 | |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 86 | // Accesses sizes are powers of two: 1, 2, 4, 8, 16. |
| 87 | static const size_t kNumberOfAccessSizes = 5; |
| 88 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 89 | // Command-line flags. |
| 90 | |
| 91 | // This flag may need to be replaced with -f[no-]asan-reads. |
| 92 | static cl::opt<bool> ClInstrumentReads("asan-instrument-reads", |
| 93 | cl::desc("instrument read instructions"), cl::Hidden, cl::init(true)); |
| 94 | static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes", |
| 95 | cl::desc("instrument write instructions"), cl::Hidden, cl::init(true)); |
Kostya Serebryany | e6cf2e0 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 96 | static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics", |
| 97 | cl::desc("instrument atomic instructions (rmw, cmpxchg)"), |
| 98 | cl::Hidden, cl::init(true)); |
Kostya Serebryany | 6e2d506 | 2012-08-15 08:58:58 +0000 | [diff] [blame] | 99 | static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path", |
| 100 | cl::desc("use instrumentation with slow path for all accesses"), |
| 101 | cl::Hidden, cl::init(false)); |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 102 | // This flag limits the number of instructions to be instrumented |
Kostya Serebryany | 324cbb8 | 2012-06-28 09:34:41 +0000 | [diff] [blame] | 103 | // in any given BB. Normally, this should be set to unlimited (INT_MAX), |
| 104 | // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary |
| 105 | // set it to 10000. |
| 106 | static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb", |
| 107 | cl::init(10000), |
| 108 | cl::desc("maximal number of instructions to instrument in any given BB"), |
| 109 | cl::Hidden); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 110 | // This flag may need to be replaced with -f[no]asan-stack. |
| 111 | static cl::opt<bool> ClStack("asan-stack", |
| 112 | cl::desc("Handle stack memory"), cl::Hidden, cl::init(true)); |
| 113 | // This flag may need to be replaced with -f[no]asan-use-after-return. |
| 114 | static cl::opt<bool> ClUseAfterReturn("asan-use-after-return", |
| 115 | cl::desc("Check return-after-free"), cl::Hidden, cl::init(false)); |
| 116 | // This flag may need to be replaced with -f[no]asan-globals. |
| 117 | static cl::opt<bool> ClGlobals("asan-globals", |
| 118 | cl::desc("Handle global objects"), cl::Hidden, cl::init(true)); |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 119 | static cl::opt<bool> ClInitializers("asan-initialization-order", |
| 120 | cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false)); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 121 | static cl::opt<bool> ClMemIntrin("asan-memintrin", |
| 122 | cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true)); |
Kostya Serebryany | 6c55412 | 2012-12-04 06:14:01 +0000 | [diff] [blame] | 123 | static cl::opt<bool> ClRealignStack("asan-realign-stack", |
| 124 | cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true)); |
Alexey Samsonov | b0dcf61 | 2012-12-03 19:09:26 +0000 | [diff] [blame] | 125 | static cl::opt<std::string> ClBlacklistFile("asan-blacklist", |
| 126 | cl::desc("File containing the list of objects to ignore " |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 127 | "during instrumentation"), cl::Hidden); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 128 | |
| 129 | // These flags allow to change the shadow mapping. |
| 130 | // The shadow mapping looks like |
| 131 | // Shadow = (Mem >> scale) + (1 << offset_log) |
| 132 | static cl::opt<int> ClMappingScale("asan-mapping-scale", |
| 133 | cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0)); |
| 134 | static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log", |
| 135 | cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1)); |
| 136 | |
| 137 | // Optimization flags. Not user visible, used mostly for testing |
| 138 | // and benchmarking the tool. |
| 139 | static cl::opt<bool> ClOpt("asan-opt", |
| 140 | cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true)); |
| 141 | static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp", |
| 142 | cl::desc("Instrument the same temp just once"), cl::Hidden, |
| 143 | cl::init(true)); |
| 144 | static cl::opt<bool> ClOptGlobals("asan-opt-globals", |
| 145 | cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true)); |
| 146 | |
Alexey Samsonov | ee54827 | 2012-11-29 18:14:24 +0000 | [diff] [blame] | 147 | static cl::opt<bool> ClCheckLifetime("asan-check-lifetime", |
| 148 | cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), |
| 149 | cl::Hidden, cl::init(false)); |
| 150 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 151 | // Debug flags. |
| 152 | static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden, |
| 153 | cl::init(0)); |
| 154 | static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"), |
| 155 | cl::Hidden, cl::init(0)); |
| 156 | static cl::opt<std::string> ClDebugFunc("asan-debug-func", |
| 157 | cl::Hidden, cl::desc("Debug func")); |
| 158 | static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"), |
| 159 | cl::Hidden, cl::init(-1)); |
| 160 | static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"), |
| 161 | cl::Hidden, cl::init(-1)); |
| 162 | |
| 163 | namespace { |
Kostya Serebryany | ca23d43 | 2012-11-20 13:00:01 +0000 | [diff] [blame] | 164 | /// A set of dynamically initialized globals extracted from metadata. |
| 165 | class SetOfDynamicallyInitializedGlobals { |
| 166 | public: |
| 167 | void Init(Module& M) { |
| 168 | // Clang generates metadata identifying all dynamically initialized globals. |
| 169 | NamedMDNode *DynamicGlobals = |
| 170 | M.getNamedMetadata("llvm.asan.dynamically_initialized_globals"); |
| 171 | if (!DynamicGlobals) |
| 172 | return; |
| 173 | for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) { |
| 174 | MDNode *MDN = DynamicGlobals->getOperand(i); |
| 175 | assert(MDN->getNumOperands() == 1); |
| 176 | Value *VG = MDN->getOperand(0); |
| 177 | // The optimizer may optimize away a global entirely, in which case we |
| 178 | // cannot instrument access to it. |
| 179 | if (!VG) |
| 180 | continue; |
| 181 | DynInitGlobals.insert(cast<GlobalVariable>(VG)); |
| 182 | } |
| 183 | } |
| 184 | bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; } |
| 185 | private: |
| 186 | SmallSet<GlobalValue*, 32> DynInitGlobals; |
| 187 | }; |
| 188 | |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 189 | /// This struct defines the shadow mapping using the rule: |
Kostya Serebryany | 48a615f | 2013-01-23 12:54:55 +0000 | [diff] [blame] | 190 | /// shadow = (mem >> Scale) ADD-or-OR Offset. |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 191 | struct ShadowMapping { |
| 192 | int Scale; |
| 193 | uint64_t Offset; |
Kostya Serebryany | 48a615f | 2013-01-23 12:54:55 +0000 | [diff] [blame] | 194 | bool OrShadowOffset; |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 195 | }; |
| 196 | |
Alexey Samsonov | 11af9a8 | 2013-01-17 11:12:32 +0000 | [diff] [blame] | 197 | static ShadowMapping getShadowMapping(const Module &M, int LongSize, |
| 198 | bool ZeroBaseShadow) { |
| 199 | llvm::Triple TargetTriple(M.getTargetTriple()); |
| 200 | bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android; |
Kostya Serebryany | 48a615f | 2013-01-23 12:54:55 +0000 | [diff] [blame] | 201 | bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64; |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 202 | |
| 203 | ShadowMapping Mapping; |
| 204 | |
Kostya Serebryany | 48a615f | 2013-01-23 12:54:55 +0000 | [diff] [blame] | 205 | // OR-ing shadow offset if more efficient (at least on x86), |
| 206 | // but on ppc64 we have to use add since the shadow offset is not neccesary |
| 207 | // 1/8-th of the address space. |
| 208 | Mapping.OrShadowOffset = !IsPPC64; |
| 209 | |
Alexey Samsonov | 11af9a8 | 2013-01-17 11:12:32 +0000 | [diff] [blame] | 210 | Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 : |
Kostya Serebryany | 48a615f | 2013-01-23 12:54:55 +0000 | [diff] [blame] | 211 | (LongSize == 32 ? kDefaultShadowOffset32 : |
| 212 | IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64); |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 213 | if (ClMappingOffsetLog >= 0) { |
| 214 | // Zero offset log is the special case. |
| 215 | Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog; |
| 216 | } |
| 217 | |
| 218 | Mapping.Scale = kDefaultShadowScale; |
| 219 | if (ClMappingScale) { |
| 220 | Mapping.Scale = ClMappingScale; |
| 221 | } |
| 222 | |
| 223 | return Mapping; |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 224 | } |
| 225 | |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 226 | static size_t RedzoneSizeForScale(int MappingScale) { |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 227 | // Redzone used for stack and globals is at least 32 bytes. |
| 228 | // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively. |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 229 | return std::max(32U, 1U << MappingScale); |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 230 | } |
Kostya Serebryany | ca23d43 | 2012-11-20 13:00:01 +0000 | [diff] [blame] | 231 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 232 | /// AddressSanitizer: instrument the code in module to find memory bugs. |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 233 | struct AddressSanitizer : public FunctionPass { |
Alexey Samsonov | ee54827 | 2012-11-29 18:14:24 +0000 | [diff] [blame] | 234 | AddressSanitizer(bool CheckInitOrder = false, |
| 235 | bool CheckUseAfterReturn = false, |
Alexey Samsonov | b0dcf61 | 2012-12-03 19:09:26 +0000 | [diff] [blame] | 236 | bool CheckLifetime = false, |
Alexey Samsonov | 11af9a8 | 2013-01-17 11:12:32 +0000 | [diff] [blame] | 237 | StringRef BlacklistFile = StringRef(), |
| 238 | bool ZeroBaseShadow = false) |
Alexey Samsonov | ee54827 | 2012-11-29 18:14:24 +0000 | [diff] [blame] | 239 | : FunctionPass(ID), |
| 240 | CheckInitOrder(CheckInitOrder || ClInitializers), |
| 241 | CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn), |
Alexey Samsonov | b0dcf61 | 2012-12-03 19:09:26 +0000 | [diff] [blame] | 242 | CheckLifetime(CheckLifetime || ClCheckLifetime), |
| 243 | BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile |
Alexey Samsonov | 11af9a8 | 2013-01-17 11:12:32 +0000 | [diff] [blame] | 244 | : BlacklistFile), |
| 245 | ZeroBaseShadow(ZeroBaseShadow) {} |
Kostya Serebryany | 1416edc | 2012-11-28 10:31:36 +0000 | [diff] [blame] | 246 | virtual const char *getPassName() const { |
| 247 | return "AddressSanitizerFunctionPass"; |
| 248 | } |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 249 | void instrumentMop(Instruction *I); |
| 250 | void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB, |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 251 | Value *Addr, uint32_t TypeSize, bool IsWrite); |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 252 | Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong, |
| 253 | Value *ShadowValue, uint32_t TypeSize); |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 254 | Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr, |
Kostya Serebryany | 2735cf4 | 2012-07-16 17:12:07 +0000 | [diff] [blame] | 255 | bool IsWrite, size_t AccessSizeIndex); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 256 | bool instrumentMemIntrinsic(MemIntrinsic *MI); |
| 257 | void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr, |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 258 | Value *Size, |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 259 | Instruction *InsertBefore, bool IsWrite); |
| 260 | Value *memToShadow(Value *Shadow, IRBuilder<> &IRB); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 261 | bool runOnFunction(Function &F); |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 262 | void createInitializerPoisonCalls(Module &M, |
| 263 | Value *FirstAddr, Value *LastAddr); |
Kostya Serebryany | a1a8a32 | 2012-01-30 23:50:10 +0000 | [diff] [blame] | 264 | bool maybeInsertAsanInitAtFunctionEntry(Function &F); |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 265 | void emitShadowMapping(Module &M, IRBuilder<> &IRB) const; |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 266 | virtual bool doInitialization(Module &M); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 267 | static char ID; // Pass identification, replacement for typeid |
| 268 | |
| 269 | private: |
Kostya Serebryany | 8b390ff | 2012-11-29 09:54:21 +0000 | [diff] [blame] | 270 | void initializeCallbacks(Module &M); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 271 | |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 272 | bool ShouldInstrumentGlobal(GlobalVariable *G); |
Kostya Serebryany | 5a3a9c9 | 2011-11-18 01:41:06 +0000 | [diff] [blame] | 273 | bool LooksLikeCodeInBug11395(Instruction *I); |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 274 | void FindDynamicInitializers(Module &M); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 275 | |
Alexey Samsonov | ee54827 | 2012-11-29 18:14:24 +0000 | [diff] [blame] | 276 | bool CheckInitOrder; |
| 277 | bool CheckUseAfterReturn; |
| 278 | bool CheckLifetime; |
Alexey Samsonov | 11af9a8 | 2013-01-17 11:12:32 +0000 | [diff] [blame] | 279 | SmallString<64> BlacklistFile; |
| 280 | bool ZeroBaseShadow; |
| 281 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 282 | LLVMContext *C; |
Micah Villmow | 3574eca | 2012-10-08 16:38:25 +0000 | [diff] [blame] | 283 | DataLayout *TD; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 284 | int LongSize; |
| 285 | Type *IntptrTy; |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 286 | ShadowMapping Mapping; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 287 | Function *AsanCtorFunction; |
| 288 | Function *AsanInitFunction; |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 289 | Function *AsanHandleNoReturnFunc; |
Kostya Serebryany | b5b86d2 | 2012-08-24 16:44:47 +0000 | [diff] [blame] | 290 | OwningPtr<BlackList> BL; |
Kostya Serebryany | 9db5b5f | 2012-07-16 14:09:42 +0000 | [diff] [blame] | 291 | // This array is indexed by AccessIsWrite and log2(AccessSize). |
| 292 | Function *AsanErrorCallback[2][kNumberOfAccessSizes]; |
Kostya Serebryany | f7b0822 | 2012-07-20 09:54:50 +0000 | [diff] [blame] | 293 | InlineAsm *EmptyAsm; |
Kostya Serebryany | ca23d43 | 2012-11-20 13:00:01 +0000 | [diff] [blame] | 294 | SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals; |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 295 | |
| 296 | friend struct FunctionStackPoisoner; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 297 | }; |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 298 | |
Kostya Serebryany | 1416edc | 2012-11-28 10:31:36 +0000 | [diff] [blame] | 299 | class AddressSanitizerModule : public ModulePass { |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 300 | public: |
Alexey Samsonov | b0dcf61 | 2012-12-03 19:09:26 +0000 | [diff] [blame] | 301 | AddressSanitizerModule(bool CheckInitOrder = false, |
Alexey Samsonov | 11af9a8 | 2013-01-17 11:12:32 +0000 | [diff] [blame] | 302 | StringRef BlacklistFile = StringRef(), |
| 303 | bool ZeroBaseShadow = false) |
Alexey Samsonov | ee54827 | 2012-11-29 18:14:24 +0000 | [diff] [blame] | 304 | : ModulePass(ID), |
Alexey Samsonov | b0dcf61 | 2012-12-03 19:09:26 +0000 | [diff] [blame] | 305 | CheckInitOrder(CheckInitOrder || ClInitializers), |
| 306 | BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile |
Alexey Samsonov | 11af9a8 | 2013-01-17 11:12:32 +0000 | [diff] [blame] | 307 | : BlacklistFile), |
| 308 | ZeroBaseShadow(ZeroBaseShadow) {} |
Kostya Serebryany | 1416edc | 2012-11-28 10:31:36 +0000 | [diff] [blame] | 309 | bool runOnModule(Module &M); |
| 310 | static char ID; // Pass identification, replacement for typeid |
Kostya Serebryany | 1416edc | 2012-11-28 10:31:36 +0000 | [diff] [blame] | 311 | virtual const char *getPassName() const { |
| 312 | return "AddressSanitizerModule"; |
| 313 | } |
Alexey Samsonov | f985f44 | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 314 | |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 315 | private: |
Alexey Samsonov | 4684858 | 2012-12-25 12:28:20 +0000 | [diff] [blame] | 316 | void initializeCallbacks(Module &M); |
| 317 | |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 318 | bool ShouldInstrumentGlobal(GlobalVariable *G); |
| 319 | void createInitializerPoisonCalls(Module &M, Value *FirstAddr, |
| 320 | Value *LastAddr); |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 321 | size_t RedzoneSize() const { |
| 322 | return RedzoneSizeForScale(Mapping.Scale); |
| 323 | } |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 324 | |
Alexey Samsonov | ee54827 | 2012-11-29 18:14:24 +0000 | [diff] [blame] | 325 | bool CheckInitOrder; |
Alexey Samsonov | b0dcf61 | 2012-12-03 19:09:26 +0000 | [diff] [blame] | 326 | SmallString<64> BlacklistFile; |
Alexey Samsonov | 11af9a8 | 2013-01-17 11:12:32 +0000 | [diff] [blame] | 327 | bool ZeroBaseShadow; |
| 328 | |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 329 | OwningPtr<BlackList> BL; |
| 330 | SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals; |
| 331 | Type *IntptrTy; |
| 332 | LLVMContext *C; |
Kostya Serebryany | 1416edc | 2012-11-28 10:31:36 +0000 | [diff] [blame] | 333 | DataLayout *TD; |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 334 | ShadowMapping Mapping; |
Alexey Samsonov | 4684858 | 2012-12-25 12:28:20 +0000 | [diff] [blame] | 335 | Function *AsanPoisonGlobals; |
| 336 | Function *AsanUnpoisonGlobals; |
| 337 | Function *AsanRegisterGlobals; |
| 338 | Function *AsanUnregisterGlobals; |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 339 | }; |
| 340 | |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 341 | // Stack poisoning does not play well with exception handling. |
| 342 | // When an exception is thrown, we essentially bypass the code |
| 343 | // that unpoisones the stack. This is why the run-time library has |
| 344 | // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire |
| 345 | // stack in the interceptor. This however does not work inside the |
| 346 | // actual function which catches the exception. Most likely because the |
| 347 | // compiler hoists the load of the shadow value somewhere too high. |
| 348 | // This causes asan to report a non-existing bug on 453.povray. |
| 349 | // It sounds like an LLVM bug. |
| 350 | struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> { |
| 351 | Function &F; |
| 352 | AddressSanitizer &ASan; |
| 353 | DIBuilder DIB; |
| 354 | LLVMContext *C; |
| 355 | Type *IntptrTy; |
| 356 | Type *IntptrPtrTy; |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 357 | ShadowMapping Mapping; |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 358 | |
| 359 | SmallVector<AllocaInst*, 16> AllocaVec; |
| 360 | SmallVector<Instruction*, 8> RetVec; |
| 361 | uint64_t TotalStackSize; |
| 362 | unsigned StackAlignment; |
| 363 | |
| 364 | Function *AsanStackMallocFunc, *AsanStackFreeFunc; |
| 365 | Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc; |
| 366 | |
Alexey Samsonov | 1c8b825 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 367 | // Stores a place and arguments of poisoning/unpoisoning call for alloca. |
| 368 | struct AllocaPoisonCall { |
| 369 | IntrinsicInst *InsBefore; |
| 370 | uint64_t Size; |
| 371 | bool DoPoison; |
| 372 | }; |
| 373 | SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec; |
| 374 | |
| 375 | // Maps Value to an AllocaInst from which the Value is originated. |
| 376 | typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy; |
| 377 | AllocaForValueMapTy AllocaForValue; |
| 378 | |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 379 | FunctionStackPoisoner(Function &F, AddressSanitizer &ASan) |
| 380 | : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C), |
| 381 | IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)), |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 382 | Mapping(ASan.Mapping), |
| 383 | TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {} |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 384 | |
| 385 | bool runOnFunction() { |
| 386 | if (!ClStack) return false; |
| 387 | // Collect alloca, ret, lifetime instructions etc. |
| 388 | for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()), |
| 389 | DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) { |
| 390 | BasicBlock *BB = *DI; |
| 391 | visit(*BB); |
| 392 | } |
| 393 | if (AllocaVec.empty()) return false; |
| 394 | |
| 395 | initializeCallbacks(*F.getParent()); |
| 396 | |
| 397 | poisonStack(); |
| 398 | |
| 399 | if (ClDebugStack) { |
| 400 | DEBUG(dbgs() << F); |
| 401 | } |
| 402 | return true; |
| 403 | } |
| 404 | |
| 405 | // Finds all static Alloca instructions and puts |
| 406 | // poisoned red zones around all of them. |
| 407 | // Then unpoison everything back before the function returns. |
| 408 | void poisonStack(); |
| 409 | |
| 410 | // ----------------------- Visitors. |
| 411 | /// \brief Collect all Ret instructions. |
| 412 | void visitReturnInst(ReturnInst &RI) { |
| 413 | RetVec.push_back(&RI); |
| 414 | } |
| 415 | |
| 416 | /// \brief Collect Alloca instructions we want (and can) handle. |
| 417 | void visitAllocaInst(AllocaInst &AI) { |
Alexey Samsonov | 1c8b825 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 418 | if (!isInterestingAlloca(AI)) return; |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 419 | |
| 420 | StackAlignment = std::max(StackAlignment, AI.getAlignment()); |
| 421 | AllocaVec.push_back(&AI); |
| 422 | uint64_t AlignedSize = getAlignedAllocaSize(&AI); |
| 423 | TotalStackSize += AlignedSize; |
| 424 | } |
| 425 | |
Alexey Samsonov | 1c8b825 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 426 | /// \brief Collect lifetime intrinsic calls to check for use-after-scope |
| 427 | /// errors. |
| 428 | void visitIntrinsicInst(IntrinsicInst &II) { |
| 429 | if (!ASan.CheckLifetime) return; |
| 430 | Intrinsic::ID ID = II.getIntrinsicID(); |
| 431 | if (ID != Intrinsic::lifetime_start && |
| 432 | ID != Intrinsic::lifetime_end) |
| 433 | return; |
| 434 | // Found lifetime intrinsic, add ASan instrumentation if necessary. |
| 435 | ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0)); |
| 436 | // If size argument is undefined, don't do anything. |
| 437 | if (Size->isMinusOne()) return; |
| 438 | // Check that size doesn't saturate uint64_t and can |
| 439 | // be stored in IntptrTy. |
| 440 | const uint64_t SizeValue = Size->getValue().getLimitedValue(); |
| 441 | if (SizeValue == ~0ULL || |
| 442 | !ConstantInt::isValueValidForType(IntptrTy, SizeValue)) |
| 443 | return; |
| 444 | // Find alloca instruction that corresponds to llvm.lifetime argument. |
| 445 | AllocaInst *AI = findAllocaForValue(II.getArgOperand(1)); |
| 446 | if (!AI) return; |
| 447 | bool DoPoison = (ID == Intrinsic::lifetime_end); |
| 448 | AllocaPoisonCall APC = {&II, SizeValue, DoPoison}; |
| 449 | AllocaPoisonCallVec.push_back(APC); |
| 450 | } |
| 451 | |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 452 | // ---------------------- Helpers. |
| 453 | void initializeCallbacks(Module &M); |
| 454 | |
Alexey Samsonov | 1c8b825 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 455 | // Check if we want (and can) handle this alloca. |
| 456 | bool isInterestingAlloca(AllocaInst &AI) { |
| 457 | return (!AI.isArrayAllocation() && |
| 458 | AI.isStaticAlloca() && |
| 459 | AI.getAllocatedType()->isSized()); |
| 460 | } |
| 461 | |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 462 | size_t RedzoneSize() const { |
| 463 | return RedzoneSizeForScale(Mapping.Scale); |
| 464 | } |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 465 | uint64_t getAllocaSizeInBytes(AllocaInst *AI) { |
| 466 | Type *Ty = AI->getAllocatedType(); |
| 467 | uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty); |
| 468 | return SizeInBytes; |
| 469 | } |
| 470 | uint64_t getAlignedSize(uint64_t SizeInBytes) { |
| 471 | size_t RZ = RedzoneSize(); |
| 472 | return ((SizeInBytes + RZ - 1) / RZ) * RZ; |
| 473 | } |
| 474 | uint64_t getAlignedAllocaSize(AllocaInst *AI) { |
| 475 | uint64_t SizeInBytes = getAllocaSizeInBytes(AI); |
| 476 | return getAlignedSize(SizeInBytes); |
| 477 | } |
Alexey Samsonov | 1c8b825 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 478 | /// Finds alloca where the value comes from. |
| 479 | AllocaInst *findAllocaForValue(Value *V); |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 480 | void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, |
| 481 | Value *ShadowBase, bool DoPoison); |
| 482 | void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison); |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 483 | }; |
| 484 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 485 | } // namespace |
| 486 | |
| 487 | char AddressSanitizer::ID = 0; |
| 488 | INITIALIZE_PASS(AddressSanitizer, "asan", |
| 489 | "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", |
| 490 | false, false) |
Alexey Samsonov | ee54827 | 2012-11-29 18:14:24 +0000 | [diff] [blame] | 491 | FunctionPass *llvm::createAddressSanitizerFunctionPass( |
Alexey Samsonov | b0dcf61 | 2012-12-03 19:09:26 +0000 | [diff] [blame] | 492 | bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime, |
Alexey Samsonov | 11af9a8 | 2013-01-17 11:12:32 +0000 | [diff] [blame] | 493 | StringRef BlacklistFile, bool ZeroBaseShadow) { |
Alexey Samsonov | ee54827 | 2012-11-29 18:14:24 +0000 | [diff] [blame] | 494 | return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn, |
Alexey Samsonov | 11af9a8 | 2013-01-17 11:12:32 +0000 | [diff] [blame] | 495 | CheckLifetime, BlacklistFile, ZeroBaseShadow); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 496 | } |
| 497 | |
Kostya Serebryany | 1416edc | 2012-11-28 10:31:36 +0000 | [diff] [blame] | 498 | char AddressSanitizerModule::ID = 0; |
| 499 | INITIALIZE_PASS(AddressSanitizerModule, "asan-module", |
| 500 | "AddressSanitizer: detects use-after-free and out-of-bounds bugs." |
| 501 | "ModulePass", false, false) |
Alexey Samsonov | b0dcf61 | 2012-12-03 19:09:26 +0000 | [diff] [blame] | 502 | ModulePass *llvm::createAddressSanitizerModulePass( |
Alexey Samsonov | 11af9a8 | 2013-01-17 11:12:32 +0000 | [diff] [blame] | 503 | bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) { |
| 504 | return new AddressSanitizerModule(CheckInitOrder, BlacklistFile, |
| 505 | ZeroBaseShadow); |
Alexander Potapenko | 2587804 | 2012-01-23 11:22:43 +0000 | [diff] [blame] | 506 | } |
| 507 | |
Kostya Serebryany | 2735cf4 | 2012-07-16 17:12:07 +0000 | [diff] [blame] | 508 | static size_t TypeSizeToSizeIndex(uint32_t TypeSize) { |
| 509 | size_t Res = CountTrailingZeros_32(TypeSize / 8); |
| 510 | assert(Res < kNumberOfAccessSizes); |
| 511 | return Res; |
| 512 | } |
| 513 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 514 | // Create a constant for Str so that we can pass it to the run-time lib. |
| 515 | static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) { |
Chris Lattner | 18c7f80 | 2012-02-05 02:29:43 +0000 | [diff] [blame] | 516 | Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 517 | return new GlobalVariable(M, StrConst->getType(), true, |
Kostya Serebryany | 51c7c65 | 2012-11-20 14:16:08 +0000 | [diff] [blame] | 518 | GlobalValue::PrivateLinkage, StrConst, |
| 519 | kAsanGenPrefix); |
| 520 | } |
| 521 | |
| 522 | static bool GlobalWasGeneratedByAsan(GlobalVariable *G) { |
| 523 | return G->getName().find(kAsanGenPrefix) == 0; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 524 | } |
| 525 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 526 | Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) { |
| 527 | // Shadow >> scale |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 528 | Shadow = IRB.CreateLShr(Shadow, Mapping.Scale); |
| 529 | if (Mapping.Offset == 0) |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 530 | return Shadow; |
| 531 | // (Shadow >> scale) | offset |
Kostya Serebryany | 48a615f | 2013-01-23 12:54:55 +0000 | [diff] [blame] | 532 | if (Mapping.OrShadowOffset) |
| 533 | return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset)); |
| 534 | else |
| 535 | return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset)); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 536 | } |
| 537 | |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 538 | void AddressSanitizer::instrumentMemIntrinsicParam( |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 539 | Instruction *OrigIns, |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 540 | Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) { |
| 541 | // Check the first byte. |
| 542 | { |
| 543 | IRBuilder<> IRB(InsertBefore); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 544 | instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 545 | } |
| 546 | // Check the last byte. |
| 547 | { |
| 548 | IRBuilder<> IRB(InsertBefore); |
| 549 | Value *SizeMinusOne = IRB.CreateSub( |
| 550 | Size, ConstantInt::get(Size->getType(), 1)); |
| 551 | SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false); |
| 552 | Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy); |
| 553 | Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 554 | instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 555 | } |
| 556 | } |
| 557 | |
| 558 | // Instrument memset/memmove/memcpy |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 559 | bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 560 | Value *Dst = MI->getDest(); |
| 561 | MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI); |
Kostya Serebryany | 2735cf4 | 2012-07-16 17:12:07 +0000 | [diff] [blame] | 562 | Value *Src = MemTran ? MemTran->getSource() : 0; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 563 | Value *Length = MI->getLength(); |
| 564 | |
| 565 | Constant *ConstLength = dyn_cast<Constant>(Length); |
| 566 | Instruction *InsertBefore = MI; |
| 567 | if (ConstLength) { |
| 568 | if (ConstLength->isNullValue()) return false; |
| 569 | } else { |
| 570 | // The size is not a constant so it could be zero -- check at run-time. |
| 571 | IRBuilder<> IRB(InsertBefore); |
| 572 | |
| 573 | Value *Cmp = IRB.CreateICmpNE(Length, |
Kostya Serebryany | 56139bc | 2012-07-02 11:42:29 +0000 | [diff] [blame] | 574 | Constant::getNullValue(Length->getType())); |
Evgeniy Stepanov | 4a2dec0 | 2012-10-19 10:48:31 +0000 | [diff] [blame] | 575 | InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 576 | } |
| 577 | |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 578 | instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 579 | if (Src) |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 580 | instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 581 | return true; |
| 582 | } |
| 583 | |
Kostya Serebryany | e6cf2e0 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 584 | // If I is an interesting memory access, return the PointerOperand |
| 585 | // and set IsWrite. Otherwise return NULL. |
| 586 | static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 587 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
Kostya Serebryany | e6cf2e0 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 588 | if (!ClInstrumentReads) return NULL; |
| 589 | *IsWrite = false; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 590 | return LI->getPointerOperand(); |
| 591 | } |
Kostya Serebryany | e6cf2e0 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 592 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
| 593 | if (!ClInstrumentWrites) return NULL; |
| 594 | *IsWrite = true; |
| 595 | return SI->getPointerOperand(); |
| 596 | } |
| 597 | if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) { |
| 598 | if (!ClInstrumentAtomics) return NULL; |
| 599 | *IsWrite = true; |
| 600 | return RMW->getPointerOperand(); |
| 601 | } |
| 602 | if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) { |
| 603 | if (!ClInstrumentAtomics) return NULL; |
| 604 | *IsWrite = true; |
| 605 | return XCHG->getPointerOperand(); |
| 606 | } |
| 607 | return NULL; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 608 | } |
| 609 | |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 610 | void AddressSanitizer::instrumentMop(Instruction *I) { |
Axel Naumann | 3780ad8 | 2012-09-17 14:20:57 +0000 | [diff] [blame] | 611 | bool IsWrite = false; |
Kostya Serebryany | e6cf2e0 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 612 | Value *Addr = isInterestingMemoryAccess(I, &IsWrite); |
| 613 | assert(Addr); |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 614 | if (ClOpt && ClOptGlobals) { |
| 615 | if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) { |
| 616 | // If initialization order checking is disabled, a simple access to a |
| 617 | // dynamically initialized global is always valid. |
Alexey Samsonov | ee54827 | 2012-11-29 18:14:24 +0000 | [diff] [blame] | 618 | if (!CheckInitOrder) |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 619 | return; |
| 620 | // If a global variable does not have dynamic initialization we don't |
Kostya Serebryany | 4077906 | 2012-11-20 13:11:32 +0000 | [diff] [blame] | 621 | // have to instrument it. However, if a global does not have initailizer |
| 622 | // at all, we assume it has dynamic initializer (in other TU). |
| 623 | if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G)) |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 624 | return; |
| 625 | } |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 626 | } |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 627 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 628 | Type *OrigPtrTy = Addr->getType(); |
| 629 | Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType(); |
| 630 | |
| 631 | assert(OrigTy->isSized()); |
| 632 | uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy); |
| 633 | |
| 634 | if (TypeSize != 8 && TypeSize != 16 && |
| 635 | TypeSize != 32 && TypeSize != 64 && TypeSize != 128) { |
| 636 | // Ignore all unusual sizes. |
| 637 | return; |
| 638 | } |
| 639 | |
| 640 | IRBuilder<> IRB(I); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 641 | instrumentAddress(I, IRB, Addr, TypeSize, IsWrite); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 642 | } |
| 643 | |
Alexander Potapenko | 55cabae | 2012-04-23 10:47:31 +0000 | [diff] [blame] | 644 | // Validate the result of Module::getOrInsertFunction called for an interface |
| 645 | // function of AddressSanitizer. If the instrumented module defines a function |
| 646 | // with the same name, their prototypes must match, otherwise |
| 647 | // getOrInsertFunction returns a bitcast. |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 648 | static Function *checkInterfaceFunction(Constant *FuncOrBitcast) { |
Alexander Potapenko | 55cabae | 2012-04-23 10:47:31 +0000 | [diff] [blame] | 649 | if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast); |
| 650 | FuncOrBitcast->dump(); |
| 651 | report_fatal_error("trying to redefine an AddressSanitizer " |
| 652 | "interface function"); |
| 653 | } |
| 654 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 655 | Instruction *AddressSanitizer::generateCrashCode( |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 656 | Instruction *InsertBefore, Value *Addr, |
Kostya Serebryany | 4f0c696 | 2012-07-17 11:04:12 +0000 | [diff] [blame] | 657 | bool IsWrite, size_t AccessSizeIndex) { |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 658 | IRBuilder<> IRB(InsertBefore); |
| 659 | CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], |
| 660 | Addr); |
Kostya Serebryany | f7b0822 | 2012-07-20 09:54:50 +0000 | [diff] [blame] | 661 | // We don't do Call->setDoesNotReturn() because the BB already has |
| 662 | // UnreachableInst at the end. |
| 663 | // This EmptyAsm is required to avoid callback merge. |
| 664 | IRB.CreateCall(EmptyAsm); |
Kostya Serebryany | 3c7faae | 2012-01-06 18:09:21 +0000 | [diff] [blame] | 665 | return Call; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 666 | } |
| 667 | |
Kostya Serebryany | 2735cf4 | 2012-07-16 17:12:07 +0000 | [diff] [blame] | 668 | Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong, |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 669 | Value *ShadowValue, |
| 670 | uint32_t TypeSize) { |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 671 | size_t Granularity = 1 << Mapping.Scale; |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 672 | // Addr & (Granularity - 1) |
| 673 | Value *LastAccessedByte = IRB.CreateAnd( |
| 674 | AddrLong, ConstantInt::get(IntptrTy, Granularity - 1)); |
| 675 | // (Addr & (Granularity - 1)) + size - 1 |
| 676 | if (TypeSize / 8 > 1) |
| 677 | LastAccessedByte = IRB.CreateAdd( |
| 678 | LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)); |
| 679 | // (uint8_t) ((Addr & (Granularity-1)) + size - 1) |
| 680 | LastAccessedByte = IRB.CreateIntCast( |
Kostya Serebryany | 6e2d506 | 2012-08-15 08:58:58 +0000 | [diff] [blame] | 681 | LastAccessedByte, ShadowValue->getType(), false); |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 682 | // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue |
| 683 | return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue); |
| 684 | } |
| 685 | |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 686 | void AddressSanitizer::instrumentAddress(Instruction *OrigIns, |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 687 | IRBuilder<> &IRB, Value *Addr, |
| 688 | uint32_t TypeSize, bool IsWrite) { |
| 689 | Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy); |
| 690 | |
| 691 | Type *ShadowTy = IntegerType::get( |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 692 | *C, std::max(8U, TypeSize >> Mapping.Scale)); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 693 | Type *ShadowPtrTy = PointerType::get(ShadowTy, 0); |
| 694 | Value *ShadowPtr = memToShadow(AddrLong, IRB); |
| 695 | Value *CmpVal = Constant::getNullValue(ShadowTy); |
| 696 | Value *ShadowValue = IRB.CreateLoad( |
| 697 | IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy)); |
| 698 | |
| 699 | Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal); |
Kostya Serebryany | 11c2a47 | 2012-08-13 14:08:46 +0000 | [diff] [blame] | 700 | size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize); |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 701 | size_t Granularity = 1 << Mapping.Scale; |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 702 | TerminatorInst *CrashTerm = 0; |
| 703 | |
Kostya Serebryany | 6e2d506 | 2012-08-15 08:58:58 +0000 | [diff] [blame] | 704 | if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) { |
Evgeniy Stepanov | 4a2dec0 | 2012-10-19 10:48:31 +0000 | [diff] [blame] | 705 | TerminatorInst *CheckTerm = |
| 706 | SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false); |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 707 | assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional()); |
Kostya Serebryany | f7b0822 | 2012-07-20 09:54:50 +0000 | [diff] [blame] | 708 | BasicBlock *NextBB = CheckTerm->getSuccessor(0); |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 709 | IRB.SetInsertPoint(CheckTerm); |
| 710 | Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 711 | BasicBlock *CrashBlock = |
| 712 | BasicBlock::Create(*C, "", NextBB->getParent(), NextBB); |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 713 | CrashTerm = new UnreachableInst(*C, CrashBlock); |
Kostya Serebryany | f7b0822 | 2012-07-20 09:54:50 +0000 | [diff] [blame] | 714 | BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2); |
| 715 | ReplaceInstWithInst(CheckTerm, NewTerm); |
Kostya Serebryany | c0ed3e5 | 2012-07-16 16:15:40 +0000 | [diff] [blame] | 716 | } else { |
Evgeniy Stepanov | 4a2dec0 | 2012-10-19 10:48:31 +0000 | [diff] [blame] | 717 | CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 718 | } |
Kostya Serebryany | ebd6454 | 2012-08-14 14:04:51 +0000 | [diff] [blame] | 719 | |
| 720 | Instruction *Crash = |
| 721 | generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex); |
| 722 | Crash->setDebugLoc(OrigIns->getDebugLoc()); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 723 | } |
| 724 | |
Kostya Serebryany | 1416edc | 2012-11-28 10:31:36 +0000 | [diff] [blame] | 725 | void AddressSanitizerModule::createInitializerPoisonCalls( |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 726 | Module &M, Value *FirstAddr, Value *LastAddr) { |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 727 | // We do all of our poisoning and unpoisoning within _GLOBAL__I_a. |
| 728 | Function *GlobalInit = M.getFunction("_GLOBAL__I_a"); |
| 729 | // If that function is not present, this TU contains no globals, or they have |
| 730 | // all been optimized away |
| 731 | if (!GlobalInit) |
| 732 | return; |
| 733 | |
| 734 | // Set up the arguments to our poison/unpoison functions. |
| 735 | IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt()); |
| 736 | |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 737 | // Add a call to poison all external globals before the given function starts. |
| 738 | IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr); |
| 739 | |
| 740 | // Add calls to unpoison all globals before each return instruction. |
| 741 | for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end(); |
| 742 | I != E; ++I) { |
| 743 | if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) { |
| 744 | CallInst::Create(AsanUnpoisonGlobals, "", RI); |
| 745 | } |
| 746 | } |
| 747 | } |
| 748 | |
Kostya Serebryany | 1416edc | 2012-11-28 10:31:36 +0000 | [diff] [blame] | 749 | bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) { |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 750 | Type *Ty = cast<PointerType>(G->getType())->getElementType(); |
Kostya Serebryany | 324d96b | 2012-10-17 13:40:06 +0000 | [diff] [blame] | 751 | DEBUG(dbgs() << "GLOBAL: " << *G << "\n"); |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 752 | |
Kostya Serebryany | 59a4a47 | 2012-09-05 07:29:56 +0000 | [diff] [blame] | 753 | if (BL->isIn(*G)) return false; |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 754 | if (!Ty->isSized()) return false; |
| 755 | if (!G->hasInitializer()) return false; |
Kostya Serebryany | 51c7c65 | 2012-11-20 14:16:08 +0000 | [diff] [blame] | 756 | if (GlobalWasGeneratedByAsan(G)) return false; // Our own global. |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 757 | // Touch only those globals that will not be defined in other modules. |
| 758 | // Don't handle ODR type linkages since other modules may be built w/o asan. |
| 759 | if (G->getLinkage() != GlobalVariable::ExternalLinkage && |
| 760 | G->getLinkage() != GlobalVariable::PrivateLinkage && |
| 761 | G->getLinkage() != GlobalVariable::InternalLinkage) |
| 762 | return false; |
| 763 | // Two problems with thread-locals: |
| 764 | // - The address of the main thread's copy can't be computed at link-time. |
| 765 | // - Need to poison all copies, not just the main thread's one. |
| 766 | if (G->isThreadLocal()) |
| 767 | return false; |
| 768 | // For now, just ignore this Alloca if the alignment is large. |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 769 | if (G->getAlignment() > RedzoneSize()) return false; |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 770 | |
| 771 | // Ignore all the globals with the names starting with "\01L_OBJC_". |
| 772 | // Many of those are put into the .cstring section. The linker compresses |
| 773 | // that section by removing the spare \0s after the string terminator, so |
| 774 | // our redzones get broken. |
| 775 | if ((G->getName().find("\01L_OBJC_") == 0) || |
| 776 | (G->getName().find("\01l_OBJC_") == 0)) { |
| 777 | DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G); |
| 778 | return false; |
| 779 | } |
| 780 | |
| 781 | if (G->hasSection()) { |
| 782 | StringRef Section(G->getSection()); |
| 783 | // Ignore the globals from the __OBJC section. The ObjC runtime assumes |
| 784 | // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to |
| 785 | // them. |
| 786 | if ((Section.find("__OBJC,") == 0) || |
| 787 | (Section.find("__DATA, __objc_") == 0)) { |
| 788 | DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G); |
| 789 | return false; |
| 790 | } |
| 791 | // See http://code.google.com/p/address-sanitizer/issues/detail?id=32 |
| 792 | // Constant CFString instances are compiled in the following way: |
| 793 | // -- the string buffer is emitted into |
| 794 | // __TEXT,__cstring,cstring_literals |
| 795 | // -- the constant NSConstantString structure referencing that buffer |
| 796 | // is placed into __DATA,__cfstring |
| 797 | // Therefore there's no point in placing redzones into __DATA,__cfstring. |
| 798 | // Moreover, it causes the linker to crash on OS X 10.7 |
| 799 | if (Section.find("__DATA,__cfstring") == 0) { |
| 800 | DEBUG(dbgs() << "Ignoring CFString: " << *G); |
| 801 | return false; |
| 802 | } |
| 803 | } |
| 804 | |
| 805 | return true; |
| 806 | } |
| 807 | |
Alexey Samsonov | 4684858 | 2012-12-25 12:28:20 +0000 | [diff] [blame] | 808 | void AddressSanitizerModule::initializeCallbacks(Module &M) { |
| 809 | IRBuilder<> IRB(*C); |
| 810 | // Declare our poisoning and unpoisoning functions. |
| 811 | AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction( |
| 812 | kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL)); |
| 813 | AsanPoisonGlobals->setLinkage(Function::ExternalLinkage); |
| 814 | AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction( |
| 815 | kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL)); |
| 816 | AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage); |
| 817 | // Declare functions that register/unregister globals. |
| 818 | AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction( |
| 819 | kAsanRegisterGlobalsName, IRB.getVoidTy(), |
| 820 | IntptrTy, IntptrTy, NULL)); |
| 821 | AsanRegisterGlobals->setLinkage(Function::ExternalLinkage); |
| 822 | AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction( |
| 823 | kAsanUnregisterGlobalsName, |
| 824 | IRB.getVoidTy(), IntptrTy, IntptrTy, NULL)); |
| 825 | AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage); |
| 826 | } |
| 827 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 828 | // This function replaces all global variables with new variables that have |
| 829 | // trailing redzones. It also creates a function that poisons |
| 830 | // redzones and inserts this function into llvm.global_ctors. |
Kostya Serebryany | 1416edc | 2012-11-28 10:31:36 +0000 | [diff] [blame] | 831 | bool AddressSanitizerModule::runOnModule(Module &M) { |
| 832 | if (!ClGlobals) return false; |
| 833 | TD = getAnalysisIfAvailable<DataLayout>(); |
| 834 | if (!TD) |
| 835 | return false; |
Alexey Samsonov | b0dcf61 | 2012-12-03 19:09:26 +0000 | [diff] [blame] | 836 | BL.reset(new BlackList(BlacklistFile)); |
Alexey Samsonov | d6f62c8 | 2012-11-29 18:27:01 +0000 | [diff] [blame] | 837 | if (BL->isIn(M)) return false; |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 838 | C = &(M.getContext()); |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 839 | int LongSize = TD->getPointerSizeInBits(); |
| 840 | IntptrTy = Type::getIntNTy(*C, LongSize); |
Alexey Samsonov | 11af9a8 | 2013-01-17 11:12:32 +0000 | [diff] [blame] | 841 | Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow); |
Alexey Samsonov | 4684858 | 2012-12-25 12:28:20 +0000 | [diff] [blame] | 842 | initializeCallbacks(M); |
| 843 | DynamicallyInitializedGlobals.Init(M); |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 844 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 845 | SmallVector<GlobalVariable *, 16> GlobalsToChange; |
| 846 | |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 847 | for (Module::GlobalListType::iterator G = M.global_begin(), |
| 848 | E = M.global_end(); G != E; ++G) { |
| 849 | if (ShouldInstrumentGlobal(G)) |
| 850 | GlobalsToChange.push_back(G); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 851 | } |
| 852 | |
| 853 | size_t n = GlobalsToChange.size(); |
| 854 | if (n == 0) return false; |
| 855 | |
| 856 | // A global is described by a structure |
| 857 | // size_t beg; |
| 858 | // size_t size; |
| 859 | // size_t size_with_redzone; |
| 860 | // const char *name; |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 861 | // size_t has_dynamic_init; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 862 | // We initialize an array of such structures and pass it to a run-time call. |
| 863 | StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy, |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 864 | IntptrTy, IntptrTy, |
| 865 | IntptrTy, NULL); |
| 866 | SmallVector<Constant *, 16> Initializers(n), DynamicInit; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 867 | |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 868 | |
| 869 | Function *CtorFunc = M.getFunction(kAsanModuleCtorName); |
| 870 | assert(CtorFunc); |
| 871 | IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator()); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 872 | |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 873 | // The addresses of the first and last dynamically initialized globals in |
| 874 | // this TU. Used in initialization order checking. |
| 875 | Value *FirstDynamic = 0, *LastDynamic = 0; |
| 876 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 877 | for (size_t i = 0; i < n; i++) { |
| 878 | GlobalVariable *G = GlobalsToChange[i]; |
| 879 | PointerType *PtrTy = cast<PointerType>(G->getType()); |
| 880 | Type *Ty = PtrTy->getElementType(); |
Kostya Serebryany | 208a4ff | 2012-03-21 15:28:50 +0000 | [diff] [blame] | 881 | uint64_t SizeInBytes = TD->getTypeAllocSize(Ty); |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 882 | size_t RZ = RedzoneSize(); |
| 883 | uint64_t RightRedzoneSize = RZ + (RZ - (SizeInBytes % RZ)); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 884 | Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize); |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 885 | // Determine whether this global should be poisoned in initialization. |
Kostya Serebryany | ca23d43 | 2012-11-20 13:00:01 +0000 | [diff] [blame] | 886 | bool GlobalHasDynamicInitializer = |
| 887 | DynamicallyInitializedGlobals.Contains(G); |
Kostya Serebryany | 59a4a47 | 2012-09-05 07:29:56 +0000 | [diff] [blame] | 888 | // Don't check initialization order if this global is blacklisted. |
Kostya Serebryany | 7dadac6 | 2012-09-05 09:00:18 +0000 | [diff] [blame] | 889 | GlobalHasDynamicInitializer &= !BL->isInInit(*G); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 890 | |
| 891 | StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL); |
| 892 | Constant *NewInitializer = ConstantStruct::get( |
| 893 | NewTy, G->getInitializer(), |
| 894 | Constant::getNullValue(RightRedZoneTy), NULL); |
| 895 | |
Kostya Serebryany | a4b2b1d | 2011-12-15 22:55:55 +0000 | [diff] [blame] | 896 | SmallString<2048> DescriptionOfGlobal = G->getName(); |
| 897 | DescriptionOfGlobal += " ("; |
| 898 | DescriptionOfGlobal += M.getModuleIdentifier(); |
| 899 | DescriptionOfGlobal += ")"; |
| 900 | GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 901 | |
| 902 | // Create a new global variable with enough space for a redzone. |
| 903 | GlobalVariable *NewGlobal = new GlobalVariable( |
| 904 | M, NewTy, G->isConstant(), G->getLinkage(), |
Hans Wennborg | ce718ff | 2012-06-23 11:37:03 +0000 | [diff] [blame] | 905 | NewInitializer, "", G, G->getThreadLocalMode()); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 906 | NewGlobal->copyAttributesFrom(G); |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 907 | NewGlobal->setAlignment(RZ); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 908 | |
| 909 | Value *Indices2[2]; |
| 910 | Indices2[0] = IRB.getInt32(0); |
| 911 | Indices2[1] = IRB.getInt32(0); |
| 912 | |
| 913 | G->replaceAllUsesWith( |
Kostya Serebryany | f1639ab | 2012-01-28 04:27:16 +0000 | [diff] [blame] | 914 | ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true)); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 915 | NewGlobal->takeName(G); |
| 916 | G->eraseFromParent(); |
| 917 | |
| 918 | Initializers[i] = ConstantStruct::get( |
| 919 | GlobalStructTy, |
| 920 | ConstantExpr::getPointerCast(NewGlobal, IntptrTy), |
| 921 | ConstantInt::get(IntptrTy, SizeInBytes), |
| 922 | ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize), |
| 923 | ConstantExpr::getPointerCast(Name, IntptrTy), |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 924 | ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer), |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 925 | NULL); |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 926 | |
| 927 | // Populate the first and last globals declared in this TU. |
Alexey Samsonov | ee54827 | 2012-11-29 18:14:24 +0000 | [diff] [blame] | 928 | if (CheckInitOrder && GlobalHasDynamicInitializer) { |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 929 | LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy); |
| 930 | if (FirstDynamic == 0) |
| 931 | FirstDynamic = LastDynamic; |
| 932 | } |
| 933 | |
Kostya Serebryany | 324d96b | 2012-10-17 13:40:06 +0000 | [diff] [blame] | 934 | DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n"); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 935 | } |
| 936 | |
| 937 | ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n); |
| 938 | GlobalVariable *AllGlobals = new GlobalVariable( |
| 939 | M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage, |
| 940 | ConstantArray::get(ArrayOfGlobalStructTy, Initializers), ""); |
| 941 | |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 942 | // Create calls for poisoning before initializers run and unpoisoning after. |
Alexey Samsonov | ee54827 | 2012-11-29 18:14:24 +0000 | [diff] [blame] | 943 | if (CheckInitOrder && FirstDynamic && LastDynamic) |
Kostya Serebryany | 9b9f87a | 2012-08-21 08:24:25 +0000 | [diff] [blame] | 944 | createInitializerPoisonCalls(M, FirstDynamic, LastDynamic); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 945 | IRB.CreateCall2(AsanRegisterGlobals, |
| 946 | IRB.CreatePointerCast(AllGlobals, IntptrTy), |
| 947 | ConstantInt::get(IntptrTy, n)); |
| 948 | |
Kostya Serebryany | 7bcfc99 | 2011-12-15 21:59:03 +0000 | [diff] [blame] | 949 | // We also need to unregister globals at the end, e.g. when a shared library |
| 950 | // gets closed. |
| 951 | Function *AsanDtorFunction = Function::Create( |
| 952 | FunctionType::get(Type::getVoidTy(*C), false), |
| 953 | GlobalValue::InternalLinkage, kAsanModuleDtorName, &M); |
| 954 | BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction); |
| 955 | IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB)); |
Kostya Serebryany | 7bcfc99 | 2011-12-15 21:59:03 +0000 | [diff] [blame] | 956 | IRB_Dtor.CreateCall2(AsanUnregisterGlobals, |
| 957 | IRB.CreatePointerCast(AllGlobals, IntptrTy), |
| 958 | ConstantInt::get(IntptrTy, n)); |
| 959 | appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority); |
| 960 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 961 | DEBUG(dbgs() << M); |
| 962 | return true; |
| 963 | } |
| 964 | |
Kostya Serebryany | 8b390ff | 2012-11-29 09:54:21 +0000 | [diff] [blame] | 965 | void AddressSanitizer::initializeCallbacks(Module &M) { |
| 966 | IRBuilder<> IRB(*C); |
Kostya Serebryany | 9db5b5f | 2012-07-16 14:09:42 +0000 | [diff] [blame] | 967 | // Create __asan_report* callbacks. |
| 968 | for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) { |
| 969 | for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes; |
| 970 | AccessSizeIndex++) { |
| 971 | // IsWrite and TypeSize are encoded in the function name. |
| 972 | std::string FunctionName = std::string(kAsanReportErrorTemplate) + |
| 973 | (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex); |
Kostya Serebryany | 4f0c696 | 2012-07-17 11:04:12 +0000 | [diff] [blame] | 974 | // If we are merging crash callbacks, they have two parameters. |
Kostya Serebryany | 7846c1c | 2012-11-07 12:42:18 +0000 | [diff] [blame] | 975 | AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = |
| 976 | checkInterfaceFunction(M.getOrInsertFunction( |
| 977 | FunctionName, IRB.getVoidTy(), IntptrTy, NULL)); |
Kostya Serebryany | 9db5b5f | 2012-07-16 14:09:42 +0000 | [diff] [blame] | 978 | } |
| 979 | } |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 980 | |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 981 | AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction( |
| 982 | kAsanHandleNoReturnName, IRB.getVoidTy(), NULL)); |
Kostya Serebryany | f7b0822 | 2012-07-20 09:54:50 +0000 | [diff] [blame] | 983 | // We insert an empty inline asm after __asan_report* to avoid callback merge. |
| 984 | EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false), |
| 985 | StringRef(""), StringRef(""), |
| 986 | /*hasSideEffects=*/true); |
Kostya Serebryany | 8b390ff | 2012-11-29 09:54:21 +0000 | [diff] [blame] | 987 | } |
| 988 | |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 989 | void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const { |
Alexey Samsonov | 11af9a8 | 2013-01-17 11:12:32 +0000 | [diff] [blame] | 990 | // Tell the values of mapping offset and scale to the run-time. |
| 991 | GlobalValue *asan_mapping_offset = |
| 992 | new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage, |
| 993 | ConstantInt::get(IntptrTy, Mapping.Offset), |
| 994 | kAsanMappingOffsetName); |
| 995 | // Read the global, otherwise it may be optimized away. |
| 996 | IRB.CreateLoad(asan_mapping_offset, true); |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 997 | |
Alexey Samsonov | 11af9a8 | 2013-01-17 11:12:32 +0000 | [diff] [blame] | 998 | GlobalValue *asan_mapping_scale = |
| 999 | new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage, |
| 1000 | ConstantInt::get(IntptrTy, Mapping.Scale), |
| 1001 | kAsanMappingScaleName); |
| 1002 | // Read the global, otherwise it may be optimized away. |
| 1003 | IRB.CreateLoad(asan_mapping_scale, true); |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 1004 | } |
| 1005 | |
Kostya Serebryany | 8b390ff | 2012-11-29 09:54:21 +0000 | [diff] [blame] | 1006 | // virtual |
| 1007 | bool AddressSanitizer::doInitialization(Module &M) { |
| 1008 | // Initialize the private fields. No one has accessed them before. |
| 1009 | TD = getAnalysisIfAvailable<DataLayout>(); |
| 1010 | |
| 1011 | if (!TD) |
| 1012 | return false; |
Alexey Samsonov | b0dcf61 | 2012-12-03 19:09:26 +0000 | [diff] [blame] | 1013 | BL.reset(new BlackList(BlacklistFile)); |
Kostya Serebryany | 8b390ff | 2012-11-29 09:54:21 +0000 | [diff] [blame] | 1014 | DynamicallyInitializedGlobals.Init(M); |
| 1015 | |
| 1016 | C = &(M.getContext()); |
| 1017 | LongSize = TD->getPointerSizeInBits(); |
| 1018 | IntptrTy = Type::getIntNTy(*C, LongSize); |
Kostya Serebryany | 8b390ff | 2012-11-29 09:54:21 +0000 | [diff] [blame] | 1019 | |
| 1020 | AsanCtorFunction = Function::Create( |
| 1021 | FunctionType::get(Type::getVoidTy(*C), false), |
| 1022 | GlobalValue::InternalLinkage, kAsanModuleCtorName, &M); |
| 1023 | BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction); |
| 1024 | // call __asan_init in the module ctor. |
| 1025 | IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB)); |
| 1026 | AsanInitFunction = checkInterfaceFunction( |
| 1027 | M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL)); |
| 1028 | AsanInitFunction->setLinkage(Function::ExternalLinkage); |
| 1029 | IRB.CreateCall(AsanInitFunction); |
Kostya Serebryany | 9db5b5f | 2012-07-16 14:09:42 +0000 | [diff] [blame] | 1030 | |
Alexey Samsonov | 11af9a8 | 2013-01-17 11:12:32 +0000 | [diff] [blame] | 1031 | Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow); |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 1032 | emitShadowMapping(M, IRB); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1033 | |
Kostya Serebryany | 7bcfc99 | 2011-12-15 21:59:03 +0000 | [diff] [blame] | 1034 | appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 1035 | return true; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1036 | } |
| 1037 | |
Kostya Serebryany | a1a8a32 | 2012-01-30 23:50:10 +0000 | [diff] [blame] | 1038 | bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) { |
| 1039 | // For each NSObject descendant having a +load method, this method is invoked |
| 1040 | // by the ObjC runtime before any of the static constructors is called. |
| 1041 | // Therefore we need to instrument such methods with a call to __asan_init |
| 1042 | // at the beginning in order to initialize our runtime before any access to |
| 1043 | // the shadow memory. |
| 1044 | // We cannot just ignore these methods, because they may call other |
| 1045 | // instrumented functions. |
| 1046 | if (F.getName().find(" load]") != std::string::npos) { |
| 1047 | IRBuilder<> IRB(F.begin()->begin()); |
| 1048 | IRB.CreateCall(AsanInitFunction); |
| 1049 | return true; |
| 1050 | } |
| 1051 | return false; |
| 1052 | } |
| 1053 | |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 1054 | bool AddressSanitizer::runOnFunction(Function &F) { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1055 | if (BL->isIn(F)) return false; |
| 1056 | if (&F == AsanCtorFunction) return false; |
Kostya Serebryany | 324d96b | 2012-10-17 13:40:06 +0000 | [diff] [blame] | 1057 | DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n"); |
Kostya Serebryany | 8b390ff | 2012-11-29 09:54:21 +0000 | [diff] [blame] | 1058 | initializeCallbacks(*F.getParent()); |
Kostya Serebryany | a1a8a32 | 2012-01-30 23:50:10 +0000 | [diff] [blame] | 1059 | |
| 1060 | // If needed, insert __asan_init before checking for AddressSafety attr. |
| 1061 | maybeInsertAsanInitAtFunctionEntry(F); |
| 1062 | |
Bill Wendling | 831737d | 2012-12-30 10:32:01 +0000 | [diff] [blame] | 1063 | if (!F.getAttributes().hasAttribute(AttributeSet::FunctionIndex, |
| 1064 | Attribute::AddressSafety)) |
Bill Wendling | 6765834 | 2012-10-09 07:45:08 +0000 | [diff] [blame] | 1065 | return false; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1066 | |
| 1067 | if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) |
| 1068 | return false; |
Bill Wendling | 6765834 | 2012-10-09 07:45:08 +0000 | [diff] [blame] | 1069 | |
| 1070 | // We want to instrument every address only once per basic block (unless there |
| 1071 | // are calls between uses). |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1072 | SmallSet<Value*, 16> TempsToInstrument; |
| 1073 | SmallVector<Instruction*, 16> ToInstrument; |
Kostya Serebryany | 95e3cf4 | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 1074 | SmallVector<Instruction*, 8> NoReturnCalls; |
Kostya Serebryany | e6cf2e0 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 1075 | bool IsWrite; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1076 | |
| 1077 | // Fill the set of memory operations to instrument. |
| 1078 | for (Function::iterator FI = F.begin(), FE = F.end(); |
| 1079 | FI != FE; ++FI) { |
| 1080 | TempsToInstrument.clear(); |
Kostya Serebryany | 324cbb8 | 2012-06-28 09:34:41 +0000 | [diff] [blame] | 1081 | int NumInsnsPerBB = 0; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1082 | for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); |
| 1083 | BI != BE; ++BI) { |
Kostya Serebryany | bcb55ce | 2012-01-11 18:15:23 +0000 | [diff] [blame] | 1084 | if (LooksLikeCodeInBug11395(BI)) return false; |
Kostya Serebryany | e6cf2e0 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 1085 | if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1086 | if (ClOpt && ClOptSameTemp) { |
| 1087 | if (!TempsToInstrument.insert(Addr)) |
| 1088 | continue; // We've seen this temp in the current BB. |
| 1089 | } |
| 1090 | } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) { |
| 1091 | // ok, take it. |
| 1092 | } else { |
Kostya Serebryany | 95e3cf4 | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 1093 | if (CallInst *CI = dyn_cast<CallInst>(BI)) { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1094 | // A call inside BB. |
| 1095 | TempsToInstrument.clear(); |
Kostya Serebryany | a17babb | 2012-11-30 11:08:59 +0000 | [diff] [blame] | 1096 | if (CI->doesNotReturn()) { |
Kostya Serebryany | 95e3cf4 | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 1097 | NoReturnCalls.push_back(CI); |
| 1098 | } |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1099 | } |
| 1100 | continue; |
| 1101 | } |
| 1102 | ToInstrument.push_back(BI); |
Kostya Serebryany | 324cbb8 | 2012-06-28 09:34:41 +0000 | [diff] [blame] | 1103 | NumInsnsPerBB++; |
| 1104 | if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) |
| 1105 | break; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1106 | } |
| 1107 | } |
| 1108 | |
| 1109 | // Instrument. |
| 1110 | int NumInstrumented = 0; |
| 1111 | for (size_t i = 0, n = ToInstrument.size(); i != n; i++) { |
| 1112 | Instruction *Inst = ToInstrument[i]; |
| 1113 | if (ClDebugMin < 0 || ClDebugMax < 0 || |
| 1114 | (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) { |
Kostya Serebryany | e6cf2e0 | 2012-05-30 09:04:06 +0000 | [diff] [blame] | 1115 | if (isInterestingMemoryAccess(Inst, &IsWrite)) |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 1116 | instrumentMop(Inst); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1117 | else |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 1118 | instrumentMemIntrinsic(cast<MemIntrinsic>(Inst)); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1119 | } |
| 1120 | NumInstrumented++; |
| 1121 | } |
| 1122 | |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1123 | FunctionStackPoisoner FSP(F, *this); |
| 1124 | bool ChangedStack = FSP.runOnFunction(); |
Kostya Serebryany | 95e3cf4 | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 1125 | |
| 1126 | // We must unpoison the stack before every NoReturn call (throw, _exit, etc). |
| 1127 | // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37 |
| 1128 | for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) { |
| 1129 | Instruction *CI = NoReturnCalls[i]; |
| 1130 | IRBuilder<> IRB(CI); |
Kostya Serebryany | ee4edec | 2012-10-15 14:20:06 +0000 | [diff] [blame] | 1131 | IRB.CreateCall(AsanHandleNoReturnFunc); |
Kostya Serebryany | 95e3cf4 | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 1132 | } |
Kostya Serebryany | 324d96b | 2012-10-17 13:40:06 +0000 | [diff] [blame] | 1133 | DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n"); |
Kostya Serebryany | 95e3cf4 | 2012-02-08 21:36:17 +0000 | [diff] [blame] | 1134 | |
| 1135 | return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty(); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1136 | } |
| 1137 | |
| 1138 | static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) { |
| 1139 | if (ShadowRedzoneSize == 1) return PoisonByte; |
| 1140 | if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte; |
| 1141 | if (ShadowRedzoneSize == 4) |
| 1142 | return (PoisonByte << 24) + (PoisonByte << 16) + |
| 1143 | (PoisonByte << 8) + (PoisonByte); |
Craig Topper | 8581438 | 2012-02-07 05:05:23 +0000 | [diff] [blame] | 1144 | llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4"); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1145 | } |
| 1146 | |
| 1147 | static void PoisonShadowPartialRightRedzone(uint8_t *Shadow, |
| 1148 | size_t Size, |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 1149 | size_t RZSize, |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1150 | size_t ShadowGranularity, |
| 1151 | uint8_t Magic) { |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 1152 | for (size_t i = 0; i < RZSize; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1153 | i+= ShadowGranularity, Shadow++) { |
| 1154 | if (i + ShadowGranularity <= Size) { |
| 1155 | *Shadow = 0; // fully addressable |
| 1156 | } else if (i >= Size) { |
| 1157 | *Shadow = Magic; // unaddressable |
| 1158 | } else { |
| 1159 | *Shadow = Size - i; // first Size-i bytes are addressable |
| 1160 | } |
| 1161 | } |
| 1162 | } |
| 1163 | |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1164 | // Workaround for bug 11395: we don't want to instrument stack in functions |
| 1165 | // with large assembly blobs (32-bit only), otherwise reg alloc may crash. |
| 1166 | // FIXME: remove once the bug 11395 is fixed. |
| 1167 | bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) { |
| 1168 | if (LongSize != 32) return false; |
| 1169 | CallInst *CI = dyn_cast<CallInst>(I); |
| 1170 | if (!CI || !CI->isInlineAsm()) return false; |
| 1171 | if (CI->getNumArgOperands() <= 5) return false; |
| 1172 | // We have inline assembly with quite a few arguments. |
| 1173 | return true; |
| 1174 | } |
| 1175 | |
| 1176 | void FunctionStackPoisoner::initializeCallbacks(Module &M) { |
| 1177 | IRBuilder<> IRB(*C); |
| 1178 | AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction( |
| 1179 | kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL)); |
| 1180 | AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction( |
| 1181 | kAsanStackFreeName, IRB.getVoidTy(), |
| 1182 | IntptrTy, IntptrTy, IntptrTy, NULL)); |
| 1183 | AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction( |
| 1184 | kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL)); |
| 1185 | AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction( |
| 1186 | kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL)); |
| 1187 | } |
| 1188 | |
| 1189 | void FunctionStackPoisoner::poisonRedZones( |
| 1190 | const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase, |
| 1191 | bool DoPoison) { |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 1192 | size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1193 | assert(ShadowRZSize >= 1 && ShadowRZSize <= 4); |
| 1194 | Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8); |
| 1195 | Type *RZPtrTy = PointerType::get(RZTy, 0); |
| 1196 | |
| 1197 | Value *PoisonLeft = ConstantInt::get(RZTy, |
| 1198 | ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize)); |
| 1199 | Value *PoisonMid = ConstantInt::get(RZTy, |
| 1200 | ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize)); |
| 1201 | Value *PoisonRight = ConstantInt::get(RZTy, |
| 1202 | ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize)); |
| 1203 | |
| 1204 | // poison the first red zone. |
| 1205 | IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy)); |
| 1206 | |
| 1207 | // poison all other red zones. |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 1208 | uint64_t Pos = RedzoneSize(); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1209 | for (size_t i = 0, n = AllocaVec.size(); i < n; i++) { |
| 1210 | AllocaInst *AI = AllocaVec[i]; |
| 1211 | uint64_t SizeInBytes = getAllocaSizeInBytes(AI); |
| 1212 | uint64_t AlignedSize = getAlignedAllocaSize(AI); |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 1213 | assert(AlignedSize - SizeInBytes < RedzoneSize()); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1214 | Value *Ptr = NULL; |
| 1215 | |
| 1216 | Pos += AlignedSize; |
| 1217 | |
| 1218 | assert(ShadowBase->getType() == IntptrTy); |
| 1219 | if (SizeInBytes < AlignedSize) { |
| 1220 | // Poison the partial redzone at right |
| 1221 | Ptr = IRB.CreateAdd( |
| 1222 | ShadowBase, ConstantInt::get(IntptrTy, |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 1223 | (Pos >> Mapping.Scale) - ShadowRZSize)); |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 1224 | size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1225 | uint32_t Poison = 0; |
| 1226 | if (DoPoison) { |
| 1227 | PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes, |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 1228 | RedzoneSize(), |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 1229 | 1ULL << Mapping.Scale, |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1230 | kAsanStackPartialRedzoneMagic); |
| 1231 | } |
| 1232 | Value *PartialPoison = ConstantInt::get(RZTy, Poison); |
| 1233 | IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy)); |
| 1234 | } |
| 1235 | |
| 1236 | // Poison the full redzone at right. |
| 1237 | Ptr = IRB.CreateAdd(ShadowBase, |
Alexey Samsonov | 19cd7e9 | 2013-01-16 13:23:28 +0000 | [diff] [blame] | 1238 | ConstantInt::get(IntptrTy, Pos >> Mapping.Scale)); |
Alexey Samsonov | 1c8b825 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 1239 | bool LastAlloca = (i == AllocaVec.size() - 1); |
| 1240 | Value *Poison = LastAlloca ? PoisonRight : PoisonMid; |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1241 | IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy)); |
| 1242 | |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 1243 | Pos += RedzoneSize(); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1244 | } |
| 1245 | } |
| 1246 | |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1247 | void FunctionStackPoisoner::poisonStack() { |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1248 | uint64_t LocalStackSize = TotalStackSize + |
| 1249 | (AllocaVec.size() + 1) * RedzoneSize(); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1250 | |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1251 | bool DoStackMalloc = ASan.CheckUseAfterReturn |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1252 | && LocalStackSize <= kMaxStackMallocSize; |
| 1253 | |
Alexey Samsonov | 1c8b825 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 1254 | assert(AllocaVec.size() > 0); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1255 | Instruction *InsBefore = AllocaVec[0]; |
| 1256 | IRBuilder<> IRB(InsBefore); |
| 1257 | |
| 1258 | |
| 1259 | Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize); |
| 1260 | AllocaInst *MyAlloca = |
| 1261 | new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore); |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1262 | if (ClRealignStack && StackAlignment < RedzoneSize()) |
| 1263 | StackAlignment = RedzoneSize(); |
| 1264 | MyAlloca->setAlignment(StackAlignment); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1265 | assert(MyAlloca->isStaticAlloca()); |
| 1266 | Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy); |
| 1267 | Value *LocalStackBase = OrigStackBase; |
| 1268 | |
| 1269 | if (DoStackMalloc) { |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1270 | LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc, |
| 1271 | ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase); |
| 1272 | } |
| 1273 | |
| 1274 | // This string will be parsed by the run-time (DescribeStackAddress). |
| 1275 | SmallString<2048> StackDescriptionStorage; |
| 1276 | raw_svector_ostream StackDescription(StackDescriptionStorage); |
| 1277 | StackDescription << F.getName() << " " << AllocaVec.size() << " "; |
| 1278 | |
Alexey Samsonov | 1c8b825 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 1279 | // Insert poison calls for lifetime intrinsics for alloca. |
| 1280 | bool HavePoisonedAllocas = false; |
| 1281 | for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) { |
| 1282 | const AllocaPoisonCall &APC = AllocaPoisonCallVec[i]; |
| 1283 | IntrinsicInst *II = APC.InsBefore; |
| 1284 | AllocaInst *AI = findAllocaForValue(II->getArgOperand(1)); |
| 1285 | assert(AI); |
| 1286 | IRBuilder<> IRB(II); |
| 1287 | poisonAlloca(AI, APC.Size, IRB, APC.DoPoison); |
| 1288 | HavePoisonedAllocas |= APC.DoPoison; |
| 1289 | } |
| 1290 | |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 1291 | uint64_t Pos = RedzoneSize(); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1292 | // Replace Alloca instructions with base+offset. |
| 1293 | for (size_t i = 0, n = AllocaVec.size(); i < n; i++) { |
| 1294 | AllocaInst *AI = AllocaVec[i]; |
| 1295 | uint64_t SizeInBytes = getAllocaSizeInBytes(AI); |
| 1296 | StringRef Name = AI->getName(); |
| 1297 | StackDescription << Pos << " " << SizeInBytes << " " |
| 1298 | << Name.size() << " " << Name << " "; |
| 1299 | uint64_t AlignedSize = getAlignedAllocaSize(AI); |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 1300 | assert((AlignedSize % RedzoneSize()) == 0); |
Alexey Samsonov | f985f44 | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 1301 | Value *NewAllocaPtr = IRB.CreateIntToPtr( |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1302 | IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)), |
Alexey Samsonov | f985f44 | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 1303 | AI->getType()); |
Alexey Samsonov | 1afbb51 | 2012-12-12 14:31:53 +0000 | [diff] [blame] | 1304 | replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB); |
Alexey Samsonov | f985f44 | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 1305 | AI->replaceAllUsesWith(NewAllocaPtr); |
Kostya Serebryany | b9a12ea | 2012-11-22 03:18:50 +0000 | [diff] [blame] | 1306 | Pos += AlignedSize + RedzoneSize(); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1307 | } |
| 1308 | assert(Pos == LocalStackSize); |
| 1309 | |
| 1310 | // Write the Magic value and the frame description constant to the redzone. |
| 1311 | Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy); |
| 1312 | IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic), |
| 1313 | BasePlus0); |
| 1314 | Value *BasePlus1 = IRB.CreateAdd(LocalStackBase, |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1315 | ConstantInt::get(IntptrTy, |
| 1316 | ASan.LongSize/8)); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1317 | BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy); |
Alexey Samsonov | 9ce84c1 | 2012-11-02 12:20:34 +0000 | [diff] [blame] | 1318 | GlobalVariable *StackDescriptionGlobal = |
Kostya Serebryany | a5f54f1 | 2012-11-01 13:42:40 +0000 | [diff] [blame] | 1319 | createPrivateGlobalForString(*F.getParent(), StackDescription.str()); |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1320 | Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, |
| 1321 | IntptrTy); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1322 | IRB.CreateStore(Description, BasePlus1); |
| 1323 | |
| 1324 | // Poison the stack redzones at the entry. |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1325 | Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB); |
| 1326 | poisonRedZones(AllocaVec, IRB, ShadowBase, true); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1327 | |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1328 | // Unpoison the stack before all ret instructions. |
| 1329 | for (size_t i = 0, n = RetVec.size(); i < n; i++) { |
| 1330 | Instruction *Ret = RetVec[i]; |
| 1331 | IRBuilder<> IRBRet(Ret); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1332 | // Mark the current frame as retired. |
| 1333 | IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic), |
| 1334 | BasePlus0); |
| 1335 | // Unpoison the stack. |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1336 | poisonRedZones(AllocaVec, IRBRet, ShadowBase, false); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1337 | if (DoStackMalloc) { |
Alexey Samsonov | f985f44 | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 1338 | // In use-after-return mode, mark the whole stack frame unaddressable. |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1339 | IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase, |
| 1340 | ConstantInt::get(IntptrTy, LocalStackSize), |
| 1341 | OrigStackBase); |
Alexey Samsonov | f985f44 | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 1342 | } else if (HavePoisonedAllocas) { |
| 1343 | // If we poisoned some allocas in llvm.lifetime analysis, |
| 1344 | // unpoison whole stack frame now. |
| 1345 | assert(LocalStackBase == OrigStackBase); |
| 1346 | poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1347 | } |
| 1348 | } |
| 1349 | |
Kostya Serebryany | bd0052a | 2012-10-19 06:20:53 +0000 | [diff] [blame] | 1350 | // We are done. Remove the old unused alloca instructions. |
| 1351 | for (size_t i = 0, n = AllocaVec.size(); i < n; i++) |
| 1352 | AllocaVec[i]->eraseFromParent(); |
Kostya Serebryany | 800e03f | 2011-11-16 01:35:23 +0000 | [diff] [blame] | 1353 | } |
Alexey Samsonov | f985f44 | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 1354 | |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1355 | void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size, |
| 1356 | IRBuilder<> IRB, bool DoPoison) { |
Alexey Samsonov | f985f44 | 2012-12-04 01:34:23 +0000 | [diff] [blame] | 1357 | // For now just insert the call to ASan runtime. |
| 1358 | Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy); |
| 1359 | Value *SizeArg = ConstantInt::get(IntptrTy, Size); |
| 1360 | IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc |
| 1361 | : AsanUnpoisonStackMemoryFunc, |
| 1362 | AddrArg, SizeArg); |
| 1363 | } |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1364 | |
| 1365 | // Handling llvm.lifetime intrinsics for a given %alloca: |
| 1366 | // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca. |
| 1367 | // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect |
| 1368 | // invalid accesses) and unpoison it for llvm.lifetime.start (the memory |
| 1369 | // could be poisoned by previous llvm.lifetime.end instruction, as the |
| 1370 | // variable may go in and out of scope several times, e.g. in loops). |
| 1371 | // (3) if we poisoned at least one %alloca in a function, |
| 1372 | // unpoison the whole stack frame at function exit. |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1373 | |
Alexey Samsonov | 1c8b825 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 1374 | AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) { |
| 1375 | if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) |
| 1376 | // We're intested only in allocas we can handle. |
| 1377 | return isInterestingAlloca(*AI) ? AI : 0; |
| 1378 | // See if we've already calculated (or started to calculate) alloca for a |
| 1379 | // given value. |
| 1380 | AllocaForValueMapTy::iterator I = AllocaForValue.find(V); |
| 1381 | if (I != AllocaForValue.end()) |
| 1382 | return I->second; |
| 1383 | // Store 0 while we're calculating alloca for value V to avoid |
| 1384 | // infinite recursion if the value references itself. |
| 1385 | AllocaForValue[V] = 0; |
| 1386 | AllocaInst *Res = 0; |
| 1387 | if (CastInst *CI = dyn_cast<CastInst>(V)) |
| 1388 | Res = findAllocaForValue(CI->getOperand(0)); |
| 1389 | else if (PHINode *PN = dyn_cast<PHINode>(V)) { |
| 1390 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 1391 | Value *IncValue = PN->getIncomingValue(i); |
| 1392 | // Allow self-referencing phi-nodes. |
| 1393 | if (IncValue == PN) continue; |
| 1394 | AllocaInst *IncValueAI = findAllocaForValue(IncValue); |
| 1395 | // AI for incoming values should exist and should all be equal. |
| 1396 | if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res)) |
| 1397 | return 0; |
| 1398 | Res = IncValueAI; |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1399 | } |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1400 | } |
Alexey Samsonov | 1c8b825 | 2012-12-27 08:50:58 +0000 | [diff] [blame] | 1401 | if (Res != 0) |
| 1402 | AllocaForValue[V] = Res; |
Alexey Samsonov | 59cca13 | 2012-12-25 12:04:36 +0000 | [diff] [blame] | 1403 | return Res; |
| 1404 | } |