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