blob: 828fbc04f4b86238cb1ed4fd99bc10c14aa68aba [file] [log] [blame]
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001//===-- 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 Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +000019#include "BlackList.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000020#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/OwningPtr.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000026#include "llvm/ADT/Triple.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/DataLayout.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000028#include "llvm/DIBuilder.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000029#include "llvm/Function.h"
30#include "llvm/IRBuilder.h"
31#include "llvm/InlineAsm.h"
32#include "llvm/IntrinsicInst.h"
33#include "llvm/LLVMContext.h"
34#include "llvm/Module.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/DataTypes.h"
37#include "llvm/Support/Debug.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000038#include "llvm/Support/raw_ostream.h"
39#include "llvm/Support/system_error.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000040#include "llvm/Target/TargetMachine.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000041#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000042#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000043#include "llvm/Transforms/Utils/ModuleUtils.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000044#include "llvm/Type.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000045#include <algorithm>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000046#include <string>
Kostya Serebryany800e03f2011-11-16 01:35:23 +000047
48using namespace llvm;
49
50static const uint64_t kDefaultShadowScale = 3;
51static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
52static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000053static const uint64_t kDefaultShadowOffsetAndroid = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000054
55static const size_t kMaxStackMallocSize = 1 << 16; // 64K
56static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
57static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
58
59static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000060static const char *kAsanModuleDtorName = "asan.module_dtor";
61static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000062static const char *kAsanReportErrorTemplate = "__asan_report_";
63static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000064static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +000065static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
66static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000067static const char *kAsanInitName = "__asan_init";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000068static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000069static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
70static const char *kAsanMappingScaleName = "__asan_mapping_scale";
71static const char *kAsanStackMallocName = "__asan_stack_malloc";
72static const char *kAsanStackFreeName = "__asan_stack_free";
Kostya Serebryany51c7c652012-11-20 14:16:08 +000073static const char *kAsanGenPrefix = "__asan_gen_";
Alexey Samsonovf985f442012-12-04 01:34:23 +000074static const char *kAsanPoisonStackMemoryName = "__asan_poison_stack_memory";
75static const char *kAsanUnpoisonStackMemoryName =
76 "__asan_unpoison_stack_memory";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000077
78static const int kAsanStackLeftRedzoneMagic = 0xf1;
79static const int kAsanStackMidRedzoneMagic = 0xf2;
80static const int kAsanStackRightRedzoneMagic = 0xf3;
81static const int kAsanStackPartialRedzoneMagic = 0xf4;
82
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000083// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
84static const size_t kNumberOfAccessSizes = 5;
85
Kostya Serebryany800e03f2011-11-16 01:35:23 +000086// Command-line flags.
87
88// This flag may need to be replaced with -f[no-]asan-reads.
89static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
90 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
91static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
92 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000093static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
94 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
95 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +000096static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
97 cl::desc("use instrumentation with slow path for all accesses"),
98 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000099// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000100// in any given BB. Normally, this should be set to unlimited (INT_MAX),
101// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
102// set it to 10000.
103static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
104 cl::init(10000),
105 cl::desc("maximal number of instructions to instrument in any given BB"),
106 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000107// This flag may need to be replaced with -f[no]asan-stack.
108static cl::opt<bool> ClStack("asan-stack",
109 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
110// This flag may need to be replaced with -f[no]asan-use-after-return.
111static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
112 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
113// This flag may need to be replaced with -f[no]asan-globals.
114static cl::opt<bool> ClGlobals("asan-globals",
115 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000116static cl::opt<bool> ClInitializers("asan-initialization-order",
117 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000118static cl::opt<bool> ClMemIntrin("asan-memintrin",
119 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Kostya Serebryany6c554122012-12-04 06:14:01 +0000120static cl::opt<bool> ClRealignStack("asan-realign-stack",
121 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000122static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
123 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000124 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000125
126// These flags allow to change the shadow mapping.
127// The shadow mapping looks like
128// Shadow = (Mem >> scale) + (1 << offset_log)
129static cl::opt<int> ClMappingScale("asan-mapping-scale",
130 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
131static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
132 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
133
134// Optimization flags. Not user visible, used mostly for testing
135// and benchmarking the tool.
136static cl::opt<bool> ClOpt("asan-opt",
137 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
138static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
139 cl::desc("Instrument the same temp just once"), cl::Hidden,
140 cl::init(true));
141static cl::opt<bool> ClOptGlobals("asan-opt-globals",
142 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
143
Alexey Samsonovee548272012-11-29 18:14:24 +0000144static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
145 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
146 cl::Hidden, cl::init(false));
147
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000148// Debug flags.
149static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
150 cl::init(0));
151static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
152 cl::Hidden, cl::init(0));
153static cl::opt<std::string> ClDebugFunc("asan-debug-func",
154 cl::Hidden, cl::desc("Debug func"));
155static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
156 cl::Hidden, cl::init(-1));
157static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
158 cl::Hidden, cl::init(-1));
159
160namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000161/// A set of dynamically initialized globals extracted from metadata.
162class SetOfDynamicallyInitializedGlobals {
163 public:
164 void Init(Module& M) {
165 // Clang generates metadata identifying all dynamically initialized globals.
166 NamedMDNode *DynamicGlobals =
167 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
168 if (!DynamicGlobals)
169 return;
170 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
171 MDNode *MDN = DynamicGlobals->getOperand(i);
172 assert(MDN->getNumOperands() == 1);
173 Value *VG = MDN->getOperand(0);
174 // The optimizer may optimize away a global entirely, in which case we
175 // cannot instrument access to it.
176 if (!VG)
177 continue;
178 DynInitGlobals.insert(cast<GlobalVariable>(VG));
179 }
180 }
181 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
182 private:
183 SmallSet<GlobalValue*, 32> DynInitGlobals;
184};
185
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000186static int MappingScale() {
187 return ClMappingScale ? ClMappingScale : kDefaultShadowScale;
188}
189
190static size_t RedzoneSize() {
191 // Redzone used for stack and globals is at least 32 bytes.
192 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
193 return std::max(32U, 1U << MappingScale());
194}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000195
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000196/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000197struct AddressSanitizer : public FunctionPass {
Alexey Samsonovee548272012-11-29 18:14:24 +0000198 AddressSanitizer(bool CheckInitOrder = false,
199 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000200 bool CheckLifetime = false,
201 StringRef BlacklistFile = StringRef())
Alexey Samsonovee548272012-11-29 18:14:24 +0000202 : FunctionPass(ID),
203 CheckInitOrder(CheckInitOrder || ClInitializers),
204 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000205 CheckLifetime(CheckLifetime || ClCheckLifetime),
206 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
207 : BlacklistFile) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000208 virtual const char *getPassName() const {
209 return "AddressSanitizerFunctionPass";
210 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000211 void instrumentMop(Instruction *I);
212 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000213 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000214 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
215 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000216 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000217 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000218 bool instrumentMemIntrinsic(MemIntrinsic *MI);
219 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000220 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000221 Instruction *InsertBefore, bool IsWrite);
222 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000223 bool runOnFunction(Function &F);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000224 void createInitializerPoisonCalls(Module &M,
225 Value *FirstAddr, Value *LastAddr);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000226 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000227 bool poisonStackInFunction(Function &F);
228 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000229 static char ID; // Pass identification, replacement for typeid
230
231 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000232 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000233 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
234 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanovd8313be2012-03-02 10:41:08 +0000235 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000236 return SizeInBytes;
237 }
238 uint64_t getAlignedSize(uint64_t SizeInBytes) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000239 size_t RZ = RedzoneSize();
240 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000241 }
242 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
243 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
244 return getAlignedSize(SizeInBytes);
245 }
246
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000247 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000248 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
249 Value *ShadowBase, bool DoPoison);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000250 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000251 void FindDynamicInitializers(Module &M);
Alexey Samsonovf985f442012-12-04 01:34:23 +0000252 /// Analyze lifetime intrinsics for given alloca. Use Value* instead of
253 /// AllocaInst* here, as we call this method after we merge all allocas into a
254 /// single one. Returns true if ASan added some instrumentation.
255 bool handleAllocaLifetime(Value *Alloca);
256 /// Analyze lifetime intrinsics for a specific value, casted from alloca.
257 /// Returns true if if ASan added some instrumentation.
258 bool handleValueLifetime(Value *V);
259 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000260
Alexey Samsonovee548272012-11-29 18:14:24 +0000261 bool CheckInitOrder;
262 bool CheckUseAfterReturn;
263 bool CheckLifetime;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000264 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000265 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000266 uint64_t MappingOffset;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000267 int LongSize;
268 Type *IntptrTy;
269 Type *IntptrPtrTy;
270 Function *AsanCtorFunction;
271 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000272 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
Alexey Samsonovf985f442012-12-04 01:34:23 +0000273 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000274 Function *AsanHandleNoReturnFunc;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000275 SmallString<64> BlacklistFile;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000276 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000277 // This array is indexed by AccessIsWrite and log2(AccessSize).
278 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000279 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000280 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000281};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000282
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000283class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000284 public:
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000285 AddressSanitizerModule(bool CheckInitOrder = false,
286 StringRef BlacklistFile = StringRef())
Alexey Samsonovee548272012-11-29 18:14:24 +0000287 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000288 CheckInitOrder(CheckInitOrder || ClInitializers),
289 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
290 : BlacklistFile) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000291 bool runOnModule(Module &M);
292 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000293 virtual const char *getPassName() const {
294 return "AddressSanitizerModule";
295 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000296
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000297 private:
298 bool ShouldInstrumentGlobal(GlobalVariable *G);
299 void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
300 Value *LastAddr);
301
Alexey Samsonovee548272012-11-29 18:14:24 +0000302 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000303 SmallString<64> BlacklistFile;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000304 OwningPtr<BlackList> BL;
305 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
306 Type *IntptrTy;
307 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000308 DataLayout *TD;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000309};
310
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000311} // namespace
312
313char AddressSanitizer::ID = 0;
314INITIALIZE_PASS(AddressSanitizer, "asan",
315 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
316 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000317FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000318 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
319 StringRef BlacklistFile) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000320 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000321 CheckLifetime, BlacklistFile);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000322}
323
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000324char AddressSanitizerModule::ID = 0;
325INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
326 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
327 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000328ModulePass *llvm::createAddressSanitizerModulePass(
329 bool CheckInitOrder, StringRef BlacklistFile) {
330 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile);
Alexander Potapenko25878042012-01-23 11:22:43 +0000331}
332
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000333static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
334 size_t Res = CountTrailingZeros_32(TypeSize / 8);
335 assert(Res < kNumberOfAccessSizes);
336 return Res;
337}
338
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000339// Create a constant for Str so that we can pass it to the run-time lib.
340static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000341 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000342 return new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000343 GlobalValue::PrivateLinkage, StrConst,
344 kAsanGenPrefix);
345}
346
347static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
348 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000349}
350
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000351Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
352 // Shadow >> scale
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000353 Shadow = IRB.CreateLShr(Shadow, MappingScale());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000354 if (MappingOffset == 0)
355 return Shadow;
356 // (Shadow >> scale) | offset
357 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
358 MappingOffset));
359}
360
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000361void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000362 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000363 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
364 // Check the first byte.
365 {
366 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000367 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000368 }
369 // Check the last byte.
370 {
371 IRBuilder<> IRB(InsertBefore);
372 Value *SizeMinusOne = IRB.CreateSub(
373 Size, ConstantInt::get(Size->getType(), 1));
374 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
375 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
376 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000377 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000378 }
379}
380
381// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000382bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000383 Value *Dst = MI->getDest();
384 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000385 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000386 Value *Length = MI->getLength();
387
388 Constant *ConstLength = dyn_cast<Constant>(Length);
389 Instruction *InsertBefore = MI;
390 if (ConstLength) {
391 if (ConstLength->isNullValue()) return false;
392 } else {
393 // The size is not a constant so it could be zero -- check at run-time.
394 IRBuilder<> IRB(InsertBefore);
395
396 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000397 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000398 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000399 }
400
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000401 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000402 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000403 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000404 return true;
405}
406
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000407// If I is an interesting memory access, return the PointerOperand
408// and set IsWrite. Otherwise return NULL.
409static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000410 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000411 if (!ClInstrumentReads) return NULL;
412 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000413 return LI->getPointerOperand();
414 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000415 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
416 if (!ClInstrumentWrites) return NULL;
417 *IsWrite = true;
418 return SI->getPointerOperand();
419 }
420 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
421 if (!ClInstrumentAtomics) return NULL;
422 *IsWrite = true;
423 return RMW->getPointerOperand();
424 }
425 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
426 if (!ClInstrumentAtomics) return NULL;
427 *IsWrite = true;
428 return XCHG->getPointerOperand();
429 }
430 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000431}
432
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000433void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000434 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000435 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
436 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000437 if (ClOpt && ClOptGlobals) {
438 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
439 // If initialization order checking is disabled, a simple access to a
440 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000441 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000442 return;
443 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000444 // have to instrument it. However, if a global does not have initailizer
445 // at all, we assume it has dynamic initializer (in other TU).
446 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000447 return;
448 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000449 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000450
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000451 Type *OrigPtrTy = Addr->getType();
452 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
453
454 assert(OrigTy->isSized());
455 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
456
457 if (TypeSize != 8 && TypeSize != 16 &&
458 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
459 // Ignore all unusual sizes.
460 return;
461 }
462
463 IRBuilder<> IRB(I);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000464 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000465}
466
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000467// Validate the result of Module::getOrInsertFunction called for an interface
468// function of AddressSanitizer. If the instrumented module defines a function
469// with the same name, their prototypes must match, otherwise
470// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000471static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000472 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
473 FuncOrBitcast->dump();
474 report_fatal_error("trying to redefine an AddressSanitizer "
475 "interface function");
476}
477
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000478Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000479 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000480 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000481 IRBuilder<> IRB(InsertBefore);
482 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
483 Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000484 // We don't do Call->setDoesNotReturn() because the BB already has
485 // UnreachableInst at the end.
486 // This EmptyAsm is required to avoid callback merge.
487 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000488 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000489}
490
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000491Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000492 Value *ShadowValue,
493 uint32_t TypeSize) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000494 size_t Granularity = 1 << MappingScale();
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000495 // Addr & (Granularity - 1)
496 Value *LastAccessedByte = IRB.CreateAnd(
497 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
498 // (Addr & (Granularity - 1)) + size - 1
499 if (TypeSize / 8 > 1)
500 LastAccessedByte = IRB.CreateAdd(
501 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
502 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
503 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000504 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000505 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
506 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
507}
508
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000509void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000510 IRBuilder<> &IRB, Value *Addr,
511 uint32_t TypeSize, bool IsWrite) {
512 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
513
514 Type *ShadowTy = IntegerType::get(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000515 *C, std::max(8U, TypeSize >> MappingScale()));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000516 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
517 Value *ShadowPtr = memToShadow(AddrLong, IRB);
518 Value *CmpVal = Constant::getNullValue(ShadowTy);
519 Value *ShadowValue = IRB.CreateLoad(
520 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
521
522 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000523 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000524 size_t Granularity = 1 << MappingScale();
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000525 TerminatorInst *CrashTerm = 0;
526
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000527 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000528 TerminatorInst *CheckTerm =
529 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000530 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000531 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000532 IRB.SetInsertPoint(CheckTerm);
533 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000534 BasicBlock *CrashBlock =
535 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000536 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000537 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
538 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000539 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000540 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000541 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000542
543 Instruction *Crash =
544 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
545 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000546}
547
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000548void AddressSanitizerModule::createInitializerPoisonCalls(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000549 Module &M, Value *FirstAddr, Value *LastAddr) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000550 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
551 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
552 // If that function is not present, this TU contains no globals, or they have
553 // all been optimized away
554 if (!GlobalInit)
555 return;
556
557 // Set up the arguments to our poison/unpoison functions.
558 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
559
560 // Declare our poisoning and unpoisoning functions.
561 Function *AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
562 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
563 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
564 Function *AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
565 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
566 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
567
568 // Add a call to poison all external globals before the given function starts.
569 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
570
571 // Add calls to unpoison all globals before each return instruction.
572 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
573 I != E; ++I) {
574 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
575 CallInst::Create(AsanUnpoisonGlobals, "", RI);
576 }
577 }
578}
579
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000580bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000581 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000582 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000583
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000584 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000585 if (!Ty->isSized()) return false;
586 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000587 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000588 // Touch only those globals that will not be defined in other modules.
589 // Don't handle ODR type linkages since other modules may be built w/o asan.
590 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
591 G->getLinkage() != GlobalVariable::PrivateLinkage &&
592 G->getLinkage() != GlobalVariable::InternalLinkage)
593 return false;
594 // Two problems with thread-locals:
595 // - The address of the main thread's copy can't be computed at link-time.
596 // - Need to poison all copies, not just the main thread's one.
597 if (G->isThreadLocal())
598 return false;
599 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000600 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000601
602 // Ignore all the globals with the names starting with "\01L_OBJC_".
603 // Many of those are put into the .cstring section. The linker compresses
604 // that section by removing the spare \0s after the string terminator, so
605 // our redzones get broken.
606 if ((G->getName().find("\01L_OBJC_") == 0) ||
607 (G->getName().find("\01l_OBJC_") == 0)) {
608 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
609 return false;
610 }
611
612 if (G->hasSection()) {
613 StringRef Section(G->getSection());
614 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
615 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
616 // them.
617 if ((Section.find("__OBJC,") == 0) ||
618 (Section.find("__DATA, __objc_") == 0)) {
619 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
620 return false;
621 }
622 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
623 // Constant CFString instances are compiled in the following way:
624 // -- the string buffer is emitted into
625 // __TEXT,__cstring,cstring_literals
626 // -- the constant NSConstantString structure referencing that buffer
627 // is placed into __DATA,__cfstring
628 // Therefore there's no point in placing redzones into __DATA,__cfstring.
629 // Moreover, it causes the linker to crash on OS X 10.7
630 if (Section.find("__DATA,__cfstring") == 0) {
631 DEBUG(dbgs() << "Ignoring CFString: " << *G);
632 return false;
633 }
634 }
635
636 return true;
637}
638
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000639// This function replaces all global variables with new variables that have
640// trailing redzones. It also creates a function that poisons
641// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000642bool AddressSanitizerModule::runOnModule(Module &M) {
643 if (!ClGlobals) return false;
644 TD = getAnalysisIfAvailable<DataLayout>();
645 if (!TD)
646 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000647 BL.reset(new BlackList(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000648 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000649 DynamicallyInitializedGlobals.Init(M);
650 C = &(M.getContext());
651 IntptrTy = Type::getIntNTy(*C, TD->getPointerSizeInBits());
652
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000653 SmallVector<GlobalVariable *, 16> GlobalsToChange;
654
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000655 for (Module::GlobalListType::iterator G = M.global_begin(),
656 E = M.global_end(); G != E; ++G) {
657 if (ShouldInstrumentGlobal(G))
658 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000659 }
660
661 size_t n = GlobalsToChange.size();
662 if (n == 0) return false;
663
664 // A global is described by a structure
665 // size_t beg;
666 // size_t size;
667 // size_t size_with_redzone;
668 // const char *name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000669 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000670 // We initialize an array of such structures and pass it to a run-time call.
671 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000672 IntptrTy, IntptrTy,
673 IntptrTy, NULL);
674 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000675
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000676
677 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
678 assert(CtorFunc);
679 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000680
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000681 // The addresses of the first and last dynamically initialized globals in
682 // this TU. Used in initialization order checking.
683 Value *FirstDynamic = 0, *LastDynamic = 0;
684
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000685 for (size_t i = 0; i < n; i++) {
686 GlobalVariable *G = GlobalsToChange[i];
687 PointerType *PtrTy = cast<PointerType>(G->getType());
688 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000689 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000690 size_t RZ = RedzoneSize();
691 uint64_t RightRedzoneSize = RZ + (RZ - (SizeInBytes % RZ));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000692 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000693 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000694 bool GlobalHasDynamicInitializer =
695 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000696 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000697 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000698
699 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
700 Constant *NewInitializer = ConstantStruct::get(
701 NewTy, G->getInitializer(),
702 Constant::getNullValue(RightRedZoneTy), NULL);
703
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000704 SmallString<2048> DescriptionOfGlobal = G->getName();
705 DescriptionOfGlobal += " (";
706 DescriptionOfGlobal += M.getModuleIdentifier();
707 DescriptionOfGlobal += ")";
708 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000709
710 // Create a new global variable with enough space for a redzone.
711 GlobalVariable *NewGlobal = new GlobalVariable(
712 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000713 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000714 NewGlobal->copyAttributesFrom(G);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000715 NewGlobal->setAlignment(RZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000716
717 Value *Indices2[2];
718 Indices2[0] = IRB.getInt32(0);
719 Indices2[1] = IRB.getInt32(0);
720
721 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000722 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000723 NewGlobal->takeName(G);
724 G->eraseFromParent();
725
726 Initializers[i] = ConstantStruct::get(
727 GlobalStructTy,
728 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
729 ConstantInt::get(IntptrTy, SizeInBytes),
730 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
731 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000732 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000733 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000734
735 // Populate the first and last globals declared in this TU.
Alexey Samsonovee548272012-11-29 18:14:24 +0000736 if (CheckInitOrder && GlobalHasDynamicInitializer) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000737 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
738 if (FirstDynamic == 0)
739 FirstDynamic = LastDynamic;
740 }
741
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000742 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000743 }
744
745 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
746 GlobalVariable *AllGlobals = new GlobalVariable(
747 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
748 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
749
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000750 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovee548272012-11-29 18:14:24 +0000751 if (CheckInitOrder && FirstDynamic && LastDynamic)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000752 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
753
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000754 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000755 kAsanRegisterGlobalsName, IRB.getVoidTy(),
756 IntptrTy, IntptrTy, NULL));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000757 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
758
759 IRB.CreateCall2(AsanRegisterGlobals,
760 IRB.CreatePointerCast(AllGlobals, IntptrTy),
761 ConstantInt::get(IntptrTy, n));
762
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000763 // We also need to unregister globals at the end, e.g. when a shared library
764 // gets closed.
765 Function *AsanDtorFunction = Function::Create(
766 FunctionType::get(Type::getVoidTy(*C), false),
767 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
768 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
769 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000770 Function *AsanUnregisterGlobals =
771 checkInterfaceFunction(M.getOrInsertFunction(
772 kAsanUnregisterGlobalsName,
773 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000774 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
775
776 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
777 IRB.CreatePointerCast(AllGlobals, IntptrTy),
778 ConstantInt::get(IntptrTy, n));
779 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
780
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000781 DEBUG(dbgs() << M);
782 return true;
783}
784
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000785void AddressSanitizer::initializeCallbacks(Module &M) {
786 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000787 // Create __asan_report* callbacks.
788 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
789 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
790 AccessSizeIndex++) {
791 // IsWrite and TypeSize are encoded in the function name.
792 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
793 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000794 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +0000795 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
796 checkInterfaceFunction(M.getOrInsertFunction(
797 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000798 }
799 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000800
801 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
802 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
803 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
804 kAsanStackFreeName, IRB.getVoidTy(),
805 IntptrTy, IntptrTy, IntptrTy, NULL));
806 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
807 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Alexey Samsonovf985f442012-12-04 01:34:23 +0000808 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
809 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
810 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
811 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000812
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000813 // We insert an empty inline asm after __asan_report* to avoid callback merge.
814 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
815 StringRef(""), StringRef(""),
816 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000817}
818
819// virtual
820bool AddressSanitizer::doInitialization(Module &M) {
821 // Initialize the private fields. No one has accessed them before.
822 TD = getAnalysisIfAvailable<DataLayout>();
823
824 if (!TD)
825 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000826 BL.reset(new BlackList(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000827 DynamicallyInitializedGlobals.Init(M);
828
829 C = &(M.getContext());
830 LongSize = TD->getPointerSizeInBits();
831 IntptrTy = Type::getIntNTy(*C, LongSize);
832 IntptrPtrTy = PointerType::get(IntptrTy, 0);
833
834 AsanCtorFunction = Function::Create(
835 FunctionType::get(Type::getVoidTy(*C), false),
836 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
837 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
838 // call __asan_init in the module ctor.
839 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
840 AsanInitFunction = checkInterfaceFunction(
841 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
842 AsanInitFunction->setLinkage(Function::ExternalLinkage);
843 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000844
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000845 llvm::Triple targetTriple(M.getTargetTriple());
Logan Chien43bf7092012-09-02 09:29:46 +0000846 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000847
848 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
849 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000850 if (ClMappingOffsetLog >= 0) {
851 if (ClMappingOffsetLog == 0) {
852 // special case
853 MappingOffset = 0;
854 } else {
855 MappingOffset = 1ULL << ClMappingOffsetLog;
856 }
857 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000858
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000859
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000860 if (ClMappingOffsetLog >= 0) {
861 // Tell the run-time the current values of mapping offset and scale.
862 GlobalValue *asan_mapping_offset =
863 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
864 ConstantInt::get(IntptrTy, MappingOffset),
865 kAsanMappingOffsetName);
866 // Read the global, otherwise it may be optimized away.
867 IRB.CreateLoad(asan_mapping_offset, true);
868 }
869 if (ClMappingScale) {
870 GlobalValue *asan_mapping_scale =
871 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000872 ConstantInt::get(IntptrTy, MappingScale()),
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000873 kAsanMappingScaleName);
874 // Read the global, otherwise it may be optimized away.
875 IRB.CreateLoad(asan_mapping_scale, true);
876 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000877
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000878 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryany9b027412011-12-12 18:01:46 +0000879
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000880 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000881}
882
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000883bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
884 // For each NSObject descendant having a +load method, this method is invoked
885 // by the ObjC runtime before any of the static constructors is called.
886 // Therefore we need to instrument such methods with a call to __asan_init
887 // at the beginning in order to initialize our runtime before any access to
888 // the shadow memory.
889 // We cannot just ignore these methods, because they may call other
890 // instrumented functions.
891 if (F.getName().find(" load]") != std::string::npos) {
892 IRBuilder<> IRB(F.begin()->begin());
893 IRB.CreateCall(AsanInitFunction);
894 return true;
895 }
896 return false;
897}
898
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000899bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000900 if (BL->isIn(F)) return false;
901 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000902 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000903 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000904
905 // If needed, insert __asan_init before checking for AddressSafety attr.
906 maybeInsertAsanInitAtFunctionEntry(F);
907
Bill Wendling034b94b2012-12-19 07:18:57 +0000908 if (!F.getFnAttributes().hasAttribute(Attribute::AddressSafety))
Bill Wendling67658342012-10-09 07:45:08 +0000909 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000910
911 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
912 return false;
Bill Wendling67658342012-10-09 07:45:08 +0000913
914 // We want to instrument every address only once per basic block (unless there
915 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000916 SmallSet<Value*, 16> TempsToInstrument;
917 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000918 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000919 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000920
921 // Fill the set of memory operations to instrument.
922 for (Function::iterator FI = F.begin(), FE = F.end();
923 FI != FE; ++FI) {
924 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000925 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000926 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
927 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +0000928 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000929 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000930 if (ClOpt && ClOptSameTemp) {
931 if (!TempsToInstrument.insert(Addr))
932 continue; // We've seen this temp in the current BB.
933 }
934 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
935 // ok, take it.
936 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000937 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000938 // A call inside BB.
939 TempsToInstrument.clear();
Kostya Serebryanya17babb2012-11-30 11:08:59 +0000940 if (CI->doesNotReturn()) {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000941 NoReturnCalls.push_back(CI);
942 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000943 }
944 continue;
945 }
946 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000947 NumInsnsPerBB++;
948 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
949 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000950 }
951 }
952
953 // Instrument.
954 int NumInstrumented = 0;
955 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
956 Instruction *Inst = ToInstrument[i];
957 if (ClDebugMin < 0 || ClDebugMax < 0 ||
958 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000959 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000960 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000961 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000962 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000963 }
964 NumInstrumented++;
965 }
966
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000967 bool ChangedStack = poisonStackInFunction(F);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000968
969 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
970 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
971 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
972 Instruction *CI = NoReturnCalls[i];
973 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000974 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000975 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000976 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000977
978 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000979}
980
981static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
982 if (ShadowRedzoneSize == 1) return PoisonByte;
983 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
984 if (ShadowRedzoneSize == 4)
985 return (PoisonByte << 24) + (PoisonByte << 16) +
986 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +0000987 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000988}
989
990static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
991 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000992 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000993 size_t ShadowGranularity,
994 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000995 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000996 i+= ShadowGranularity, Shadow++) {
997 if (i + ShadowGranularity <= Size) {
998 *Shadow = 0; // fully addressable
999 } else if (i >= Size) {
1000 *Shadow = Magic; // unaddressable
1001 } else {
1002 *Shadow = Size - i; // first Size-i bytes are addressable
1003 }
1004 }
1005}
1006
1007void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
1008 IRBuilder<> IRB,
1009 Value *ShadowBase, bool DoPoison) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001010 size_t ShadowRZSize = RedzoneSize() >> MappingScale();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001011 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1012 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1013 Type *RZPtrTy = PointerType::get(RZTy, 0);
1014
1015 Value *PoisonLeft = ConstantInt::get(RZTy,
1016 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1017 Value *PoisonMid = ConstantInt::get(RZTy,
1018 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1019 Value *PoisonRight = ConstantInt::get(RZTy,
1020 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1021
1022 // poison the first red zone.
1023 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1024
1025 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001026 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001027 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1028 AllocaInst *AI = AllocaVec[i];
1029 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1030 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001031 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001032 Value *Ptr = NULL;
1033
1034 Pos += AlignedSize;
1035
1036 assert(ShadowBase->getType() == IntptrTy);
1037 if (SizeInBytes < AlignedSize) {
1038 // Poison the partial redzone at right
1039 Ptr = IRB.CreateAdd(
1040 ShadowBase, ConstantInt::get(IntptrTy,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001041 (Pos >> MappingScale()) - ShadowRZSize));
1042 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001043 uint32_t Poison = 0;
1044 if (DoPoison) {
1045 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001046 RedzoneSize(),
1047 1ULL << MappingScale(),
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001048 kAsanStackPartialRedzoneMagic);
1049 }
1050 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1051 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1052 }
1053
1054 // Poison the full redzone at right.
1055 Ptr = IRB.CreateAdd(ShadowBase,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001056 ConstantInt::get(IntptrTy, Pos >> MappingScale()));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001057 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
1058 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1059
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001060 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001061 }
1062}
1063
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +00001064// Workaround for bug 11395: we don't want to instrument stack in functions
1065// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
Kostya Serebryanyd2703de2011-11-23 02:10:54 +00001066// FIXME: remove once the bug 11395 is fixed.
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +00001067bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1068 if (LongSize != 32) return false;
1069 CallInst *CI = dyn_cast<CallInst>(I);
1070 if (!CI || !CI->isInlineAsm()) return false;
1071 if (CI->getNumArgOperands() <= 5) return false;
1072 // We have inline assembly with quite a few arguments.
1073 return true;
1074}
1075
Alexey Samsonovf985f442012-12-04 01:34:23 +00001076// Handling llvm.lifetime intrinsics for a given %alloca:
1077// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1078// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1079// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1080// could be poisoned by previous llvm.lifetime.end instruction, as the
1081// variable may go in and out of scope several times, e.g. in loops).
1082// (3) if we poisoned at least one %alloca in a function,
1083// unpoison the whole stack frame at function exit.
1084bool AddressSanitizer::handleAllocaLifetime(Value *Alloca) {
1085 assert(CheckLifetime);
1086 Type *AllocaType = Alloca->getType();
1087 Type *Int8PtrTy = Type::getInt8PtrTy(AllocaType->getContext());
1088
1089 bool Res = false;
1090 // Typical code looks like this:
1091 // %alloca = alloca <type>, <alignment>
1092 // ... some code ...
1093 // %val1 = bitcast <type>* %alloca to i8*
1094 // call void @llvm.lifetime.start(i64 <size>, i8* %val1)
1095 // ... more code ...
1096 // %val2 = bitcast <type>* %alloca to i8*
1097 // call void @llvm.lifetime.start(i64 <size>, i8* %val2)
1098 // That is, to handle %alloca we must find all its casts to
1099 // i8* values, and find lifetime instructions for these values.
1100 if (AllocaType == Int8PtrTy)
1101 Res |= handleValueLifetime(Alloca);
1102 for (Value::use_iterator UI = Alloca->use_begin(), UE = Alloca->use_end();
1103 UI != UE; ++UI) {
1104 if (UI->getType() != Int8PtrTy) continue;
1105 if (UI->stripPointerCasts() != Alloca) continue;
1106 Res |= handleValueLifetime(*UI);
1107 }
1108 return Res;
1109}
1110
1111bool AddressSanitizer::handleValueLifetime(Value *V) {
1112 assert(CheckLifetime);
1113 bool Res = false;
1114 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;
1115 ++UI) {
1116 IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI);
1117 if (!II) continue;
1118 Intrinsic::ID ID = II->getIntrinsicID();
1119 if (ID != Intrinsic::lifetime_start &&
1120 ID != Intrinsic::lifetime_end)
1121 continue;
1122 if (V != II->getArgOperand(1))
1123 continue;
1124 // Found lifetime intrinsic, add ASan instrumentation if necessary.
1125 ConstantInt *Size = dyn_cast<ConstantInt>(II->getArgOperand(0));
1126 // If size argument is undefined, don't do anything.
1127 if (Size->isMinusOne())
1128 continue;
1129 // Check that size doesn't saturate uint64_t and can
1130 // be stored in IntptrTy.
1131 const uint64_t SizeValue = Size->getValue().getLimitedValue();
1132 if (SizeValue == ~0ULL ||
1133 !ConstantInt::isValueValidForType(IntptrTy, SizeValue)) {
1134 continue;
1135 }
1136 IRBuilder<> IRB(II);
1137 bool DoPoison = (ID == Intrinsic::lifetime_end);
1138 poisonAlloca(V, SizeValue, IRB, DoPoison);
1139 Res = true;
1140 }
1141 return Res;
1142}
1143
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001144// Find all static Alloca instructions and put
1145// poisoned red zones around all of them.
1146// Then unpoison everything back before the function returns.
1147//
1148// Stack poisoning does not play well with exception handling.
1149// When an exception is thrown, we essentially bypass the code
1150// that unpoisones the stack. This is why the run-time library has
1151// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
1152// stack in the interceptor. This however does not work inside the
1153// actual function which catches the exception. Most likely because the
1154// compiler hoists the load of the shadow value somewhere too high.
1155// This causes asan to report a non-existing bug on 453.povray.
1156// It sounds like an LLVM bug.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001157bool AddressSanitizer::poisonStackInFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001158 if (!ClStack) return false;
1159 SmallVector<AllocaInst*, 16> AllocaVec;
1160 SmallVector<Instruction*, 8> RetVec;
1161 uint64_t TotalSize = 0;
Alexey Samsonovf985f442012-12-04 01:34:23 +00001162 bool HavePoisonedAllocas = false;
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001163 DIBuilder DIB(*F.getParent());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001164
1165 // Filter out Alloca instructions we want (and can) handle.
1166 // Collect Ret instructions.
Kostya Serebryany6c554122012-12-04 06:14:01 +00001167 unsigned ResultAlignment = 1 << MappingScale();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001168 for (Function::iterator FI = F.begin(), FE = F.end();
1169 FI != FE; ++FI) {
1170 BasicBlock &BB = *FI;
1171 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
1172 BI != BE; ++BI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001173 if (isa<ReturnInst>(BI)) {
1174 RetVec.push_back(BI);
1175 continue;
1176 }
1177
1178 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
1179 if (!AI) continue;
1180 if (AI->isArrayAllocation()) continue;
1181 if (!AI->isStaticAlloca()) continue;
1182 if (!AI->getAllocatedType()->isSized()) continue;
Kostya Serebryany6c554122012-12-04 06:14:01 +00001183 ResultAlignment = std::max(ResultAlignment, AI->getAlignment());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001184 AllocaVec.push_back(AI);
1185 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1186 TotalSize += AlignedSize;
1187 }
1188 }
1189
1190 if (AllocaVec.empty()) return false;
1191
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001192 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001193
Alexey Samsonovee548272012-11-29 18:14:24 +00001194 bool DoStackMalloc = CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001195 && LocalStackSize <= kMaxStackMallocSize;
1196
1197 Instruction *InsBefore = AllocaVec[0];
1198 IRBuilder<> IRB(InsBefore);
1199
1200
1201 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1202 AllocaInst *MyAlloca =
1203 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Kostya Serebryany6c554122012-12-04 06:14:01 +00001204 if (ClRealignStack && ResultAlignment < RedzoneSize())
1205 ResultAlignment = RedzoneSize();
1206 MyAlloca->setAlignment(ResultAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001207 assert(MyAlloca->isStaticAlloca());
1208 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1209 Value *LocalStackBase = OrigStackBase;
1210
1211 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001212 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1213 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1214 }
1215
1216 // This string will be parsed by the run-time (DescribeStackAddress).
1217 SmallString<2048> StackDescriptionStorage;
1218 raw_svector_ostream StackDescription(StackDescriptionStorage);
1219 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1220
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001221 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001222 // Replace Alloca instructions with base+offset.
1223 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1224 AllocaInst *AI = AllocaVec[i];
1225 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1226 StringRef Name = AI->getName();
1227 StackDescription << Pos << " " << SizeInBytes << " "
1228 << Name.size() << " " << Name << " ";
1229 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001230 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001231 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001232 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001233 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001234 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001235 AI->replaceAllUsesWith(NewAllocaPtr);
1236 // Analyze lifetime intrinsics only for static allocas we handle.
1237 if (CheckLifetime)
1238 HavePoisonedAllocas |= handleAllocaLifetime(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001239 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001240 }
1241 assert(Pos == LocalStackSize);
1242
1243 // Write the Magic value and the frame description constant to the redzone.
1244 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1245 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1246 BasePlus0);
1247 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1248 ConstantInt::get(IntptrTy, LongSize/8));
1249 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001250 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001251 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001252 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001253 IRB.CreateStore(Description, BasePlus1);
1254
1255 // Poison the stack redzones at the entry.
1256 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1257 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1258
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001259 // Unpoison the stack before all ret instructions.
1260 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1261 Instruction *Ret = RetVec[i];
1262 IRBuilder<> IRBRet(Ret);
1263
1264 // Mark the current frame as retired.
1265 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1266 BasePlus0);
1267 // Unpoison the stack.
1268 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1269
1270 if (DoStackMalloc) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001271 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001272 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1273 ConstantInt::get(IntptrTy, LocalStackSize),
1274 OrigStackBase);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001275 } else if (HavePoisonedAllocas) {
1276 // If we poisoned some allocas in llvm.lifetime analysis,
1277 // unpoison whole stack frame now.
1278 assert(LocalStackBase == OrigStackBase);
1279 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001280 }
1281 }
1282
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001283 // We are done. Remove the old unused alloca instructions.
1284 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1285 AllocaVec[i]->eraseFromParent();
1286
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001287 if (ClDebugStack) {
1288 DEBUG(dbgs() << F);
1289 }
1290
1291 return true;
1292}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001293
1294void AddressSanitizer::poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB,
1295 bool DoPoison) {
1296 // For now just insert the call to ASan runtime.
1297 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1298 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1299 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1300 : AsanUnpoisonStackMemoryFunc,
1301 AddrArg, SizeArg);
1302}