blob: 14348b9bac670b7c1e6f0c87432e410609c643a7 [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
Kostya Serebryanya1c45042012-03-14 23:22:10 +000018#include "FunctionBlackList.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000019#include "llvm/Function.h"
20#include "llvm/IRBuilder.h"
21#include "llvm/IntrinsicInst.h"
22#include "llvm/LLVMContext.h"
23#include "llvm/Module.h"
24#include "llvm/Type.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000025#include "llvm/ADT/ArrayRef.h"
26#include "llvm/ADT/OwningPtr.h"
27#include "llvm/ADT/SmallSet.h"
28#include "llvm/ADT/SmallString.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000031#include "llvm/ADT/Triple.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000032#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/DataTypes.h"
34#include "llvm/Support/Debug.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000035#include "llvm/Support/raw_ostream.h"
36#include "llvm/Support/system_error.h"
37#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetMachine.h"
39#include "llvm/Transforms/Instrumentation.h"
40#include "llvm/Transforms/Utils/BasicBlockUtils.h"
41#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000042
43#include <string>
44#include <algorithm>
45
46using namespace llvm;
47
48static const uint64_t kDefaultShadowScale = 3;
49static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
50static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000051static const uint64_t kDefaultShadowOffsetAndroid = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000052
53static const size_t kMaxStackMallocSize = 1 << 16; // 64K
54static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
55static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
56
57static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000058static const char *kAsanModuleDtorName = "asan.module_dtor";
59static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000060static const char *kAsanReportErrorTemplate = "__asan_report_";
61static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000062static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000063static const char *kAsanInitName = "__asan_init";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000064static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000065static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
66static const char *kAsanMappingScaleName = "__asan_mapping_scale";
67static const char *kAsanStackMallocName = "__asan_stack_malloc";
68static const char *kAsanStackFreeName = "__asan_stack_free";
69
70static const int kAsanStackLeftRedzoneMagic = 0xf1;
71static const int kAsanStackMidRedzoneMagic = 0xf2;
72static const int kAsanStackRightRedzoneMagic = 0xf3;
73static const int kAsanStackPartialRedzoneMagic = 0xf4;
74
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000075// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
76static const size_t kNumberOfAccessSizes = 5;
77
Kostya Serebryany800e03f2011-11-16 01:35:23 +000078// Command-line flags.
79
80// This flag may need to be replaced with -f[no-]asan-reads.
81static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
82 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
83static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
84 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000085static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
86 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
87 cl::Hidden, cl::init(true));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000088static cl::opt<bool> ClMergeCallbacks("asan-merge-callbacks",
89 cl::desc("merge __asan_report_ callbacks to create fewer BBs"),
90 cl::Hidden, cl::init(false));
91// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +000092// in any given BB. Normally, this should be set to unlimited (INT_MAX),
93// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
94// set it to 10000.
95static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
96 cl::init(10000),
97 cl::desc("maximal number of instructions to instrument in any given BB"),
98 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +000099// This flag may need to be replaced with -f[no]asan-stack.
100static cl::opt<bool> ClStack("asan-stack",
101 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
102// This flag may need to be replaced with -f[no]asan-use-after-return.
103static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
104 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
105// This flag may need to be replaced with -f[no]asan-globals.
106static cl::opt<bool> ClGlobals("asan-globals",
107 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
108static cl::opt<bool> ClMemIntrin("asan-memintrin",
109 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
110// This flag may need to be replaced with -fasan-blacklist.
111static cl::opt<std::string> ClBlackListFile("asan-blacklist",
112 cl::desc("File containing the list of functions to ignore "
113 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000114
115// These flags allow to change the shadow mapping.
116// The shadow mapping looks like
117// Shadow = (Mem >> scale) + (1 << offset_log)
118static cl::opt<int> ClMappingScale("asan-mapping-scale",
119 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
120static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
121 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
122
123// Optimization flags. Not user visible, used mostly for testing
124// and benchmarking the tool.
125static cl::opt<bool> ClOpt("asan-opt",
126 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
127static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
128 cl::desc("Instrument the same temp just once"), cl::Hidden,
129 cl::init(true));
130static cl::opt<bool> ClOptGlobals("asan-opt-globals",
131 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
132
133// Debug flags.
134static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
135 cl::init(0));
136static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
137 cl::Hidden, cl::init(0));
138static cl::opt<std::string> ClDebugFunc("asan-debug-func",
139 cl::Hidden, cl::desc("Debug func"));
140static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
141 cl::Hidden, cl::init(-1));
142static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
143 cl::Hidden, cl::init(-1));
144
145namespace {
146
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000147/// When the crash callbacks are merged, they receive some amount of arguments
148/// that are merged in a PHI node. This struct represents arguments from one
149/// call site.
150struct CrashArg {
151 Value *Arg1;
152 Value *Arg2;
153};
154
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000155/// An object of this type is created while instrumenting every function.
156struct AsanFunctionContext {
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000157 AsanFunctionContext(Function &Function) : F(Function), CrashBlock() { }
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000158
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000159 Function &F;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000160 // These are initially zero. If we require at least one call to
161 // __asan_report_{read,write}{1,2,4,8,16}, an appropriate BB is created.
162 BasicBlock *CrashBlock[2][kNumberOfAccessSizes];
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000163 typedef SmallVector<CrashArg, 8> CrashArgsVec;
164 CrashArgsVec CrashArgs[2][kNumberOfAccessSizes];
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000165};
166
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000167/// AddressSanitizer: instrument the code in module to find memory bugs.
168struct AddressSanitizer : public ModulePass {
169 AddressSanitizer();
Alexander Potapenko25878042012-01-23 11:22:43 +0000170 virtual const char *getPassName() const;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000171 void instrumentMop(AsanFunctionContext &AFC, Instruction *I);
172 void instrumentAddress(AsanFunctionContext &AFC,
173 Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000174 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000175 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
176 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000177 Instruction *generateCrashCode(BasicBlock *BB, Value *Addr, Value *PC,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000178 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000179 bool instrumentMemIntrinsic(AsanFunctionContext &AFC, MemIntrinsic *MI);
180 void instrumentMemIntrinsicParam(AsanFunctionContext &AFC,
181 Instruction *OrigIns, Value *Addr,
182 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000183 Instruction *InsertBefore, bool IsWrite);
184 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
185 bool handleFunction(Module &M, Function &F);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000186 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000187 bool poisonStackInFunction(Module &M, Function &F);
188 virtual bool runOnModule(Module &M);
189 bool insertGlobalRedzones(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000190 static char ID; // Pass identification, replacement for typeid
191
192 private:
193
194 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
195 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanovd8313be2012-03-02 10:41:08 +0000196 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000197 return SizeInBytes;
198 }
199 uint64_t getAlignedSize(uint64_t SizeInBytes) {
200 return ((SizeInBytes + RedzoneSize - 1)
201 / RedzoneSize) * RedzoneSize;
202 }
203 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
204 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
205 return getAlignedSize(SizeInBytes);
206 }
207
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000208 Function *checkInterfaceFunction(Constant *FuncOrBitcast);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000209 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
210 Value *ShadowBase, bool DoPoison);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000211 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000212
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000213 LLVMContext *C;
214 TargetData *TD;
215 uint64_t MappingOffset;
216 int MappingScale;
217 size_t RedzoneSize;
218 int LongSize;
219 Type *IntptrTy;
220 Type *IntptrPtrTy;
221 Function *AsanCtorFunction;
222 Function *AsanInitFunction;
223 Instruction *CtorInsertBefore;
Kostya Serebryanya1c45042012-03-14 23:22:10 +0000224 OwningPtr<FunctionBlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000225 // This array is indexed by AccessIsWrite and log2(AccessSize).
226 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000227};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000228
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000229} // namespace
230
231char AddressSanitizer::ID = 0;
232INITIALIZE_PASS(AddressSanitizer, "asan",
233 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
234 false, false)
235AddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
236ModulePass *llvm::createAddressSanitizerPass() {
237 return new AddressSanitizer();
238}
239
Alexander Potapenko25878042012-01-23 11:22:43 +0000240const char *AddressSanitizer::getPassName() const {
241 return "AddressSanitizer";
242}
243
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000244static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
245 size_t Res = CountTrailingZeros_32(TypeSize / 8);
246 assert(Res < kNumberOfAccessSizes);
247 return Res;
248}
249
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000250// Create a constant for Str so that we can pass it to the run-time lib.
251static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000252 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000253 return new GlobalVariable(M, StrConst->getType(), true,
254 GlobalValue::PrivateLinkage, StrConst, "");
255}
256
257// Split the basic block and insert an if-then code.
258// Before:
259// Head
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000260// Cmp
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000261// Tail
262// After:
263// Head
264// if (Cmp)
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000265// ThenBlock
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000266// Tail
267//
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000268// If ThenBlock is zero, a new block is created and its terminator is returned.
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000269// Otherwize 0 is returned.
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000270static BranchInst *splitBlockAndInsertIfThen(Value *Cmp,
271 BasicBlock *ThenBlock = 0) {
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000272 Instruction *SplitBefore = cast<Instruction>(Cmp)->getNextNode();
Chandler Carruthc3c8db92012-07-16 08:58:53 +0000273 BasicBlock *Head = SplitBefore->getParent();
Chandler Carruth349f14c2012-07-16 10:01:02 +0000274 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
Chandler Carruthc3c8db92012-07-16 08:58:53 +0000275 TerminatorInst *HeadOldTerm = Head->getTerminator();
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000276 BranchInst *CheckTerm = 0;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000277 if (!ThenBlock) {
278 LLVMContext &C = Head->getParent()->getParent()->getContext();
279 ThenBlock = BasicBlock::Create(C, "", Head->getParent());
280 CheckTerm = BranchInst::Create(Tail, ThenBlock);
281 }
Chandler Carruth349f14c2012-07-16 10:01:02 +0000282 BranchInst *HeadNewTerm =
283 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cmp);
284 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
Chandler Carruthc3c8db92012-07-16 08:58:53 +0000285
Chandler Carruth349f14c2012-07-16 10:01:02 +0000286 return CheckTerm;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000287}
288
289Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
290 // Shadow >> scale
291 Shadow = IRB.CreateLShr(Shadow, MappingScale);
292 if (MappingOffset == 0)
293 return Shadow;
294 // (Shadow >> scale) | offset
295 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
296 MappingOffset));
297}
298
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000299void AddressSanitizer::instrumentMemIntrinsicParam(
300 AsanFunctionContext &AFC, Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000301 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
302 // Check the first byte.
303 {
304 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000305 instrumentAddress(AFC, OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000306 }
307 // Check the last byte.
308 {
309 IRBuilder<> IRB(InsertBefore);
310 Value *SizeMinusOne = IRB.CreateSub(
311 Size, ConstantInt::get(Size->getType(), 1));
312 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
313 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
314 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000315 instrumentAddress(AFC, OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000316 }
317}
318
319// Instrument memset/memmove/memcpy
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000320bool AddressSanitizer::instrumentMemIntrinsic(AsanFunctionContext &AFC,
321 MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000322 Value *Dst = MI->getDest();
323 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000324 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000325 Value *Length = MI->getLength();
326
327 Constant *ConstLength = dyn_cast<Constant>(Length);
328 Instruction *InsertBefore = MI;
329 if (ConstLength) {
330 if (ConstLength->isNullValue()) return false;
331 } else {
332 // The size is not a constant so it could be zero -- check at run-time.
333 IRBuilder<> IRB(InsertBefore);
334
335 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000336 Constant::getNullValue(Length->getType()));
337 InsertBefore = splitBlockAndInsertIfThen(Cmp);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000338 }
339
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000340 instrumentMemIntrinsicParam(AFC, MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000341 if (Src)
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000342 instrumentMemIntrinsicParam(AFC, MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000343 return true;
344}
345
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000346// If I is an interesting memory access, return the PointerOperand
347// and set IsWrite. Otherwise return NULL.
348static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000349 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000350 if (!ClInstrumentReads) return NULL;
351 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000352 return LI->getPointerOperand();
353 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000354 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
355 if (!ClInstrumentWrites) return NULL;
356 *IsWrite = true;
357 return SI->getPointerOperand();
358 }
359 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
360 if (!ClInstrumentAtomics) return NULL;
361 *IsWrite = true;
362 return RMW->getPointerOperand();
363 }
364 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
365 if (!ClInstrumentAtomics) return NULL;
366 *IsWrite = true;
367 return XCHG->getPointerOperand();
368 }
369 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000370}
371
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000372void AddressSanitizer::instrumentMop(AsanFunctionContext &AFC, Instruction *I) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000373 bool IsWrite;
374 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
375 assert(Addr);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000376 if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
377 // We are accessing a global scalar variable. Nothing to catch here.
378 return;
379 }
380 Type *OrigPtrTy = Addr->getType();
381 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
382
383 assert(OrigTy->isSized());
384 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
385
386 if (TypeSize != 8 && TypeSize != 16 &&
387 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
388 // Ignore all unusual sizes.
389 return;
390 }
391
392 IRBuilder<> IRB(I);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000393 instrumentAddress(AFC, I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000394}
395
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000396// Validate the result of Module::getOrInsertFunction called for an interface
397// function of AddressSanitizer. If the instrumented module defines a function
398// with the same name, their prototypes must match, otherwise
399// getOrInsertFunction returns a bitcast.
400Function *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
401 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
402 FuncOrBitcast->dump();
403 report_fatal_error("trying to redefine an AddressSanitizer "
404 "interface function");
405}
406
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000407Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000408 BasicBlock *BB, Value *Addr, Value *PC,
409 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000410 IRBuilder<> IRB(BB->getFirstNonPHI());
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000411 CallInst *Call;
412 if (PC)
413 Call = IRB.CreateCall2(AsanErrorCallback[IsWrite][AccessSizeIndex],
414 Addr, PC);
415 else
416 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000417 Call->setDoesNotReturn();
418 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000419}
420
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000421Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000422 Value *ShadowValue,
423 uint32_t TypeSize) {
424 size_t Granularity = 1 << MappingScale;
425 // Addr & (Granularity - 1)
426 Value *LastAccessedByte = IRB.CreateAnd(
427 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
428 // (Addr & (Granularity - 1)) + size - 1
429 if (TypeSize / 8 > 1)
430 LastAccessedByte = IRB.CreateAdd(
431 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
432 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
433 LastAccessedByte = IRB.CreateIntCast(
434 LastAccessedByte, IRB.getInt8Ty(), false);
435 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
436 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
437}
438
439void AddressSanitizer::instrumentAddress(AsanFunctionContext &AFC,
440 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000441 IRBuilder<> &IRB, Value *Addr,
442 uint32_t TypeSize, bool IsWrite) {
443 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
444
445 Type *ShadowTy = IntegerType::get(
446 *C, std::max(8U, TypeSize >> MappingScale));
447 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
448 Value *ShadowPtr = memToShadow(AddrLong, IRB);
449 Value *CmpVal = Constant::getNullValue(ShadowTy);
450 Value *ShadowValue = IRB.CreateLoad(
451 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
452
453 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
454
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000455 BasicBlock *CrashBlock = 0;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000456 if (ClMergeCallbacks) {
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000457 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
458 BasicBlock **Cached = &AFC.CrashBlock[IsWrite][AccessSizeIndex];
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000459 if (!*Cached) {
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000460 std::string BBName("crash_bb-");
461 BBName += (IsWrite ? "w-" : "r-") + itostr(1 << AccessSizeIndex);
462 BasicBlock *BB = BasicBlock::Create(*C, BBName, &AFC.F);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000463 new UnreachableInst(*C, BB);
464 *Cached = BB;
465 }
466 CrashBlock = *Cached;
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000467 // We need to pass the PC as the second parameter to __asan_report_*.
468 // There are few problems:
469 // - Some architectures (e.g. x86_32) don't have a cheap way to get the PC.
470 // - LLVM doesn't have the appropriate intrinsic.
471 // For now, put a random number into the PC, just to allow experiments.
472 Value *PC = ConstantInt::get(IntptrTy, rand());
473 CrashArg Arg = {AddrLong, PC};
474 AFC.CrashArgs[IsWrite][AccessSizeIndex].push_back(Arg);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000475 } else {
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000476 CrashBlock = BasicBlock::Create(*C, "crash_bb", &AFC.F);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000477 new UnreachableInst(*C, CrashBlock);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000478 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000479 Instruction *Crash =
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000480 generateCrashCode(CrashBlock, AddrLong, 0, IsWrite, AccessSizeIndex);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000481 Crash->setDebugLoc(OrigIns->getDebugLoc());
482 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000483
484 size_t Granularity = 1 << MappingScale;
485 if (TypeSize < 8 * Granularity) {
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000486 Instruction *CheckTerm = splitBlockAndInsertIfThen(Cmp);
487 IRB.SetInsertPoint(CheckTerm);
488 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
489 splitBlockAndInsertIfThen(Cmp2, CrashBlock);
490 } else {
491 splitBlockAndInsertIfThen(Cmp, CrashBlock);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000492 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000493}
494
495// This function replaces all global variables with new variables that have
496// trailing redzones. It also creates a function that poisons
497// redzones and inserts this function into llvm.global_ctors.
498bool AddressSanitizer::insertGlobalRedzones(Module &M) {
499 SmallVector<GlobalVariable *, 16> GlobalsToChange;
500
501 for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
502 E = M.getGlobalList().end(); G != E; ++G) {
503 Type *Ty = cast<PointerType>(G->getType())->getElementType();
504 DEBUG(dbgs() << "GLOBAL: " << *G);
505
506 if (!Ty->isSized()) continue;
507 if (!G->hasInitializer()) continue;
Kostya Serebryany7cf2a042011-11-17 23:14:59 +0000508 // Touch only those globals that will not be defined in other modules.
509 // Don't handle ODR type linkages since other modules may be built w/o asan.
Kostya Serebryany2e7fb2f2011-11-17 23:37:53 +0000510 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
511 G->getLinkage() != GlobalVariable::PrivateLinkage &&
512 G->getLinkage() != GlobalVariable::InternalLinkage)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000513 continue;
Kostya Serebryanyd2703de2011-11-23 02:10:54 +0000514 // Two problems with thread-locals:
515 // - The address of the main thread's copy can't be computed at link-time.
516 // - Need to poison all copies, not just the main thread's one.
517 if (G->isThreadLocal())
518 continue;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000519 // For now, just ignore this Alloca if the alignment is large.
520 if (G->getAlignment() > RedzoneSize) continue;
521
522 // Ignore all the globals with the names starting with "\01L_OBJC_".
523 // Many of those are put into the .cstring section. The linker compresses
524 // that section by removing the spare \0s after the string terminator, so
525 // our redzones get broken.
526 if ((G->getName().find("\01L_OBJC_") == 0) ||
527 (G->getName().find("\01l_OBJC_") == 0)) {
528 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
529 continue;
530 }
531
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000532 if (G->hasSection()) {
533 StringRef Section(G->getSection());
Alexander Potapenko8375bc92012-01-30 10:40:22 +0000534 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
535 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
536 // them.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000537 if ((Section.find("__OBJC,") == 0) ||
538 (Section.find("__DATA, __objc_") == 0)) {
539 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
540 continue;
541 }
Alexander Potapenko8375bc92012-01-30 10:40:22 +0000542 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
543 // Constant CFString instances are compiled in the following way:
544 // -- the string buffer is emitted into
545 // __TEXT,__cstring,cstring_literals
546 // -- the constant NSConstantString structure referencing that buffer
547 // is placed into __DATA,__cfstring
548 // Therefore there's no point in placing redzones into __DATA,__cfstring.
549 // Moreover, it causes the linker to crash on OS X 10.7
550 if (Section.find("__DATA,__cfstring") == 0) {
551 DEBUG(dbgs() << "Ignoring CFString: " << *G);
552 continue;
553 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000554 }
555
556 GlobalsToChange.push_back(G);
557 }
558
559 size_t n = GlobalsToChange.size();
560 if (n == 0) return false;
561
562 // A global is described by a structure
563 // size_t beg;
564 // size_t size;
565 // size_t size_with_redzone;
566 // const char *name;
567 // We initialize an array of such structures and pass it to a run-time call.
568 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
569 IntptrTy, IntptrTy, NULL);
570 SmallVector<Constant *, 16> Initializers(n);
571
572 IRBuilder<> IRB(CtorInsertBefore);
573
574 for (size_t i = 0; i < n; i++) {
575 GlobalVariable *G = GlobalsToChange[i];
576 PointerType *PtrTy = cast<PointerType>(G->getType());
577 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000578 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000579 uint64_t RightRedzoneSize = RedzoneSize +
580 (RedzoneSize - (SizeInBytes % RedzoneSize));
581 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
582
583 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
584 Constant *NewInitializer = ConstantStruct::get(
585 NewTy, G->getInitializer(),
586 Constant::getNullValue(RightRedZoneTy), NULL);
587
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000588 SmallString<2048> DescriptionOfGlobal = G->getName();
589 DescriptionOfGlobal += " (";
590 DescriptionOfGlobal += M.getModuleIdentifier();
591 DescriptionOfGlobal += ")";
592 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000593
594 // Create a new global variable with enough space for a redzone.
595 GlobalVariable *NewGlobal = new GlobalVariable(
596 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000597 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000598 NewGlobal->copyAttributesFrom(G);
599 NewGlobal->setAlignment(RedzoneSize);
600
601 Value *Indices2[2];
602 Indices2[0] = IRB.getInt32(0);
603 Indices2[1] = IRB.getInt32(0);
604
605 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000606 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000607 NewGlobal->takeName(G);
608 G->eraseFromParent();
609
610 Initializers[i] = ConstantStruct::get(
611 GlobalStructTy,
612 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
613 ConstantInt::get(IntptrTy, SizeInBytes),
614 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
615 ConstantExpr::getPointerCast(Name, IntptrTy),
616 NULL);
617 DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
618 }
619
620 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
621 GlobalVariable *AllGlobals = new GlobalVariable(
622 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
623 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
624
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000625 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000626 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
627 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
628
629 IRB.CreateCall2(AsanRegisterGlobals,
630 IRB.CreatePointerCast(AllGlobals, IntptrTy),
631 ConstantInt::get(IntptrTy, n));
632
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000633 // We also need to unregister globals at the end, e.g. when a shared library
634 // gets closed.
635 Function *AsanDtorFunction = Function::Create(
636 FunctionType::get(Type::getVoidTy(*C), false),
637 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
638 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
639 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000640 Function *AsanUnregisterGlobals =
641 checkInterfaceFunction(M.getOrInsertFunction(
642 kAsanUnregisterGlobalsName,
643 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000644 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
645
646 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
647 IRB.CreatePointerCast(AllGlobals, IntptrTy),
648 ConstantInt::get(IntptrTy, n));
649 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
650
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000651 DEBUG(dbgs() << M);
652 return true;
653}
654
655// virtual
656bool AddressSanitizer::runOnModule(Module &M) {
657 // Initialize the private fields. No one has accessed them before.
658 TD = getAnalysisIfAvailable<TargetData>();
659 if (!TD)
660 return false;
Kostya Serebryanya1c45042012-03-14 23:22:10 +0000661 BL.reset(new FunctionBlackList(ClBlackListFile));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000662
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000663 C = &(M.getContext());
664 LongSize = TD->getPointerSizeInBits();
665 IntptrTy = Type::getIntNTy(*C, LongSize);
666 IntptrPtrTy = PointerType::get(IntptrTy, 0);
667
668 AsanCtorFunction = Function::Create(
669 FunctionType::get(Type::getVoidTy(*C), false),
670 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
671 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
672 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
673
674 // call __asan_init in the module ctor.
675 IRBuilder<> IRB(CtorInsertBefore);
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000676 AsanInitFunction = checkInterfaceFunction(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000677 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
678 AsanInitFunction->setLinkage(Function::ExternalLinkage);
679 IRB.CreateCall(AsanInitFunction);
680
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000681 // Create __asan_report* callbacks.
682 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
683 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
684 AccessSizeIndex++) {
685 // IsWrite and TypeSize are encoded in the function name.
686 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
687 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000688 // If we are merging crash callbacks, they have two parameters.
689 if (ClMergeCallbacks)
690 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>(
691 M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy,
692 IntptrTy, NULL));
693 else
694 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>(
695 M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000696 }
697 }
698
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000699 llvm::Triple targetTriple(M.getTargetTriple());
700 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::ANDROIDEABI;
701
702 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
703 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000704 if (ClMappingOffsetLog >= 0) {
705 if (ClMappingOffsetLog == 0) {
706 // special case
707 MappingOffset = 0;
708 } else {
709 MappingOffset = 1ULL << ClMappingOffsetLog;
710 }
711 }
712 MappingScale = kDefaultShadowScale;
713 if (ClMappingScale) {
714 MappingScale = ClMappingScale;
715 }
716 // Redzone used for stack and globals is at least 32 bytes.
717 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
718 RedzoneSize = std::max(32, (int)(1 << MappingScale));
719
720 bool Res = false;
721
722 if (ClGlobals)
723 Res |= insertGlobalRedzones(M);
724
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000725 if (ClMappingOffsetLog >= 0) {
726 // Tell the run-time the current values of mapping offset and scale.
727 GlobalValue *asan_mapping_offset =
728 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
729 ConstantInt::get(IntptrTy, MappingOffset),
730 kAsanMappingOffsetName);
731 // Read the global, otherwise it may be optimized away.
732 IRB.CreateLoad(asan_mapping_offset, true);
733 }
734 if (ClMappingScale) {
735 GlobalValue *asan_mapping_scale =
736 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
737 ConstantInt::get(IntptrTy, MappingScale),
738 kAsanMappingScaleName);
739 // Read the global, otherwise it may be optimized away.
740 IRB.CreateLoad(asan_mapping_scale, true);
741 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000742
743
744 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
745 if (F->isDeclaration()) continue;
746 Res |= handleFunction(M, *F);
747 }
748
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000749 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryany9b027412011-12-12 18:01:46 +0000750
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000751 return Res;
752}
753
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000754bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
755 // For each NSObject descendant having a +load method, this method is invoked
756 // by the ObjC runtime before any of the static constructors is called.
757 // Therefore we need to instrument such methods with a call to __asan_init
758 // at the beginning in order to initialize our runtime before any access to
759 // the shadow memory.
760 // We cannot just ignore these methods, because they may call other
761 // instrumented functions.
762 if (F.getName().find(" load]") != std::string::npos) {
763 IRBuilder<> IRB(F.begin()->begin());
764 IRB.CreateCall(AsanInitFunction);
765 return true;
766 }
767 return false;
768}
769
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000770bool AddressSanitizer::handleFunction(Module &M, Function &F) {
771 if (BL->isIn(F)) return false;
772 if (&F == AsanCtorFunction) return false;
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000773
774 // If needed, insert __asan_init before checking for AddressSafety attr.
775 maybeInsertAsanInitAtFunctionEntry(F);
776
Kostya Serebryany0307b9a2012-01-24 19:34:43 +0000777 if (!F.hasFnAttr(Attribute::AddressSafety)) return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000778
779 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
780 return false;
781 // We want to instrument every address only once per basic block
782 // (unless there are calls between uses).
783 SmallSet<Value*, 16> TempsToInstrument;
784 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000785 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000786 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000787
788 // Fill the set of memory operations to instrument.
789 for (Function::iterator FI = F.begin(), FE = F.end();
790 FI != FE; ++FI) {
791 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000792 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000793 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
794 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +0000795 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000796 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000797 if (ClOpt && ClOptSameTemp) {
798 if (!TempsToInstrument.insert(Addr))
799 continue; // We've seen this temp in the current BB.
800 }
801 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
802 // ok, take it.
803 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000804 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000805 // A call inside BB.
806 TempsToInstrument.clear();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000807 if (CI->doesNotReturn()) {
808 NoReturnCalls.push_back(CI);
809 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000810 }
811 continue;
812 }
813 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000814 NumInsnsPerBB++;
815 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
816 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000817 }
818 }
819
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000820 AsanFunctionContext AFC(F);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000821
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000822 // Instrument.
823 int NumInstrumented = 0;
824 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
825 Instruction *Inst = ToInstrument[i];
826 if (ClDebugMin < 0 || ClDebugMax < 0 ||
827 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000828 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000829 instrumentMop(AFC, Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000830 else
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000831 instrumentMemIntrinsic(AFC, cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000832 }
833 NumInstrumented++;
834 }
835
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000836 // Create PHI nodes and crash callbacks if we are merging crash callbacks.
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000837 if (NumInstrumented) {
838 for (size_t IsWrite = 0; IsWrite <= 1; IsWrite++) {
839 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
840 AccessSizeIndex++) {
841 BasicBlock *BB = AFC.CrashBlock[IsWrite][AccessSizeIndex];
842 if (!BB) continue;
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000843 assert(ClMergeCallbacks);
844 AsanFunctionContext::CrashArgsVec &Args =
845 AFC.CrashArgs[IsWrite][AccessSizeIndex];
846 IRBuilder<> IRB(BB->getFirstNonPHI());
847 size_t n = Args.size();
848 PHINode *PN1 = IRB.CreatePHI(IntptrTy, n);
849 PHINode *PN2 = IRB.CreatePHI(IntptrTy, n);
850 // We need to match crash parameters and the predecessors.
851 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
852 PI != PE; ++PI) {
853 n--;
854 PN1->addIncoming(Args[n].Arg1, *PI);
855 PN2->addIncoming(Args[n].Arg2, *PI);
856 }
857 assert(n == 0);
858 generateCrashCode(BB, PN1, PN2, IsWrite, AccessSizeIndex);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000859 }
860 }
861 }
862
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000863 DEBUG(dbgs() << F);
864
865 bool ChangedStack = poisonStackInFunction(M, F);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000866
867 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
868 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
869 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
870 Instruction *CI = NoReturnCalls[i];
871 IRBuilder<> IRB(CI);
872 IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
873 IRB.getVoidTy(), NULL));
874 }
875
876 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000877}
878
879static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
880 if (ShadowRedzoneSize == 1) return PoisonByte;
881 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
882 if (ShadowRedzoneSize == 4)
883 return (PoisonByte << 24) + (PoisonByte << 16) +
884 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +0000885 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000886}
887
888static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
889 size_t Size,
890 size_t RedzoneSize,
891 size_t ShadowGranularity,
892 uint8_t Magic) {
893 for (size_t i = 0; i < RedzoneSize;
894 i+= ShadowGranularity, Shadow++) {
895 if (i + ShadowGranularity <= Size) {
896 *Shadow = 0; // fully addressable
897 } else if (i >= Size) {
898 *Shadow = Magic; // unaddressable
899 } else {
900 *Shadow = Size - i; // first Size-i bytes are addressable
901 }
902 }
903}
904
905void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
906 IRBuilder<> IRB,
907 Value *ShadowBase, bool DoPoison) {
908 size_t ShadowRZSize = RedzoneSize >> MappingScale;
909 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
910 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
911 Type *RZPtrTy = PointerType::get(RZTy, 0);
912
913 Value *PoisonLeft = ConstantInt::get(RZTy,
914 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
915 Value *PoisonMid = ConstantInt::get(RZTy,
916 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
917 Value *PoisonRight = ConstantInt::get(RZTy,
918 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
919
920 // poison the first red zone.
921 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
922
923 // poison all other red zones.
924 uint64_t Pos = RedzoneSize;
925 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
926 AllocaInst *AI = AllocaVec[i];
927 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
928 uint64_t AlignedSize = getAlignedAllocaSize(AI);
929 assert(AlignedSize - SizeInBytes < RedzoneSize);
930 Value *Ptr = NULL;
931
932 Pos += AlignedSize;
933
934 assert(ShadowBase->getType() == IntptrTy);
935 if (SizeInBytes < AlignedSize) {
936 // Poison the partial redzone at right
937 Ptr = IRB.CreateAdd(
938 ShadowBase, ConstantInt::get(IntptrTy,
939 (Pos >> MappingScale) - ShadowRZSize));
940 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
941 uint32_t Poison = 0;
942 if (DoPoison) {
943 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
944 RedzoneSize,
945 1ULL << MappingScale,
946 kAsanStackPartialRedzoneMagic);
947 }
948 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
949 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
950 }
951
952 // Poison the full redzone at right.
953 Ptr = IRB.CreateAdd(ShadowBase,
954 ConstantInt::get(IntptrTy, Pos >> MappingScale));
955 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
956 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
957
958 Pos += RedzoneSize;
959 }
960}
961
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000962// Workaround for bug 11395: we don't want to instrument stack in functions
963// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
Kostya Serebryanyd2703de2011-11-23 02:10:54 +0000964// FIXME: remove once the bug 11395 is fixed.
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000965bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
966 if (LongSize != 32) return false;
967 CallInst *CI = dyn_cast<CallInst>(I);
968 if (!CI || !CI->isInlineAsm()) return false;
969 if (CI->getNumArgOperands() <= 5) return false;
970 // We have inline assembly with quite a few arguments.
971 return true;
972}
973
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000974// Find all static Alloca instructions and put
975// poisoned red zones around all of them.
976// Then unpoison everything back before the function returns.
977//
978// Stack poisoning does not play well with exception handling.
979// When an exception is thrown, we essentially bypass the code
980// that unpoisones the stack. This is why the run-time library has
981// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
982// stack in the interceptor. This however does not work inside the
983// actual function which catches the exception. Most likely because the
984// compiler hoists the load of the shadow value somewhere too high.
985// This causes asan to report a non-existing bug on 453.povray.
986// It sounds like an LLVM bug.
987bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
988 if (!ClStack) return false;
989 SmallVector<AllocaInst*, 16> AllocaVec;
990 SmallVector<Instruction*, 8> RetVec;
991 uint64_t TotalSize = 0;
992
993 // Filter out Alloca instructions we want (and can) handle.
994 // Collect Ret instructions.
995 for (Function::iterator FI = F.begin(), FE = F.end();
996 FI != FE; ++FI) {
997 BasicBlock &BB = *FI;
998 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
999 BI != BE; ++BI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001000 if (isa<ReturnInst>(BI)) {
1001 RetVec.push_back(BI);
1002 continue;
1003 }
1004
1005 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
1006 if (!AI) continue;
1007 if (AI->isArrayAllocation()) continue;
1008 if (!AI->isStaticAlloca()) continue;
1009 if (!AI->getAllocatedType()->isSized()) continue;
1010 if (AI->getAlignment() > RedzoneSize) continue;
1011 AllocaVec.push_back(AI);
1012 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1013 TotalSize += AlignedSize;
1014 }
1015 }
1016
1017 if (AllocaVec.empty()) return false;
1018
1019 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
1020
1021 bool DoStackMalloc = ClUseAfterReturn
1022 && LocalStackSize <= kMaxStackMallocSize;
1023
1024 Instruction *InsBefore = AllocaVec[0];
1025 IRBuilder<> IRB(InsBefore);
1026
1027
1028 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1029 AllocaInst *MyAlloca =
1030 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1031 MyAlloca->setAlignment(RedzoneSize);
1032 assert(MyAlloca->isStaticAlloca());
1033 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1034 Value *LocalStackBase = OrigStackBase;
1035
1036 if (DoStackMalloc) {
1037 Value *AsanStackMallocFunc = M.getOrInsertFunction(
1038 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
1039 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1040 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1041 }
1042
1043 // This string will be parsed by the run-time (DescribeStackAddress).
1044 SmallString<2048> StackDescriptionStorage;
1045 raw_svector_ostream StackDescription(StackDescriptionStorage);
1046 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1047
1048 uint64_t Pos = RedzoneSize;
1049 // Replace Alloca instructions with base+offset.
1050 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1051 AllocaInst *AI = AllocaVec[i];
1052 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1053 StringRef Name = AI->getName();
1054 StackDescription << Pos << " " << SizeInBytes << " "
1055 << Name.size() << " " << Name << " ";
1056 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1057 assert((AlignedSize % RedzoneSize) == 0);
1058 AI->replaceAllUsesWith(
1059 IRB.CreateIntToPtr(
1060 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1061 AI->getType()));
1062 Pos += AlignedSize + RedzoneSize;
1063 }
1064 assert(Pos == LocalStackSize);
1065
1066 // Write the Magic value and the frame description constant to the redzone.
1067 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1068 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1069 BasePlus0);
1070 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1071 ConstantInt::get(IntptrTy, LongSize/8));
1072 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1073 Value *Description = IRB.CreatePointerCast(
1074 createPrivateGlobalForString(M, StackDescription.str()),
1075 IntptrTy);
1076 IRB.CreateStore(Description, BasePlus1);
1077
1078 // Poison the stack redzones at the entry.
1079 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1080 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1081
1082 Value *AsanStackFreeFunc = NULL;
1083 if (DoStackMalloc) {
1084 AsanStackFreeFunc = M.getOrInsertFunction(
1085 kAsanStackFreeName, IRB.getVoidTy(),
1086 IntptrTy, IntptrTy, IntptrTy, NULL);
1087 }
1088
1089 // Unpoison the stack before all ret instructions.
1090 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1091 Instruction *Ret = RetVec[i];
1092 IRBuilder<> IRBRet(Ret);
1093
1094 // Mark the current frame as retired.
1095 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1096 BasePlus0);
1097 // Unpoison the stack.
1098 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1099
1100 if (DoStackMalloc) {
1101 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1102 ConstantInt::get(IntptrTy, LocalStackSize),
1103 OrigStackBase);
1104 }
1105 }
1106
1107 if (ClDebugStack) {
1108 DEBUG(dbgs() << F);
1109 }
1110
1111 return true;
1112}