blob: f80c8c4fa60c228dbeea6c12fc54f5061f7b9bbb [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"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000019#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/OwningPtr.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000025#include "llvm/ADT/Triple.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000026#include "llvm/Function.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000027#include "llvm/IntrinsicInst.h"
28#include "llvm/LLVMContext.h"
29#include "llvm/Module.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/DataTypes.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/IRBuilder.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000034#include "llvm/Support/raw_ostream.h"
35#include "llvm/Support/system_error.h"
36#include "llvm/Target/TargetData.h"
37#include "llvm/Target/TargetMachine.h"
38#include "llvm/Transforms/Instrumentation.h"
39#include "llvm/Transforms/Utils/BasicBlockUtils.h"
40#include "llvm/Transforms/Utils/ModuleUtils.h"
41#include "llvm/Type.h"
42
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
75// Command-line flags.
76
77// This flag may need to be replaced with -f[no-]asan-reads.
78static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
79 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
80static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
81 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000082static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
83 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
84 cl::Hidden, cl::init(true));
Kostya Serebryany324cbb82012-06-28 09:34:41 +000085// This flags limits the number of instructions to be instrumented
86// in any given BB. Normally, this should be set to unlimited (INT_MAX),
87// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
88// set it to 10000.
89static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
90 cl::init(10000),
91 cl::desc("maximal number of instructions to instrument in any given BB"),
92 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +000093// This flag may need to be replaced with -f[no]asan-stack.
94static cl::opt<bool> ClStack("asan-stack",
95 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
96// This flag may need to be replaced with -f[no]asan-use-after-return.
97static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
98 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
99// This flag may need to be replaced with -f[no]asan-globals.
100static cl::opt<bool> ClGlobals("asan-globals",
101 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
102static cl::opt<bool> ClMemIntrin("asan-memintrin",
103 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
104// This flag may need to be replaced with -fasan-blacklist.
105static cl::opt<std::string> ClBlackListFile("asan-blacklist",
106 cl::desc("File containing the list of functions to ignore "
107 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000108
109// These flags allow to change the shadow mapping.
110// The shadow mapping looks like
111// Shadow = (Mem >> scale) + (1 << offset_log)
112static cl::opt<int> ClMappingScale("asan-mapping-scale",
113 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
114static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
115 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
116
117// Optimization flags. Not user visible, used mostly for testing
118// and benchmarking the tool.
119static cl::opt<bool> ClOpt("asan-opt",
120 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
121static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
122 cl::desc("Instrument the same temp just once"), cl::Hidden,
123 cl::init(true));
124static cl::opt<bool> ClOptGlobals("asan-opt-globals",
125 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
126
127// Debug flags.
128static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
129 cl::init(0));
130static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
131 cl::Hidden, cl::init(0));
132static cl::opt<std::string> ClDebugFunc("asan-debug-func",
133 cl::Hidden, cl::desc("Debug func"));
134static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
135 cl::Hidden, cl::init(-1));
136static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
137 cl::Hidden, cl::init(-1));
138
139namespace {
140
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000141/// AddressSanitizer: instrument the code in module to find memory bugs.
142struct AddressSanitizer : public ModulePass {
143 AddressSanitizer();
Alexander Potapenko25878042012-01-23 11:22:43 +0000144 virtual const char *getPassName() const;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000145 void instrumentMop(Instruction *I);
146 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
147 Value *Addr, uint32_t TypeSize, bool IsWrite);
148 Instruction *generateCrashCode(IRBuilder<> &IRB, Value *Addr,
149 bool IsWrite, uint32_t TypeSize);
150 bool instrumentMemIntrinsic(MemIntrinsic *MI);
151 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
152 Value *Size,
153 Instruction *InsertBefore, bool IsWrite);
154 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
155 bool handleFunction(Module &M, Function &F);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000156 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000157 bool poisonStackInFunction(Module &M, Function &F);
158 virtual bool runOnModule(Module &M);
159 bool insertGlobalRedzones(Module &M);
160 BranchInst *splitBlockAndInsertIfThen(Instruction *SplitBefore, Value *Cmp);
161 static char ID; // Pass identification, replacement for typeid
162
163 private:
164
165 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
166 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanovd8313be2012-03-02 10:41:08 +0000167 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000168 return SizeInBytes;
169 }
170 uint64_t getAlignedSize(uint64_t SizeInBytes) {
171 return ((SizeInBytes + RedzoneSize - 1)
172 / RedzoneSize) * RedzoneSize;
173 }
174 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
175 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
176 return getAlignedSize(SizeInBytes);
177 }
178
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000179 Function *checkInterfaceFunction(Constant *FuncOrBitcast);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000180 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
181 Value *ShadowBase, bool DoPoison);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000182 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000183
184 Module *CurrentModule;
185 LLVMContext *C;
186 TargetData *TD;
187 uint64_t MappingOffset;
188 int MappingScale;
189 size_t RedzoneSize;
190 int LongSize;
191 Type *IntptrTy;
192 Type *IntptrPtrTy;
193 Function *AsanCtorFunction;
194 Function *AsanInitFunction;
195 Instruction *CtorInsertBefore;
Kostya Serebryanya1c45042012-03-14 23:22:10 +0000196 OwningPtr<FunctionBlackList> BL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000197};
198} // namespace
199
200char AddressSanitizer::ID = 0;
201INITIALIZE_PASS(AddressSanitizer, "asan",
202 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
203 false, false)
204AddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
205ModulePass *llvm::createAddressSanitizerPass() {
206 return new AddressSanitizer();
207}
208
Alexander Potapenko25878042012-01-23 11:22:43 +0000209const char *AddressSanitizer::getPassName() const {
210 return "AddressSanitizer";
211}
212
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000213// Create a constant for Str so that we can pass it to the run-time lib.
214static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000215 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000216 return new GlobalVariable(M, StrConst->getType(), true,
217 GlobalValue::PrivateLinkage, StrConst, "");
218}
219
220// Split the basic block and insert an if-then code.
221// Before:
222// Head
223// SplitBefore
224// Tail
225// After:
226// Head
227// if (Cmp)
228// NewBasicBlock
229// SplitBefore
230// Tail
231//
232// Returns the NewBasicBlock's terminator.
233BranchInst *AddressSanitizer::splitBlockAndInsertIfThen(
234 Instruction *SplitBefore, Value *Cmp) {
235 BasicBlock *Head = SplitBefore->getParent();
236 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
237 TerminatorInst *HeadOldTerm = Head->getTerminator();
238 BasicBlock *NewBasicBlock =
239 BasicBlock::Create(*C, "", Head->getParent());
240 BranchInst *HeadNewTerm = BranchInst::Create(/*ifTrue*/NewBasicBlock,
241 /*ifFalse*/Tail,
242 Cmp);
243 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
244
245 BranchInst *CheckTerm = BranchInst::Create(Tail, NewBasicBlock);
246 return CheckTerm;
247}
248
249Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
250 // Shadow >> scale
251 Shadow = IRB.CreateLShr(Shadow, MappingScale);
252 if (MappingOffset == 0)
253 return Shadow;
254 // (Shadow >> scale) | offset
255 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
256 MappingOffset));
257}
258
259void AddressSanitizer::instrumentMemIntrinsicParam(Instruction *OrigIns,
260 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
261 // Check the first byte.
262 {
263 IRBuilder<> IRB(InsertBefore);
264 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
265 }
266 // Check the last byte.
267 {
268 IRBuilder<> IRB(InsertBefore);
269 Value *SizeMinusOne = IRB.CreateSub(
270 Size, ConstantInt::get(Size->getType(), 1));
271 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
272 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
273 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
274 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
275 }
276}
277
278// Instrument memset/memmove/memcpy
279bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
280 Value *Dst = MI->getDest();
281 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
282 Value *Src = MemTran ? MemTran->getSource() : NULL;
283 Value *Length = MI->getLength();
284
285 Constant *ConstLength = dyn_cast<Constant>(Length);
286 Instruction *InsertBefore = MI;
287 if (ConstLength) {
288 if (ConstLength->isNullValue()) return false;
289 } else {
290 // The size is not a constant so it could be zero -- check at run-time.
291 IRBuilder<> IRB(InsertBefore);
292
293 Value *Cmp = IRB.CreateICmpNE(Length,
294 Constant::getNullValue(Length->getType()));
295 InsertBefore = splitBlockAndInsertIfThen(InsertBefore, Cmp);
296 }
297
298 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
299 if (Src)
300 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
301 return true;
302}
303
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000304// If I is an interesting memory access, return the PointerOperand
305// and set IsWrite. Otherwise return NULL.
306static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000307 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000308 if (!ClInstrumentReads) return NULL;
309 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000310 return LI->getPointerOperand();
311 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000312 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
313 if (!ClInstrumentWrites) return NULL;
314 *IsWrite = true;
315 return SI->getPointerOperand();
316 }
317 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
318 if (!ClInstrumentAtomics) return NULL;
319 *IsWrite = true;
320 return RMW->getPointerOperand();
321 }
322 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
323 if (!ClInstrumentAtomics) return NULL;
324 *IsWrite = true;
325 return XCHG->getPointerOperand();
326 }
327 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000328}
329
330void AddressSanitizer::instrumentMop(Instruction *I) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000331 bool IsWrite;
332 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
333 assert(Addr);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000334 if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
335 // We are accessing a global scalar variable. Nothing to catch here.
336 return;
337 }
338 Type *OrigPtrTy = Addr->getType();
339 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
340
341 assert(OrigTy->isSized());
342 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
343
344 if (TypeSize != 8 && TypeSize != 16 &&
345 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
346 // Ignore all unusual sizes.
347 return;
348 }
349
350 IRBuilder<> IRB(I);
351 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
352}
353
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000354// Validate the result of Module::getOrInsertFunction called for an interface
355// function of AddressSanitizer. If the instrumented module defines a function
356// with the same name, their prototypes must match, otherwise
357// getOrInsertFunction returns a bitcast.
358Function *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
359 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
360 FuncOrBitcast->dump();
361 report_fatal_error("trying to redefine an AddressSanitizer "
362 "interface function");
363}
364
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000365Instruction *AddressSanitizer::generateCrashCode(
366 IRBuilder<> &IRB, Value *Addr, bool IsWrite, uint32_t TypeSize) {
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000367 // IsWrite and TypeSize are encoded in the function name.
368 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
369 (IsWrite ? "store" : "load") + itostr(TypeSize / 8);
370 Value *ReportWarningFunc = CurrentModule->getOrInsertFunction(
371 FunctionName, IRB.getVoidTy(), IntptrTy, NULL);
372 CallInst *Call = IRB.CreateCall(ReportWarningFunc, Addr);
373 Call->setDoesNotReturn();
374 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000375}
376
377void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
378 IRBuilder<> &IRB, Value *Addr,
379 uint32_t TypeSize, bool IsWrite) {
380 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
381
382 Type *ShadowTy = IntegerType::get(
383 *C, std::max(8U, TypeSize >> MappingScale));
384 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
385 Value *ShadowPtr = memToShadow(AddrLong, IRB);
386 Value *CmpVal = Constant::getNullValue(ShadowTy);
387 Value *ShadowValue = IRB.CreateLoad(
388 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
389
390 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
391
392 Instruction *CheckTerm = splitBlockAndInsertIfThen(
393 cast<Instruction>(Cmp)->getNextNode(), Cmp);
394 IRBuilder<> IRB2(CheckTerm);
395
396 size_t Granularity = 1 << MappingScale;
397 if (TypeSize < 8 * Granularity) {
398 // Addr & (Granularity - 1)
Kostya Serebryany3f119982012-04-27 10:04:53 +0000399 Value *LastAccessedByte = IRB2.CreateAnd(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000400 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
401 // (Addr & (Granularity - 1)) + size - 1
Kostya Serebryany3f119982012-04-27 10:04:53 +0000402 if (TypeSize / 8 > 1)
403 LastAccessedByte = IRB2.CreateAdd(
404 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000405 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
406 LastAccessedByte = IRB2.CreateIntCast(
407 LastAccessedByte, IRB.getInt8Ty(), false);
408 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
409 Value *Cmp2 = IRB2.CreateICmpSGE(LastAccessedByte, ShadowValue);
410
411 CheckTerm = splitBlockAndInsertIfThen(CheckTerm, Cmp2);
412 }
413
414 IRBuilder<> IRB1(CheckTerm);
415 Instruction *Crash = generateCrashCode(IRB1, AddrLong, IsWrite, TypeSize);
416 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryanycc1d8562011-12-01 18:54:53 +0000417 ReplaceInstWithInst(CheckTerm, new UnreachableInst(*C));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000418}
419
420// This function replaces all global variables with new variables that have
421// trailing redzones. It also creates a function that poisons
422// redzones and inserts this function into llvm.global_ctors.
423bool AddressSanitizer::insertGlobalRedzones(Module &M) {
424 SmallVector<GlobalVariable *, 16> GlobalsToChange;
425
426 for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
427 E = M.getGlobalList().end(); G != E; ++G) {
428 Type *Ty = cast<PointerType>(G->getType())->getElementType();
429 DEBUG(dbgs() << "GLOBAL: " << *G);
430
431 if (!Ty->isSized()) continue;
432 if (!G->hasInitializer()) continue;
Kostya Serebryany7cf2a042011-11-17 23:14:59 +0000433 // Touch only those globals that will not be defined in other modules.
434 // Don't handle ODR type linkages since other modules may be built w/o asan.
Kostya Serebryany2e7fb2f2011-11-17 23:37:53 +0000435 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
436 G->getLinkage() != GlobalVariable::PrivateLinkage &&
437 G->getLinkage() != GlobalVariable::InternalLinkage)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000438 continue;
Kostya Serebryanyd2703de2011-11-23 02:10:54 +0000439 // Two problems with thread-locals:
440 // - The address of the main thread's copy can't be computed at link-time.
441 // - Need to poison all copies, not just the main thread's one.
442 if (G->isThreadLocal())
443 continue;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000444 // For now, just ignore this Alloca if the alignment is large.
445 if (G->getAlignment() > RedzoneSize) continue;
446
447 // Ignore all the globals with the names starting with "\01L_OBJC_".
448 // Many of those are put into the .cstring section. The linker compresses
449 // that section by removing the spare \0s after the string terminator, so
450 // our redzones get broken.
451 if ((G->getName().find("\01L_OBJC_") == 0) ||
452 (G->getName().find("\01l_OBJC_") == 0)) {
453 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
454 continue;
455 }
456
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000457 if (G->hasSection()) {
458 StringRef Section(G->getSection());
Alexander Potapenko8375bc92012-01-30 10:40:22 +0000459 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
460 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
461 // them.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000462 if ((Section.find("__OBJC,") == 0) ||
463 (Section.find("__DATA, __objc_") == 0)) {
464 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
465 continue;
466 }
Alexander Potapenko8375bc92012-01-30 10:40:22 +0000467 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
468 // Constant CFString instances are compiled in the following way:
469 // -- the string buffer is emitted into
470 // __TEXT,__cstring,cstring_literals
471 // -- the constant NSConstantString structure referencing that buffer
472 // is placed into __DATA,__cfstring
473 // Therefore there's no point in placing redzones into __DATA,__cfstring.
474 // Moreover, it causes the linker to crash on OS X 10.7
475 if (Section.find("__DATA,__cfstring") == 0) {
476 DEBUG(dbgs() << "Ignoring CFString: " << *G);
477 continue;
478 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000479 }
480
481 GlobalsToChange.push_back(G);
482 }
483
484 size_t n = GlobalsToChange.size();
485 if (n == 0) return false;
486
487 // A global is described by a structure
488 // size_t beg;
489 // size_t size;
490 // size_t size_with_redzone;
491 // const char *name;
492 // We initialize an array of such structures and pass it to a run-time call.
493 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
494 IntptrTy, IntptrTy, NULL);
495 SmallVector<Constant *, 16> Initializers(n);
496
497 IRBuilder<> IRB(CtorInsertBefore);
498
499 for (size_t i = 0; i < n; i++) {
500 GlobalVariable *G = GlobalsToChange[i];
501 PointerType *PtrTy = cast<PointerType>(G->getType());
502 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000503 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000504 uint64_t RightRedzoneSize = RedzoneSize +
505 (RedzoneSize - (SizeInBytes % RedzoneSize));
506 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
507
508 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
509 Constant *NewInitializer = ConstantStruct::get(
510 NewTy, G->getInitializer(),
511 Constant::getNullValue(RightRedZoneTy), NULL);
512
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000513 SmallString<2048> DescriptionOfGlobal = G->getName();
514 DescriptionOfGlobal += " (";
515 DescriptionOfGlobal += M.getModuleIdentifier();
516 DescriptionOfGlobal += ")";
517 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000518
519 // Create a new global variable with enough space for a redzone.
520 GlobalVariable *NewGlobal = new GlobalVariable(
521 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000522 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000523 NewGlobal->copyAttributesFrom(G);
524 NewGlobal->setAlignment(RedzoneSize);
525
526 Value *Indices2[2];
527 Indices2[0] = IRB.getInt32(0);
528 Indices2[1] = IRB.getInt32(0);
529
530 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000531 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000532 NewGlobal->takeName(G);
533 G->eraseFromParent();
534
535 Initializers[i] = ConstantStruct::get(
536 GlobalStructTy,
537 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
538 ConstantInt::get(IntptrTy, SizeInBytes),
539 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
540 ConstantExpr::getPointerCast(Name, IntptrTy),
541 NULL);
542 DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
543 }
544
545 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
546 GlobalVariable *AllGlobals = new GlobalVariable(
547 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
548 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
549
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000550 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000551 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
552 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
553
554 IRB.CreateCall2(AsanRegisterGlobals,
555 IRB.CreatePointerCast(AllGlobals, IntptrTy),
556 ConstantInt::get(IntptrTy, n));
557
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000558 // We also need to unregister globals at the end, e.g. when a shared library
559 // gets closed.
560 Function *AsanDtorFunction = Function::Create(
561 FunctionType::get(Type::getVoidTy(*C), false),
562 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
563 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
564 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000565 Function *AsanUnregisterGlobals =
566 checkInterfaceFunction(M.getOrInsertFunction(
567 kAsanUnregisterGlobalsName,
568 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000569 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
570
571 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
572 IRB.CreatePointerCast(AllGlobals, IntptrTy),
573 ConstantInt::get(IntptrTy, n));
574 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
575
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000576 DEBUG(dbgs() << M);
577 return true;
578}
579
580// virtual
581bool AddressSanitizer::runOnModule(Module &M) {
582 // Initialize the private fields. No one has accessed them before.
583 TD = getAnalysisIfAvailable<TargetData>();
584 if (!TD)
585 return false;
Kostya Serebryanya1c45042012-03-14 23:22:10 +0000586 BL.reset(new FunctionBlackList(ClBlackListFile));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000587
588 CurrentModule = &M;
589 C = &(M.getContext());
590 LongSize = TD->getPointerSizeInBits();
591 IntptrTy = Type::getIntNTy(*C, LongSize);
592 IntptrPtrTy = PointerType::get(IntptrTy, 0);
593
594 AsanCtorFunction = Function::Create(
595 FunctionType::get(Type::getVoidTy(*C), false),
596 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
597 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
598 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
599
600 // call __asan_init in the module ctor.
601 IRBuilder<> IRB(CtorInsertBefore);
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000602 AsanInitFunction = checkInterfaceFunction(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000603 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
604 AsanInitFunction->setLinkage(Function::ExternalLinkage);
605 IRB.CreateCall(AsanInitFunction);
606
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000607 llvm::Triple targetTriple(M.getTargetTriple());
608 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::ANDROIDEABI;
609
610 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
611 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000612 if (ClMappingOffsetLog >= 0) {
613 if (ClMappingOffsetLog == 0) {
614 // special case
615 MappingOffset = 0;
616 } else {
617 MappingOffset = 1ULL << ClMappingOffsetLog;
618 }
619 }
620 MappingScale = kDefaultShadowScale;
621 if (ClMappingScale) {
622 MappingScale = ClMappingScale;
623 }
624 // Redzone used for stack and globals is at least 32 bytes.
625 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
626 RedzoneSize = std::max(32, (int)(1 << MappingScale));
627
628 bool Res = false;
629
630 if (ClGlobals)
631 Res |= insertGlobalRedzones(M);
632
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000633 if (ClMappingOffsetLog >= 0) {
634 // Tell the run-time the current values of mapping offset and scale.
635 GlobalValue *asan_mapping_offset =
636 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
637 ConstantInt::get(IntptrTy, MappingOffset),
638 kAsanMappingOffsetName);
639 // Read the global, otherwise it may be optimized away.
640 IRB.CreateLoad(asan_mapping_offset, true);
641 }
642 if (ClMappingScale) {
643 GlobalValue *asan_mapping_scale =
644 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
645 ConstantInt::get(IntptrTy, MappingScale),
646 kAsanMappingScaleName);
647 // Read the global, otherwise it may be optimized away.
648 IRB.CreateLoad(asan_mapping_scale, true);
649 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000650
651
652 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
653 if (F->isDeclaration()) continue;
654 Res |= handleFunction(M, *F);
655 }
656
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000657 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryany9b027412011-12-12 18:01:46 +0000658
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000659 return Res;
660}
661
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000662bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
663 // For each NSObject descendant having a +load method, this method is invoked
664 // by the ObjC runtime before any of the static constructors is called.
665 // Therefore we need to instrument such methods with a call to __asan_init
666 // at the beginning in order to initialize our runtime before any access to
667 // the shadow memory.
668 // We cannot just ignore these methods, because they may call other
669 // instrumented functions.
670 if (F.getName().find(" load]") != std::string::npos) {
671 IRBuilder<> IRB(F.begin()->begin());
672 IRB.CreateCall(AsanInitFunction);
673 return true;
674 }
675 return false;
676}
677
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000678bool AddressSanitizer::handleFunction(Module &M, Function &F) {
679 if (BL->isIn(F)) return false;
680 if (&F == AsanCtorFunction) return false;
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000681
682 // If needed, insert __asan_init before checking for AddressSafety attr.
683 maybeInsertAsanInitAtFunctionEntry(F);
684
Kostya Serebryany0307b9a2012-01-24 19:34:43 +0000685 if (!F.hasFnAttr(Attribute::AddressSafety)) return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000686
687 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
688 return false;
689 // We want to instrument every address only once per basic block
690 // (unless there are calls between uses).
691 SmallSet<Value*, 16> TempsToInstrument;
692 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000693 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000694 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000695
696 // Fill the set of memory operations to instrument.
697 for (Function::iterator FI = F.begin(), FE = F.end();
698 FI != FE; ++FI) {
699 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000700 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000701 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
702 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +0000703 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000704 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000705 if (ClOpt && ClOptSameTemp) {
706 if (!TempsToInstrument.insert(Addr))
707 continue; // We've seen this temp in the current BB.
708 }
709 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
710 // ok, take it.
711 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000712 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000713 // A call inside BB.
714 TempsToInstrument.clear();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000715 if (CI->doesNotReturn()) {
716 NoReturnCalls.push_back(CI);
717 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000718 }
719 continue;
720 }
721 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000722 NumInsnsPerBB++;
723 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
724 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000725 }
726 }
727
728 // Instrument.
729 int NumInstrumented = 0;
730 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
731 Instruction *Inst = ToInstrument[i];
732 if (ClDebugMin < 0 || ClDebugMax < 0 ||
733 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000734 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000735 instrumentMop(Inst);
736 else
737 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
738 }
739 NumInstrumented++;
740 }
741
742 DEBUG(dbgs() << F);
743
744 bool ChangedStack = poisonStackInFunction(M, F);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000745
746 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
747 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
748 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
749 Instruction *CI = NoReturnCalls[i];
750 IRBuilder<> IRB(CI);
751 IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
752 IRB.getVoidTy(), NULL));
753 }
754
755 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000756}
757
758static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
759 if (ShadowRedzoneSize == 1) return PoisonByte;
760 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
761 if (ShadowRedzoneSize == 4)
762 return (PoisonByte << 24) + (PoisonByte << 16) +
763 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +0000764 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000765}
766
767static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
768 size_t Size,
769 size_t RedzoneSize,
770 size_t ShadowGranularity,
771 uint8_t Magic) {
772 for (size_t i = 0; i < RedzoneSize;
773 i+= ShadowGranularity, Shadow++) {
774 if (i + ShadowGranularity <= Size) {
775 *Shadow = 0; // fully addressable
776 } else if (i >= Size) {
777 *Shadow = Magic; // unaddressable
778 } else {
779 *Shadow = Size - i; // first Size-i bytes are addressable
780 }
781 }
782}
783
784void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
785 IRBuilder<> IRB,
786 Value *ShadowBase, bool DoPoison) {
787 size_t ShadowRZSize = RedzoneSize >> MappingScale;
788 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
789 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
790 Type *RZPtrTy = PointerType::get(RZTy, 0);
791
792 Value *PoisonLeft = ConstantInt::get(RZTy,
793 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
794 Value *PoisonMid = ConstantInt::get(RZTy,
795 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
796 Value *PoisonRight = ConstantInt::get(RZTy,
797 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
798
799 // poison the first red zone.
800 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
801
802 // poison all other red zones.
803 uint64_t Pos = RedzoneSize;
804 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
805 AllocaInst *AI = AllocaVec[i];
806 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
807 uint64_t AlignedSize = getAlignedAllocaSize(AI);
808 assert(AlignedSize - SizeInBytes < RedzoneSize);
809 Value *Ptr = NULL;
810
811 Pos += AlignedSize;
812
813 assert(ShadowBase->getType() == IntptrTy);
814 if (SizeInBytes < AlignedSize) {
815 // Poison the partial redzone at right
816 Ptr = IRB.CreateAdd(
817 ShadowBase, ConstantInt::get(IntptrTy,
818 (Pos >> MappingScale) - ShadowRZSize));
819 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
820 uint32_t Poison = 0;
821 if (DoPoison) {
822 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
823 RedzoneSize,
824 1ULL << MappingScale,
825 kAsanStackPartialRedzoneMagic);
826 }
827 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
828 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
829 }
830
831 // Poison the full redzone at right.
832 Ptr = IRB.CreateAdd(ShadowBase,
833 ConstantInt::get(IntptrTy, Pos >> MappingScale));
834 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
835 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
836
837 Pos += RedzoneSize;
838 }
839}
840
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000841// Workaround for bug 11395: we don't want to instrument stack in functions
842// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
Kostya Serebryanyd2703de2011-11-23 02:10:54 +0000843// FIXME: remove once the bug 11395 is fixed.
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000844bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
845 if (LongSize != 32) return false;
846 CallInst *CI = dyn_cast<CallInst>(I);
847 if (!CI || !CI->isInlineAsm()) return false;
848 if (CI->getNumArgOperands() <= 5) return false;
849 // We have inline assembly with quite a few arguments.
850 return true;
851}
852
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000853// Find all static Alloca instructions and put
854// poisoned red zones around all of them.
855// Then unpoison everything back before the function returns.
856//
857// Stack poisoning does not play well with exception handling.
858// When an exception is thrown, we essentially bypass the code
859// that unpoisones the stack. This is why the run-time library has
860// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
861// stack in the interceptor. This however does not work inside the
862// actual function which catches the exception. Most likely because the
863// compiler hoists the load of the shadow value somewhere too high.
864// This causes asan to report a non-existing bug on 453.povray.
865// It sounds like an LLVM bug.
866bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
867 if (!ClStack) return false;
868 SmallVector<AllocaInst*, 16> AllocaVec;
869 SmallVector<Instruction*, 8> RetVec;
870 uint64_t TotalSize = 0;
871
872 // Filter out Alloca instructions we want (and can) handle.
873 // Collect Ret instructions.
874 for (Function::iterator FI = F.begin(), FE = F.end();
875 FI != FE; ++FI) {
876 BasicBlock &BB = *FI;
877 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
878 BI != BE; ++BI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000879 if (isa<ReturnInst>(BI)) {
880 RetVec.push_back(BI);
881 continue;
882 }
883
884 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
885 if (!AI) continue;
886 if (AI->isArrayAllocation()) continue;
887 if (!AI->isStaticAlloca()) continue;
888 if (!AI->getAllocatedType()->isSized()) continue;
889 if (AI->getAlignment() > RedzoneSize) continue;
890 AllocaVec.push_back(AI);
891 uint64_t AlignedSize = getAlignedAllocaSize(AI);
892 TotalSize += AlignedSize;
893 }
894 }
895
896 if (AllocaVec.empty()) return false;
897
898 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
899
900 bool DoStackMalloc = ClUseAfterReturn
901 && LocalStackSize <= kMaxStackMallocSize;
902
903 Instruction *InsBefore = AllocaVec[0];
904 IRBuilder<> IRB(InsBefore);
905
906
907 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
908 AllocaInst *MyAlloca =
909 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
910 MyAlloca->setAlignment(RedzoneSize);
911 assert(MyAlloca->isStaticAlloca());
912 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
913 Value *LocalStackBase = OrigStackBase;
914
915 if (DoStackMalloc) {
916 Value *AsanStackMallocFunc = M.getOrInsertFunction(
917 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
918 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
919 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
920 }
921
922 // This string will be parsed by the run-time (DescribeStackAddress).
923 SmallString<2048> StackDescriptionStorage;
924 raw_svector_ostream StackDescription(StackDescriptionStorage);
925 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
926
927 uint64_t Pos = RedzoneSize;
928 // Replace Alloca instructions with base+offset.
929 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
930 AllocaInst *AI = AllocaVec[i];
931 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
932 StringRef Name = AI->getName();
933 StackDescription << Pos << " " << SizeInBytes << " "
934 << Name.size() << " " << Name << " ";
935 uint64_t AlignedSize = getAlignedAllocaSize(AI);
936 assert((AlignedSize % RedzoneSize) == 0);
937 AI->replaceAllUsesWith(
938 IRB.CreateIntToPtr(
939 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
940 AI->getType()));
941 Pos += AlignedSize + RedzoneSize;
942 }
943 assert(Pos == LocalStackSize);
944
945 // Write the Magic value and the frame description constant to the redzone.
946 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
947 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
948 BasePlus0);
949 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
950 ConstantInt::get(IntptrTy, LongSize/8));
951 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
952 Value *Description = IRB.CreatePointerCast(
953 createPrivateGlobalForString(M, StackDescription.str()),
954 IntptrTy);
955 IRB.CreateStore(Description, BasePlus1);
956
957 // Poison the stack redzones at the entry.
958 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
959 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
960
961 Value *AsanStackFreeFunc = NULL;
962 if (DoStackMalloc) {
963 AsanStackFreeFunc = M.getOrInsertFunction(
964 kAsanStackFreeName, IRB.getVoidTy(),
965 IntptrTy, IntptrTy, IntptrTy, NULL);
966 }
967
968 // Unpoison the stack before all ret instructions.
969 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
970 Instruction *Ret = RetVec[i];
971 IRBuilder<> IRBRet(Ret);
972
973 // Mark the current frame as retired.
974 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
975 BasePlus0);
976 // Unpoison the stack.
977 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
978
979 if (DoStackMalloc) {
980 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
981 ConstantInt::get(IntptrTy, LocalStackSize),
982 OrigStackBase);
983 }
984 }
985
986 if (ClDebugStack) {
987 DEBUG(dbgs() << F);
988 }
989
990 return true;
991}