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