blob: 1fc1871d7124a7b32082395d09c09ef7a0328dbd [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 Serebryanyc0ed3e52012-07-16 16:15:40 +0000147/// An object of this type is created while instrumenting every function.
148struct AsanFunctionContext {
149 AsanFunctionContext() {
150 memset(this, 0, sizeof(*this));
151 }
152
153 // These are initially zero. If we require at least one call to
154 // __asan_report_{read,write}{1,2,4,8,16}, an appropriate BB is created.
155 BasicBlock *CrashBlock[2][kNumberOfAccessSizes];
156};
157
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000158/// AddressSanitizer: instrument the code in module to find memory bugs.
159struct AddressSanitizer : public ModulePass {
160 AddressSanitizer();
Alexander Potapenko25878042012-01-23 11:22:43 +0000161 virtual const char *getPassName() const;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000162 void instrumentMop(AsanFunctionContext &AFC, Instruction *I);
163 void instrumentAddress(AsanFunctionContext &AFC,
164 Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000165 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000166 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
167 Value *ShadowValue, uint32_t TypeSize);
168 Instruction *generateCrashCode(BasicBlock *BB, Value *Addr,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000169 bool IsWrite, uint32_t TypeSize);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000170 bool instrumentMemIntrinsic(AsanFunctionContext &AFC, MemIntrinsic *MI);
171 void instrumentMemIntrinsicParam(AsanFunctionContext &AFC,
172 Instruction *OrigIns, Value *Addr,
173 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000174 Instruction *InsertBefore, bool IsWrite);
175 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
176 bool handleFunction(Module &M, Function &F);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000177 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000178 bool poisonStackInFunction(Module &M, Function &F);
179 virtual bool runOnModule(Module &M);
180 bool insertGlobalRedzones(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000181 static char ID; // Pass identification, replacement for typeid
182
183 private:
184
185 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
186 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanovd8313be2012-03-02 10:41:08 +0000187 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000188 return SizeInBytes;
189 }
190 uint64_t getAlignedSize(uint64_t SizeInBytes) {
191 return ((SizeInBytes + RedzoneSize - 1)
192 / RedzoneSize) * RedzoneSize;
193 }
194 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
195 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
196 return getAlignedSize(SizeInBytes);
197 }
198
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000199 Function *checkInterfaceFunction(Constant *FuncOrBitcast);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000200 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
201 Value *ShadowBase, bool DoPoison);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000202 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000203
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000204 LLVMContext *C;
205 TargetData *TD;
206 uint64_t MappingOffset;
207 int MappingScale;
208 size_t RedzoneSize;
209 int LongSize;
210 Type *IntptrTy;
211 Type *IntptrPtrTy;
212 Function *AsanCtorFunction;
213 Function *AsanInitFunction;
214 Instruction *CtorInsertBefore;
Kostya Serebryanya1c45042012-03-14 23:22:10 +0000215 OwningPtr<FunctionBlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000216 // This array is indexed by AccessIsWrite and log2(AccessSize).
217 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000218};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000219
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000220} // namespace
221
222char AddressSanitizer::ID = 0;
223INITIALIZE_PASS(AddressSanitizer, "asan",
224 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
225 false, false)
226AddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
227ModulePass *llvm::createAddressSanitizerPass() {
228 return new AddressSanitizer();
229}
230
Alexander Potapenko25878042012-01-23 11:22:43 +0000231const char *AddressSanitizer::getPassName() const {
232 return "AddressSanitizer";
233}
234
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000235// Create a constant for Str so that we can pass it to the run-time lib.
236static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000237 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000238 return new GlobalVariable(M, StrConst->getType(), true,
239 GlobalValue::PrivateLinkage, StrConst, "");
240}
241
242// Split the basic block and insert an if-then code.
243// Before:
244// Head
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000245// Cmp
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000246// Tail
247// After:
248// Head
249// if (Cmp)
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000250// ThenBlock
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000251// Tail
252//
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000253// If ThenBlock is zero, a new block is created and its terminator is returned.
254// Otherwize NULL is returned.
255static BranchInst *splitBlockAndInsertIfThen(Value *Cmp,
256 BasicBlock *ThenBlock = 0) {
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000257 Instruction *SplitBefore = cast<Instruction>(Cmp)->getNextNode();
Chandler Carruthc3c8db92012-07-16 08:58:53 +0000258 BasicBlock *Head = SplitBefore->getParent();
Chandler Carruth349f14c2012-07-16 10:01:02 +0000259 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
Chandler Carruthc3c8db92012-07-16 08:58:53 +0000260 TerminatorInst *HeadOldTerm = Head->getTerminator();
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000261 BranchInst *CheckTerm = NULL;
262 if (!ThenBlock) {
263 LLVMContext &C = Head->getParent()->getParent()->getContext();
264 ThenBlock = BasicBlock::Create(C, "", Head->getParent());
265 CheckTerm = BranchInst::Create(Tail, ThenBlock);
266 }
Chandler Carruth349f14c2012-07-16 10:01:02 +0000267 BranchInst *HeadNewTerm =
268 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cmp);
269 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
Chandler Carruthc3c8db92012-07-16 08:58:53 +0000270
Chandler Carruth349f14c2012-07-16 10:01:02 +0000271 return CheckTerm;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000272}
273
274Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
275 // Shadow >> scale
276 Shadow = IRB.CreateLShr(Shadow, MappingScale);
277 if (MappingOffset == 0)
278 return Shadow;
279 // (Shadow >> scale) | offset
280 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
281 MappingOffset));
282}
283
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000284void AddressSanitizer::instrumentMemIntrinsicParam(
285 AsanFunctionContext &AFC, Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000286 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
287 // Check the first byte.
288 {
289 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000290 instrumentAddress(AFC, OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000291 }
292 // Check the last byte.
293 {
294 IRBuilder<> IRB(InsertBefore);
295 Value *SizeMinusOne = IRB.CreateSub(
296 Size, ConstantInt::get(Size->getType(), 1));
297 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
298 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
299 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000300 instrumentAddress(AFC, OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000301 }
302}
303
304// Instrument memset/memmove/memcpy
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000305bool AddressSanitizer::instrumentMemIntrinsic(AsanFunctionContext &AFC,
306 MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000307 Value *Dst = MI->getDest();
308 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
309 Value *Src = MemTran ? MemTran->getSource() : NULL;
310 Value *Length = MI->getLength();
311
312 Constant *ConstLength = dyn_cast<Constant>(Length);
313 Instruction *InsertBefore = MI;
314 if (ConstLength) {
315 if (ConstLength->isNullValue()) return false;
316 } else {
317 // The size is not a constant so it could be zero -- check at run-time.
318 IRBuilder<> IRB(InsertBefore);
319
320 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000321 Constant::getNullValue(Length->getType()));
322 InsertBefore = splitBlockAndInsertIfThen(Cmp);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000323 }
324
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000325 instrumentMemIntrinsicParam(AFC, MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000326 if (Src)
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000327 instrumentMemIntrinsicParam(AFC, MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000328 return true;
329}
330
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000331// If I is an interesting memory access, return the PointerOperand
332// and set IsWrite. Otherwise return NULL.
333static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000334 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000335 if (!ClInstrumentReads) return NULL;
336 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000337 return LI->getPointerOperand();
338 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000339 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
340 if (!ClInstrumentWrites) return NULL;
341 *IsWrite = true;
342 return SI->getPointerOperand();
343 }
344 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
345 if (!ClInstrumentAtomics) return NULL;
346 *IsWrite = true;
347 return RMW->getPointerOperand();
348 }
349 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
350 if (!ClInstrumentAtomics) return NULL;
351 *IsWrite = true;
352 return XCHG->getPointerOperand();
353 }
354 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000355}
356
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000357void AddressSanitizer::instrumentMop(AsanFunctionContext &AFC, Instruction *I) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000358 bool IsWrite;
359 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
360 assert(Addr);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000361 if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
362 // We are accessing a global scalar variable. Nothing to catch here.
363 return;
364 }
365 Type *OrigPtrTy = Addr->getType();
366 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
367
368 assert(OrigTy->isSized());
369 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
370
371 if (TypeSize != 8 && TypeSize != 16 &&
372 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
373 // Ignore all unusual sizes.
374 return;
375 }
376
377 IRBuilder<> IRB(I);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000378 instrumentAddress(AFC, I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000379}
380
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000381// Validate the result of Module::getOrInsertFunction called for an interface
382// function of AddressSanitizer. If the instrumented module defines a function
383// with the same name, their prototypes must match, otherwise
384// getOrInsertFunction returns a bitcast.
385Function *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
386 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
387 FuncOrBitcast->dump();
388 report_fatal_error("trying to redefine an AddressSanitizer "
389 "interface function");
390}
391
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000392Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000393 BasicBlock *BB, Value *Addr, bool IsWrite, uint32_t TypeSize) {
394 IRBuilder<> IRB(BB->getFirstNonPHI());
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000395 size_t AccessSizeIndex = CountTrailingZeros_32(TypeSize / 8);
396 assert(AccessSizeIndex < kNumberOfAccessSizes);
397 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
398 Addr);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000399 Call->setDoesNotReturn();
400 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000401}
402
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000403Value * AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
404 Value *ShadowValue,
405 uint32_t TypeSize) {
406 size_t Granularity = 1 << MappingScale;
407 // Addr & (Granularity - 1)
408 Value *LastAccessedByte = IRB.CreateAnd(
409 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
410 // (Addr & (Granularity - 1)) + size - 1
411 if (TypeSize / 8 > 1)
412 LastAccessedByte = IRB.CreateAdd(
413 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
414 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
415 LastAccessedByte = IRB.CreateIntCast(
416 LastAccessedByte, IRB.getInt8Ty(), false);
417 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
418 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
419}
420
421void AddressSanitizer::instrumentAddress(AsanFunctionContext &AFC,
422 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000423 IRBuilder<> &IRB, Value *Addr,
424 uint32_t TypeSize, bool IsWrite) {
425 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
426
427 Type *ShadowTy = IntegerType::get(
428 *C, std::max(8U, TypeSize >> MappingScale));
429 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
430 Value *ShadowPtr = memToShadow(AddrLong, IRB);
431 Value *CmpVal = Constant::getNullValue(ShadowTy);
432 Value *ShadowValue = IRB.CreateLoad(
433 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
434
435 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
436
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000437 BasicBlock *CrashBlock = NULL;
438 if (ClMergeCallbacks) {
439 llvm_unreachable("unimplemented yet");
440 } else {
441 CrashBlock = BasicBlock::Create(*C, "crash_bb",
442 OrigIns->getParent()->getParent());
443 new UnreachableInst(*C, CrashBlock);
444 Instruction *Crash =
445 generateCrashCode(CrashBlock, AddrLong, IsWrite, TypeSize);
446 Crash->setDebugLoc(OrigIns->getDebugLoc());
447 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000448
449 size_t Granularity = 1 << MappingScale;
450 if (TypeSize < 8 * Granularity) {
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000451 Instruction *CheckTerm = splitBlockAndInsertIfThen(Cmp);
452 IRB.SetInsertPoint(CheckTerm);
453 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
454 splitBlockAndInsertIfThen(Cmp2, CrashBlock);
455 } else {
456 splitBlockAndInsertIfThen(Cmp, CrashBlock);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000457 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000458}
459
460// This function replaces all global variables with new variables that have
461// trailing redzones. It also creates a function that poisons
462// redzones and inserts this function into llvm.global_ctors.
463bool AddressSanitizer::insertGlobalRedzones(Module &M) {
464 SmallVector<GlobalVariable *, 16> GlobalsToChange;
465
466 for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
467 E = M.getGlobalList().end(); G != E; ++G) {
468 Type *Ty = cast<PointerType>(G->getType())->getElementType();
469 DEBUG(dbgs() << "GLOBAL: " << *G);
470
471 if (!Ty->isSized()) continue;
472 if (!G->hasInitializer()) continue;
Kostya Serebryany7cf2a042011-11-17 23:14:59 +0000473 // Touch only those globals that will not be defined in other modules.
474 // Don't handle ODR type linkages since other modules may be built w/o asan.
Kostya Serebryany2e7fb2f2011-11-17 23:37:53 +0000475 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
476 G->getLinkage() != GlobalVariable::PrivateLinkage &&
477 G->getLinkage() != GlobalVariable::InternalLinkage)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000478 continue;
Kostya Serebryanyd2703de2011-11-23 02:10:54 +0000479 // Two problems with thread-locals:
480 // - The address of the main thread's copy can't be computed at link-time.
481 // - Need to poison all copies, not just the main thread's one.
482 if (G->isThreadLocal())
483 continue;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000484 // For now, just ignore this Alloca if the alignment is large.
485 if (G->getAlignment() > RedzoneSize) continue;
486
487 // Ignore all the globals with the names starting with "\01L_OBJC_".
488 // Many of those are put into the .cstring section. The linker compresses
489 // that section by removing the spare \0s after the string terminator, so
490 // our redzones get broken.
491 if ((G->getName().find("\01L_OBJC_") == 0) ||
492 (G->getName().find("\01l_OBJC_") == 0)) {
493 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
494 continue;
495 }
496
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000497 if (G->hasSection()) {
498 StringRef Section(G->getSection());
Alexander Potapenko8375bc92012-01-30 10:40:22 +0000499 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
500 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
501 // them.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000502 if ((Section.find("__OBJC,") == 0) ||
503 (Section.find("__DATA, __objc_") == 0)) {
504 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
505 continue;
506 }
Alexander Potapenko8375bc92012-01-30 10:40:22 +0000507 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
508 // Constant CFString instances are compiled in the following way:
509 // -- the string buffer is emitted into
510 // __TEXT,__cstring,cstring_literals
511 // -- the constant NSConstantString structure referencing that buffer
512 // is placed into __DATA,__cfstring
513 // Therefore there's no point in placing redzones into __DATA,__cfstring.
514 // Moreover, it causes the linker to crash on OS X 10.7
515 if (Section.find("__DATA,__cfstring") == 0) {
516 DEBUG(dbgs() << "Ignoring CFString: " << *G);
517 continue;
518 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000519 }
520
521 GlobalsToChange.push_back(G);
522 }
523
524 size_t n = GlobalsToChange.size();
525 if (n == 0) return false;
526
527 // A global is described by a structure
528 // size_t beg;
529 // size_t size;
530 // size_t size_with_redzone;
531 // const char *name;
532 // We initialize an array of such structures and pass it to a run-time call.
533 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
534 IntptrTy, IntptrTy, NULL);
535 SmallVector<Constant *, 16> Initializers(n);
536
537 IRBuilder<> IRB(CtorInsertBefore);
538
539 for (size_t i = 0; i < n; i++) {
540 GlobalVariable *G = GlobalsToChange[i];
541 PointerType *PtrTy = cast<PointerType>(G->getType());
542 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000543 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000544 uint64_t RightRedzoneSize = RedzoneSize +
545 (RedzoneSize - (SizeInBytes % RedzoneSize));
546 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
547
548 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
549 Constant *NewInitializer = ConstantStruct::get(
550 NewTy, G->getInitializer(),
551 Constant::getNullValue(RightRedZoneTy), NULL);
552
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000553 SmallString<2048> DescriptionOfGlobal = G->getName();
554 DescriptionOfGlobal += " (";
555 DescriptionOfGlobal += M.getModuleIdentifier();
556 DescriptionOfGlobal += ")";
557 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000558
559 // Create a new global variable with enough space for a redzone.
560 GlobalVariable *NewGlobal = new GlobalVariable(
561 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000562 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000563 NewGlobal->copyAttributesFrom(G);
564 NewGlobal->setAlignment(RedzoneSize);
565
566 Value *Indices2[2];
567 Indices2[0] = IRB.getInt32(0);
568 Indices2[1] = IRB.getInt32(0);
569
570 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000571 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000572 NewGlobal->takeName(G);
573 G->eraseFromParent();
574
575 Initializers[i] = ConstantStruct::get(
576 GlobalStructTy,
577 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
578 ConstantInt::get(IntptrTy, SizeInBytes),
579 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
580 ConstantExpr::getPointerCast(Name, IntptrTy),
581 NULL);
582 DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
583 }
584
585 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
586 GlobalVariable *AllGlobals = new GlobalVariable(
587 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
588 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
589
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000590 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000591 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
592 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
593
594 IRB.CreateCall2(AsanRegisterGlobals,
595 IRB.CreatePointerCast(AllGlobals, IntptrTy),
596 ConstantInt::get(IntptrTy, n));
597
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000598 // We also need to unregister globals at the end, e.g. when a shared library
599 // gets closed.
600 Function *AsanDtorFunction = Function::Create(
601 FunctionType::get(Type::getVoidTy(*C), false),
602 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
603 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
604 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000605 Function *AsanUnregisterGlobals =
606 checkInterfaceFunction(M.getOrInsertFunction(
607 kAsanUnregisterGlobalsName,
608 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000609 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
610
611 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
612 IRB.CreatePointerCast(AllGlobals, IntptrTy),
613 ConstantInt::get(IntptrTy, n));
614 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
615
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000616 DEBUG(dbgs() << M);
617 return true;
618}
619
620// virtual
621bool AddressSanitizer::runOnModule(Module &M) {
622 // Initialize the private fields. No one has accessed them before.
623 TD = getAnalysisIfAvailable<TargetData>();
624 if (!TD)
625 return false;
Kostya Serebryanya1c45042012-03-14 23:22:10 +0000626 BL.reset(new FunctionBlackList(ClBlackListFile));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000627
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000628 C = &(M.getContext());
629 LongSize = TD->getPointerSizeInBits();
630 IntptrTy = Type::getIntNTy(*C, LongSize);
631 IntptrPtrTy = PointerType::get(IntptrTy, 0);
632
633 AsanCtorFunction = Function::Create(
634 FunctionType::get(Type::getVoidTy(*C), false),
635 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
636 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
637 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
638
639 // call __asan_init in the module ctor.
640 IRBuilder<> IRB(CtorInsertBefore);
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000641 AsanInitFunction = checkInterfaceFunction(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000642 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
643 AsanInitFunction->setLinkage(Function::ExternalLinkage);
644 IRB.CreateCall(AsanInitFunction);
645
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000646 // Create __asan_report* callbacks.
647 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
648 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
649 AccessSizeIndex++) {
650 // IsWrite and TypeSize are encoded in the function name.
651 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
652 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
653 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>(
654 M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
655 }
656 }
657
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000658 llvm::Triple targetTriple(M.getTargetTriple());
659 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::ANDROIDEABI;
660
661 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
662 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000663 if (ClMappingOffsetLog >= 0) {
664 if (ClMappingOffsetLog == 0) {
665 // special case
666 MappingOffset = 0;
667 } else {
668 MappingOffset = 1ULL << ClMappingOffsetLog;
669 }
670 }
671 MappingScale = kDefaultShadowScale;
672 if (ClMappingScale) {
673 MappingScale = ClMappingScale;
674 }
675 // Redzone used for stack and globals is at least 32 bytes.
676 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
677 RedzoneSize = std::max(32, (int)(1 << MappingScale));
678
679 bool Res = false;
680
681 if (ClGlobals)
682 Res |= insertGlobalRedzones(M);
683
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000684 if (ClMappingOffsetLog >= 0) {
685 // Tell the run-time the current values of mapping offset and scale.
686 GlobalValue *asan_mapping_offset =
687 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
688 ConstantInt::get(IntptrTy, MappingOffset),
689 kAsanMappingOffsetName);
690 // Read the global, otherwise it may be optimized away.
691 IRB.CreateLoad(asan_mapping_offset, true);
692 }
693 if (ClMappingScale) {
694 GlobalValue *asan_mapping_scale =
695 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
696 ConstantInt::get(IntptrTy, MappingScale),
697 kAsanMappingScaleName);
698 // Read the global, otherwise it may be optimized away.
699 IRB.CreateLoad(asan_mapping_scale, true);
700 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000701
702
703 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
704 if (F->isDeclaration()) continue;
705 Res |= handleFunction(M, *F);
706 }
707
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000708 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryany9b027412011-12-12 18:01:46 +0000709
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000710 return Res;
711}
712
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000713bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
714 // For each NSObject descendant having a +load method, this method is invoked
715 // by the ObjC runtime before any of the static constructors is called.
716 // Therefore we need to instrument such methods with a call to __asan_init
717 // at the beginning in order to initialize our runtime before any access to
718 // the shadow memory.
719 // We cannot just ignore these methods, because they may call other
720 // instrumented functions.
721 if (F.getName().find(" load]") != std::string::npos) {
722 IRBuilder<> IRB(F.begin()->begin());
723 IRB.CreateCall(AsanInitFunction);
724 return true;
725 }
726 return false;
727}
728
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000729bool AddressSanitizer::handleFunction(Module &M, Function &F) {
730 if (BL->isIn(F)) return false;
731 if (&F == AsanCtorFunction) return false;
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000732
733 // If needed, insert __asan_init before checking for AddressSafety attr.
734 maybeInsertAsanInitAtFunctionEntry(F);
735
Kostya Serebryany0307b9a2012-01-24 19:34:43 +0000736 if (!F.hasFnAttr(Attribute::AddressSafety)) return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000737
738 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
739 return false;
740 // We want to instrument every address only once per basic block
741 // (unless there are calls between uses).
742 SmallSet<Value*, 16> TempsToInstrument;
743 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000744 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000745 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000746
747 // Fill the set of memory operations to instrument.
748 for (Function::iterator FI = F.begin(), FE = F.end();
749 FI != FE; ++FI) {
750 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000751 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000752 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
753 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +0000754 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000755 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000756 if (ClOpt && ClOptSameTemp) {
757 if (!TempsToInstrument.insert(Addr))
758 continue; // We've seen this temp in the current BB.
759 }
760 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
761 // ok, take it.
762 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000763 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000764 // A call inside BB.
765 TempsToInstrument.clear();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000766 if (CI->doesNotReturn()) {
767 NoReturnCalls.push_back(CI);
768 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000769 }
770 continue;
771 }
772 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000773 NumInsnsPerBB++;
774 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
775 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000776 }
777 }
778
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000779 AsanFunctionContext AFC;
780
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000781 // Instrument.
782 int NumInstrumented = 0;
783 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
784 Instruction *Inst = ToInstrument[i];
785 if (ClDebugMin < 0 || ClDebugMax < 0 ||
786 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000787 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000788 instrumentMop(AFC, Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000789 else
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000790 instrumentMemIntrinsic(AFC, cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000791 }
792 NumInstrumented++;
793 }
794
795 DEBUG(dbgs() << F);
796
797 bool ChangedStack = poisonStackInFunction(M, F);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000798
799 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
800 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
801 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
802 Instruction *CI = NoReturnCalls[i];
803 IRBuilder<> IRB(CI);
804 IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
805 IRB.getVoidTy(), NULL));
806 }
807
808 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000809}
810
811static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
812 if (ShadowRedzoneSize == 1) return PoisonByte;
813 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
814 if (ShadowRedzoneSize == 4)
815 return (PoisonByte << 24) + (PoisonByte << 16) +
816 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +0000817 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000818}
819
820static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
821 size_t Size,
822 size_t RedzoneSize,
823 size_t ShadowGranularity,
824 uint8_t Magic) {
825 for (size_t i = 0; i < RedzoneSize;
826 i+= ShadowGranularity, Shadow++) {
827 if (i + ShadowGranularity <= Size) {
828 *Shadow = 0; // fully addressable
829 } else if (i >= Size) {
830 *Shadow = Magic; // unaddressable
831 } else {
832 *Shadow = Size - i; // first Size-i bytes are addressable
833 }
834 }
835}
836
837void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
838 IRBuilder<> IRB,
839 Value *ShadowBase, bool DoPoison) {
840 size_t ShadowRZSize = RedzoneSize >> MappingScale;
841 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
842 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
843 Type *RZPtrTy = PointerType::get(RZTy, 0);
844
845 Value *PoisonLeft = ConstantInt::get(RZTy,
846 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
847 Value *PoisonMid = ConstantInt::get(RZTy,
848 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
849 Value *PoisonRight = ConstantInt::get(RZTy,
850 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
851
852 // poison the first red zone.
853 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
854
855 // poison all other red zones.
856 uint64_t Pos = RedzoneSize;
857 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
858 AllocaInst *AI = AllocaVec[i];
859 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
860 uint64_t AlignedSize = getAlignedAllocaSize(AI);
861 assert(AlignedSize - SizeInBytes < RedzoneSize);
862 Value *Ptr = NULL;
863
864 Pos += AlignedSize;
865
866 assert(ShadowBase->getType() == IntptrTy);
867 if (SizeInBytes < AlignedSize) {
868 // Poison the partial redzone at right
869 Ptr = IRB.CreateAdd(
870 ShadowBase, ConstantInt::get(IntptrTy,
871 (Pos >> MappingScale) - ShadowRZSize));
872 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
873 uint32_t Poison = 0;
874 if (DoPoison) {
875 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
876 RedzoneSize,
877 1ULL << MappingScale,
878 kAsanStackPartialRedzoneMagic);
879 }
880 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
881 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
882 }
883
884 // Poison the full redzone at right.
885 Ptr = IRB.CreateAdd(ShadowBase,
886 ConstantInt::get(IntptrTy, Pos >> MappingScale));
887 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
888 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
889
890 Pos += RedzoneSize;
891 }
892}
893
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000894// Workaround for bug 11395: we don't want to instrument stack in functions
895// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
Kostya Serebryanyd2703de2011-11-23 02:10:54 +0000896// FIXME: remove once the bug 11395 is fixed.
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000897bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
898 if (LongSize != 32) return false;
899 CallInst *CI = dyn_cast<CallInst>(I);
900 if (!CI || !CI->isInlineAsm()) return false;
901 if (CI->getNumArgOperands() <= 5) return false;
902 // We have inline assembly with quite a few arguments.
903 return true;
904}
905
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000906// Find all static Alloca instructions and put
907// poisoned red zones around all of them.
908// Then unpoison everything back before the function returns.
909//
910// Stack poisoning does not play well with exception handling.
911// When an exception is thrown, we essentially bypass the code
912// that unpoisones the stack. This is why the run-time library has
913// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
914// stack in the interceptor. This however does not work inside the
915// actual function which catches the exception. Most likely because the
916// compiler hoists the load of the shadow value somewhere too high.
917// This causes asan to report a non-existing bug on 453.povray.
918// It sounds like an LLVM bug.
919bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
920 if (!ClStack) return false;
921 SmallVector<AllocaInst*, 16> AllocaVec;
922 SmallVector<Instruction*, 8> RetVec;
923 uint64_t TotalSize = 0;
924
925 // Filter out Alloca instructions we want (and can) handle.
926 // Collect Ret instructions.
927 for (Function::iterator FI = F.begin(), FE = F.end();
928 FI != FE; ++FI) {
929 BasicBlock &BB = *FI;
930 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
931 BI != BE; ++BI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000932 if (isa<ReturnInst>(BI)) {
933 RetVec.push_back(BI);
934 continue;
935 }
936
937 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
938 if (!AI) continue;
939 if (AI->isArrayAllocation()) continue;
940 if (!AI->isStaticAlloca()) continue;
941 if (!AI->getAllocatedType()->isSized()) continue;
942 if (AI->getAlignment() > RedzoneSize) continue;
943 AllocaVec.push_back(AI);
944 uint64_t AlignedSize = getAlignedAllocaSize(AI);
945 TotalSize += AlignedSize;
946 }
947 }
948
949 if (AllocaVec.empty()) return false;
950
951 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
952
953 bool DoStackMalloc = ClUseAfterReturn
954 && LocalStackSize <= kMaxStackMallocSize;
955
956 Instruction *InsBefore = AllocaVec[0];
957 IRBuilder<> IRB(InsBefore);
958
959
960 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
961 AllocaInst *MyAlloca =
962 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
963 MyAlloca->setAlignment(RedzoneSize);
964 assert(MyAlloca->isStaticAlloca());
965 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
966 Value *LocalStackBase = OrigStackBase;
967
968 if (DoStackMalloc) {
969 Value *AsanStackMallocFunc = M.getOrInsertFunction(
970 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
971 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
972 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
973 }
974
975 // This string will be parsed by the run-time (DescribeStackAddress).
976 SmallString<2048> StackDescriptionStorage;
977 raw_svector_ostream StackDescription(StackDescriptionStorage);
978 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
979
980 uint64_t Pos = RedzoneSize;
981 // Replace Alloca instructions with base+offset.
982 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
983 AllocaInst *AI = AllocaVec[i];
984 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
985 StringRef Name = AI->getName();
986 StackDescription << Pos << " " << SizeInBytes << " "
987 << Name.size() << " " << Name << " ";
988 uint64_t AlignedSize = getAlignedAllocaSize(AI);
989 assert((AlignedSize % RedzoneSize) == 0);
990 AI->replaceAllUsesWith(
991 IRB.CreateIntToPtr(
992 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
993 AI->getType()));
994 Pos += AlignedSize + RedzoneSize;
995 }
996 assert(Pos == LocalStackSize);
997
998 // Write the Magic value and the frame description constant to the redzone.
999 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1000 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1001 BasePlus0);
1002 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1003 ConstantInt::get(IntptrTy, LongSize/8));
1004 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1005 Value *Description = IRB.CreatePointerCast(
1006 createPrivateGlobalForString(M, StackDescription.str()),
1007 IntptrTy);
1008 IRB.CreateStore(Description, BasePlus1);
1009
1010 // Poison the stack redzones at the entry.
1011 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1012 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1013
1014 Value *AsanStackFreeFunc = NULL;
1015 if (DoStackMalloc) {
1016 AsanStackFreeFunc = M.getOrInsertFunction(
1017 kAsanStackFreeName, IRB.getVoidTy(),
1018 IntptrTy, IntptrTy, IntptrTy, NULL);
1019 }
1020
1021 // Unpoison the stack before all ret instructions.
1022 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1023 Instruction *Ret = RetVec[i];
1024 IRBuilder<> IRBRet(Ret);
1025
1026 // Mark the current frame as retired.
1027 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1028 BasePlus0);
1029 // Unpoison the stack.
1030 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1031
1032 if (DoStackMalloc) {
1033 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1034 ConstantInt::get(IntptrTy, LocalStackSize),
1035 OrigStackBase);
1036 }
1037 }
1038
1039 if (ClDebugStack) {
1040 DEBUG(dbgs() << F);
1041 }
1042
1043 return true;
1044}