blob: dbd9ebaf55cc0d4ff847496e6ef082269e921eed [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
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/OwningPtr.h"
20#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/SmallString.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/Function.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000025#include "llvm/IntrinsicInst.h"
26#include "llvm/LLVMContext.h"
27#include "llvm/Module.h"
28#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/DataTypes.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/IRBuilder.h"
32#include "llvm/Support/MemoryBuffer.h"
33#include "llvm/Support/Regex.h"
34#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;
51
52static const size_t kMaxStackMallocSize = 1 << 16; // 64K
53static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
54static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
55
56static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000057static const char *kAsanModuleDtorName = "asan.module_dtor";
58static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000059static const char *kAsanReportErrorTemplate = "__asan_report_";
60static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000061static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000062static const char *kAsanInitName = "__asan_init";
63static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
64static const char *kAsanMappingScaleName = "__asan_mapping_scale";
65static const char *kAsanStackMallocName = "__asan_stack_malloc";
66static const char *kAsanStackFreeName = "__asan_stack_free";
67
68static const int kAsanStackLeftRedzoneMagic = 0xf1;
69static const int kAsanStackMidRedzoneMagic = 0xf2;
70static const int kAsanStackRightRedzoneMagic = 0xf3;
71static const int kAsanStackPartialRedzoneMagic = 0xf4;
72
73// Command-line flags.
74
75// This flag may need to be replaced with -f[no-]asan-reads.
76static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
77 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
78static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
79 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
80// This flag may need to be replaced with -f[no]asan-stack.
81static cl::opt<bool> ClStack("asan-stack",
82 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
83// This flag may need to be replaced with -f[no]asan-use-after-return.
84static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
85 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
86// This flag may need to be replaced with -f[no]asan-globals.
87static cl::opt<bool> ClGlobals("asan-globals",
88 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
89static cl::opt<bool> ClMemIntrin("asan-memintrin",
90 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
91// This flag may need to be replaced with -fasan-blacklist.
92static cl::opt<std::string> ClBlackListFile("asan-blacklist",
93 cl::desc("File containing the list of functions to ignore "
94 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +000095
96// These flags allow to change the shadow mapping.
97// The shadow mapping looks like
98// Shadow = (Mem >> scale) + (1 << offset_log)
99static cl::opt<int> ClMappingScale("asan-mapping-scale",
100 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
101static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
102 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
103
104// Optimization flags. Not user visible, used mostly for testing
105// and benchmarking the tool.
106static cl::opt<bool> ClOpt("asan-opt",
107 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
108static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
109 cl::desc("Instrument the same temp just once"), cl::Hidden,
110 cl::init(true));
111static cl::opt<bool> ClOptGlobals("asan-opt-globals",
112 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
113
114// Debug flags.
115static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
116 cl::init(0));
117static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
118 cl::Hidden, cl::init(0));
119static cl::opt<std::string> ClDebugFunc("asan-debug-func",
120 cl::Hidden, cl::desc("Debug func"));
121static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
122 cl::Hidden, cl::init(-1));
123static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
124 cl::Hidden, cl::init(-1));
125
126namespace {
127
128// Blacklisted functions are not instrumented.
129// The blacklist file contains one or more lines like this:
130// ---
131// fun:FunctionWildCard
132// ---
133// This is similar to the "ignore" feature of ThreadSanitizer.
134// http://code.google.com/p/data-race-test/wiki/ThreadSanitizerIgnores
135class BlackList {
136 public:
137 BlackList(const std::string &Path);
138 bool isIn(const Function &F);
139 private:
140 Regex *Functions;
141};
142
143/// AddressSanitizer: instrument the code in module to find memory bugs.
144struct AddressSanitizer : public ModulePass {
145 AddressSanitizer();
146 void instrumentMop(Instruction *I);
147 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
148 Value *Addr, uint32_t TypeSize, bool IsWrite);
149 Instruction *generateCrashCode(IRBuilder<> &IRB, Value *Addr,
150 bool IsWrite, uint32_t TypeSize);
151 bool instrumentMemIntrinsic(MemIntrinsic *MI);
152 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
153 Value *Size,
154 Instruction *InsertBefore, bool IsWrite);
155 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
156 bool handleFunction(Module &M, Function &F);
157 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();
167 uint64_t SizeInBytes = TD->getTypeStoreSizeInBits(Ty) / 8;
168 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
179 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
180 Value *ShadowBase, bool DoPoison);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000181 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000182
183 Module *CurrentModule;
184 LLVMContext *C;
185 TargetData *TD;
186 uint64_t MappingOffset;
187 int MappingScale;
188 size_t RedzoneSize;
189 int LongSize;
190 Type *IntptrTy;
191 Type *IntptrPtrTy;
192 Function *AsanCtorFunction;
193 Function *AsanInitFunction;
194 Instruction *CtorInsertBefore;
195 OwningPtr<BlackList> BL;
196};
197} // namespace
198
199char AddressSanitizer::ID = 0;
200INITIALIZE_PASS(AddressSanitizer, "asan",
201 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
202 false, false)
203AddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
204ModulePass *llvm::createAddressSanitizerPass() {
205 return new AddressSanitizer();
206}
207
208// Create a constant for Str so that we can pass it to the run-time lib.
209static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
210 Constant *StrConst = ConstantArray::get(M.getContext(), Str);
211 return new GlobalVariable(M, StrConst->getType(), true,
212 GlobalValue::PrivateLinkage, StrConst, "");
213}
214
215// Split the basic block and insert an if-then code.
216// Before:
217// Head
218// SplitBefore
219// Tail
220// After:
221// Head
222// if (Cmp)
223// NewBasicBlock
224// SplitBefore
225// Tail
226//
227// Returns the NewBasicBlock's terminator.
228BranchInst *AddressSanitizer::splitBlockAndInsertIfThen(
229 Instruction *SplitBefore, Value *Cmp) {
230 BasicBlock *Head = SplitBefore->getParent();
231 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
232 TerminatorInst *HeadOldTerm = Head->getTerminator();
233 BasicBlock *NewBasicBlock =
234 BasicBlock::Create(*C, "", Head->getParent());
235 BranchInst *HeadNewTerm = BranchInst::Create(/*ifTrue*/NewBasicBlock,
236 /*ifFalse*/Tail,
237 Cmp);
238 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
239
240 BranchInst *CheckTerm = BranchInst::Create(Tail, NewBasicBlock);
241 return CheckTerm;
242}
243
244Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
245 // Shadow >> scale
246 Shadow = IRB.CreateLShr(Shadow, MappingScale);
247 if (MappingOffset == 0)
248 return Shadow;
249 // (Shadow >> scale) | offset
250 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
251 MappingOffset));
252}
253
254void AddressSanitizer::instrumentMemIntrinsicParam(Instruction *OrigIns,
255 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
256 // Check the first byte.
257 {
258 IRBuilder<> IRB(InsertBefore);
259 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
260 }
261 // Check the last byte.
262 {
263 IRBuilder<> IRB(InsertBefore);
264 Value *SizeMinusOne = IRB.CreateSub(
265 Size, ConstantInt::get(Size->getType(), 1));
266 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
267 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
268 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
269 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
270 }
271}
272
273// Instrument memset/memmove/memcpy
274bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
275 Value *Dst = MI->getDest();
276 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
277 Value *Src = MemTran ? MemTran->getSource() : NULL;
278 Value *Length = MI->getLength();
279
280 Constant *ConstLength = dyn_cast<Constant>(Length);
281 Instruction *InsertBefore = MI;
282 if (ConstLength) {
283 if (ConstLength->isNullValue()) return false;
284 } else {
285 // The size is not a constant so it could be zero -- check at run-time.
286 IRBuilder<> IRB(InsertBefore);
287
288 Value *Cmp = IRB.CreateICmpNE(Length,
289 Constant::getNullValue(Length->getType()));
290 InsertBefore = splitBlockAndInsertIfThen(InsertBefore, Cmp);
291 }
292
293 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
294 if (Src)
295 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
296 return true;
297}
298
299static Value *getLDSTOperand(Instruction *I) {
300 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
301 return LI->getPointerOperand();
302 }
303 return cast<StoreInst>(*I).getPointerOperand();
304}
305
306void AddressSanitizer::instrumentMop(Instruction *I) {
307 int IsWrite = isa<StoreInst>(*I);
308 Value *Addr = getLDSTOperand(I);
309 if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
310 // We are accessing a global scalar variable. Nothing to catch here.
311 return;
312 }
313 Type *OrigPtrTy = Addr->getType();
314 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
315
316 assert(OrigTy->isSized());
317 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
318
319 if (TypeSize != 8 && TypeSize != 16 &&
320 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
321 // Ignore all unusual sizes.
322 return;
323 }
324
325 IRBuilder<> IRB(I);
326 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
327}
328
329Instruction *AddressSanitizer::generateCrashCode(
330 IRBuilder<> &IRB, Value *Addr, bool IsWrite, uint32_t TypeSize) {
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000331 // IsWrite and TypeSize are encoded in the function name.
332 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
333 (IsWrite ? "store" : "load") + itostr(TypeSize / 8);
334 Value *ReportWarningFunc = CurrentModule->getOrInsertFunction(
335 FunctionName, IRB.getVoidTy(), IntptrTy, NULL);
336 CallInst *Call = IRB.CreateCall(ReportWarningFunc, Addr);
337 Call->setDoesNotReturn();
338 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000339}
340
341void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
342 IRBuilder<> &IRB, Value *Addr,
343 uint32_t TypeSize, bool IsWrite) {
344 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
345
346 Type *ShadowTy = IntegerType::get(
347 *C, std::max(8U, TypeSize >> MappingScale));
348 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
349 Value *ShadowPtr = memToShadow(AddrLong, IRB);
350 Value *CmpVal = Constant::getNullValue(ShadowTy);
351 Value *ShadowValue = IRB.CreateLoad(
352 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
353
354 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
355
356 Instruction *CheckTerm = splitBlockAndInsertIfThen(
357 cast<Instruction>(Cmp)->getNextNode(), Cmp);
358 IRBuilder<> IRB2(CheckTerm);
359
360 size_t Granularity = 1 << MappingScale;
361 if (TypeSize < 8 * Granularity) {
362 // Addr & (Granularity - 1)
363 Value *Lower3Bits = IRB2.CreateAnd(
364 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
365 // (Addr & (Granularity - 1)) + size - 1
366 Value *LastAccessedByte = IRB2.CreateAdd(
367 Lower3Bits, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
368 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
369 LastAccessedByte = IRB2.CreateIntCast(
370 LastAccessedByte, IRB.getInt8Ty(), false);
371 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
372 Value *Cmp2 = IRB2.CreateICmpSGE(LastAccessedByte, ShadowValue);
373
374 CheckTerm = splitBlockAndInsertIfThen(CheckTerm, Cmp2);
375 }
376
377 IRBuilder<> IRB1(CheckTerm);
378 Instruction *Crash = generateCrashCode(IRB1, AddrLong, IsWrite, TypeSize);
379 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryanycc1d8562011-12-01 18:54:53 +0000380 ReplaceInstWithInst(CheckTerm, new UnreachableInst(*C));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000381}
382
383// This function replaces all global variables with new variables that have
384// trailing redzones. It also creates a function that poisons
385// redzones and inserts this function into llvm.global_ctors.
386bool AddressSanitizer::insertGlobalRedzones(Module &M) {
387 SmallVector<GlobalVariable *, 16> GlobalsToChange;
388
389 for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
390 E = M.getGlobalList().end(); G != E; ++G) {
391 Type *Ty = cast<PointerType>(G->getType())->getElementType();
392 DEBUG(dbgs() << "GLOBAL: " << *G);
393
394 if (!Ty->isSized()) continue;
395 if (!G->hasInitializer()) continue;
Kostya Serebryany7cf2a042011-11-17 23:14:59 +0000396 // Touch only those globals that will not be defined in other modules.
397 // Don't handle ODR type linkages since other modules may be built w/o asan.
Kostya Serebryany2e7fb2f2011-11-17 23:37:53 +0000398 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
399 G->getLinkage() != GlobalVariable::PrivateLinkage &&
400 G->getLinkage() != GlobalVariable::InternalLinkage)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000401 continue;
Kostya Serebryanyd2703de2011-11-23 02:10:54 +0000402 // Two problems with thread-locals:
403 // - The address of the main thread's copy can't be computed at link-time.
404 // - Need to poison all copies, not just the main thread's one.
405 if (G->isThreadLocal())
406 continue;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000407 // For now, just ignore this Alloca if the alignment is large.
408 if (G->getAlignment() > RedzoneSize) continue;
409
410 // Ignore all the globals with the names starting with "\01L_OBJC_".
411 // Many of those are put into the .cstring section. The linker compresses
412 // that section by removing the spare \0s after the string terminator, so
413 // our redzones get broken.
414 if ((G->getName().find("\01L_OBJC_") == 0) ||
415 (G->getName().find("\01l_OBJC_") == 0)) {
416 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
417 continue;
418 }
419
420 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
421 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
422 // them.
423 if (G->hasSection()) {
424 StringRef Section(G->getSection());
425 if ((Section.find("__OBJC,") == 0) ||
426 (Section.find("__DATA, __objc_") == 0)) {
427 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
428 continue;
429 }
430 }
431
432 GlobalsToChange.push_back(G);
433 }
434
435 size_t n = GlobalsToChange.size();
436 if (n == 0) return false;
437
438 // A global is described by a structure
439 // size_t beg;
440 // size_t size;
441 // size_t size_with_redzone;
442 // const char *name;
443 // We initialize an array of such structures and pass it to a run-time call.
444 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
445 IntptrTy, IntptrTy, NULL);
446 SmallVector<Constant *, 16> Initializers(n);
447
448 IRBuilder<> IRB(CtorInsertBefore);
449
450 for (size_t i = 0; i < n; i++) {
451 GlobalVariable *G = GlobalsToChange[i];
452 PointerType *PtrTy = cast<PointerType>(G->getType());
453 Type *Ty = PtrTy->getElementType();
454 uint64_t SizeInBytes = TD->getTypeStoreSizeInBits(Ty) / 8;
455 uint64_t RightRedzoneSize = RedzoneSize +
456 (RedzoneSize - (SizeInBytes % RedzoneSize));
457 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
458
459 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
460 Constant *NewInitializer = ConstantStruct::get(
461 NewTy, G->getInitializer(),
462 Constant::getNullValue(RightRedZoneTy), NULL);
463
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000464 SmallString<2048> DescriptionOfGlobal = G->getName();
465 DescriptionOfGlobal += " (";
466 DescriptionOfGlobal += M.getModuleIdentifier();
467 DescriptionOfGlobal += ")";
468 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000469
470 // Create a new global variable with enough space for a redzone.
471 GlobalVariable *NewGlobal = new GlobalVariable(
472 M, NewTy, G->isConstant(), G->getLinkage(),
473 NewInitializer, "", G, G->isThreadLocal());
474 NewGlobal->copyAttributesFrom(G);
475 NewGlobal->setAlignment(RedzoneSize);
476
477 Value *Indices2[2];
478 Indices2[0] = IRB.getInt32(0);
479 Indices2[1] = IRB.getInt32(0);
480
481 G->replaceAllUsesWith(
482 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, 2));
483 NewGlobal->takeName(G);
484 G->eraseFromParent();
485
486 Initializers[i] = ConstantStruct::get(
487 GlobalStructTy,
488 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
489 ConstantInt::get(IntptrTy, SizeInBytes),
490 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
491 ConstantExpr::getPointerCast(Name, IntptrTy),
492 NULL);
493 DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
494 }
495
496 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
497 GlobalVariable *AllGlobals = new GlobalVariable(
498 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
499 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
500
501 Function *AsanRegisterGlobals = cast<Function>(M.getOrInsertFunction(
502 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
503 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
504
505 IRB.CreateCall2(AsanRegisterGlobals,
506 IRB.CreatePointerCast(AllGlobals, IntptrTy),
507 ConstantInt::get(IntptrTy, n));
508
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000509 // We also need to unregister globals at the end, e.g. when a shared library
510 // gets closed.
511 Function *AsanDtorFunction = Function::Create(
512 FunctionType::get(Type::getVoidTy(*C), false),
513 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
514 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
515 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
516 Function *AsanUnregisterGlobals = cast<Function>(M.getOrInsertFunction(
517 kAsanUnregisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
518 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
519
520 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
521 IRB.CreatePointerCast(AllGlobals, IntptrTy),
522 ConstantInt::get(IntptrTy, n));
523 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
524
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000525 DEBUG(dbgs() << M);
526 return true;
527}
528
529// virtual
530bool AddressSanitizer::runOnModule(Module &M) {
531 // Initialize the private fields. No one has accessed them before.
532 TD = getAnalysisIfAvailable<TargetData>();
533 if (!TD)
534 return false;
535 BL.reset(new BlackList(ClBlackListFile));
536
537 CurrentModule = &M;
538 C = &(M.getContext());
539 LongSize = TD->getPointerSizeInBits();
540 IntptrTy = Type::getIntNTy(*C, LongSize);
541 IntptrPtrTy = PointerType::get(IntptrTy, 0);
542
543 AsanCtorFunction = Function::Create(
544 FunctionType::get(Type::getVoidTy(*C), false),
545 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
546 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
547 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
548
549 // call __asan_init in the module ctor.
550 IRBuilder<> IRB(CtorInsertBefore);
551 AsanInitFunction = cast<Function>(
552 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
553 AsanInitFunction->setLinkage(Function::ExternalLinkage);
554 IRB.CreateCall(AsanInitFunction);
555
556 MappingOffset = LongSize == 32
557 ? kDefaultShadowOffset32 : kDefaultShadowOffset64;
558 if (ClMappingOffsetLog >= 0) {
559 if (ClMappingOffsetLog == 0) {
560 // special case
561 MappingOffset = 0;
562 } else {
563 MappingOffset = 1ULL << ClMappingOffsetLog;
564 }
565 }
566 MappingScale = kDefaultShadowScale;
567 if (ClMappingScale) {
568 MappingScale = ClMappingScale;
569 }
570 // Redzone used for stack and globals is at least 32 bytes.
571 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
572 RedzoneSize = std::max(32, (int)(1 << MappingScale));
573
574 bool Res = false;
575
576 if (ClGlobals)
577 Res |= insertGlobalRedzones(M);
578
579 // Tell the run-time the current values of mapping offset and scale.
580 GlobalValue *asan_mapping_offset =
581 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
582 ConstantInt::get(IntptrTy, MappingOffset),
583 kAsanMappingOffsetName);
584 GlobalValue *asan_mapping_scale =
585 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
586 ConstantInt::get(IntptrTy, MappingScale),
587 kAsanMappingScaleName);
588 // Read these globals, otherwise they may be optimized away.
589 IRB.CreateLoad(asan_mapping_scale, true);
590 IRB.CreateLoad(asan_mapping_offset, true);
591
592
593 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
594 if (F->isDeclaration()) continue;
595 Res |= handleFunction(M, *F);
596 }
597
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000598 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryany9b027412011-12-12 18:01:46 +0000599
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000600 return Res;
601}
602
603bool AddressSanitizer::handleFunction(Module &M, Function &F) {
604 if (BL->isIn(F)) return false;
605 if (&F == AsanCtorFunction) return false;
606
607 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
608 return false;
609 // We want to instrument every address only once per basic block
610 // (unless there are calls between uses).
611 SmallSet<Value*, 16> TempsToInstrument;
612 SmallVector<Instruction*, 16> ToInstrument;
613
614 // Fill the set of memory operations to instrument.
615 for (Function::iterator FI = F.begin(), FE = F.end();
616 FI != FE; ++FI) {
617 TempsToInstrument.clear();
618 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
619 BI != BE; ++BI) {
620 if ((isa<LoadInst>(BI) && ClInstrumentReads) ||
621 (isa<StoreInst>(BI) && ClInstrumentWrites)) {
622 Value *Addr = getLDSTOperand(BI);
623 if (ClOpt && ClOptSameTemp) {
624 if (!TempsToInstrument.insert(Addr))
625 continue; // We've seen this temp in the current BB.
626 }
627 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
628 // ok, take it.
629 } else {
630 if (isa<CallInst>(BI)) {
631 // A call inside BB.
632 TempsToInstrument.clear();
633 }
634 continue;
635 }
636 ToInstrument.push_back(BI);
637 }
638 }
639
640 // Instrument.
641 int NumInstrumented = 0;
642 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
643 Instruction *Inst = ToInstrument[i];
644 if (ClDebugMin < 0 || ClDebugMax < 0 ||
645 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
646 if (isa<StoreInst>(Inst) || isa<LoadInst>(Inst))
647 instrumentMop(Inst);
648 else
649 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
650 }
651 NumInstrumented++;
652 }
653
654 DEBUG(dbgs() << F);
655
656 bool ChangedStack = poisonStackInFunction(M, F);
657
658 // For each NSObject descendant having a +load method, this method is invoked
659 // by the ObjC runtime before any of the static constructors is called.
660 // Therefore we need to instrument such methods with a call to __asan_init
661 // at the beginning in order to initialize our runtime before any access to
662 // the shadow memory.
663 // We cannot just ignore these methods, because they may call other
664 // instrumented functions.
665 if (F.getName().find(" load]") != std::string::npos) {
666 IRBuilder<> IRB(F.begin()->begin());
667 IRB.CreateCall(AsanInitFunction);
668 }
669
670 return NumInstrumented > 0 || ChangedStack;
671}
672
673static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
674 if (ShadowRedzoneSize == 1) return PoisonByte;
675 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
676 if (ShadowRedzoneSize == 4)
677 return (PoisonByte << 24) + (PoisonByte << 16) +
678 (PoisonByte << 8) + (PoisonByte);
679 assert(0 && "ShadowRedzoneSize is either 1, 2 or 4");
680 return 0;
681}
682
683static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
684 size_t Size,
685 size_t RedzoneSize,
686 size_t ShadowGranularity,
687 uint8_t Magic) {
688 for (size_t i = 0; i < RedzoneSize;
689 i+= ShadowGranularity, Shadow++) {
690 if (i + ShadowGranularity <= Size) {
691 *Shadow = 0; // fully addressable
692 } else if (i >= Size) {
693 *Shadow = Magic; // unaddressable
694 } else {
695 *Shadow = Size - i; // first Size-i bytes are addressable
696 }
697 }
698}
699
700void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
701 IRBuilder<> IRB,
702 Value *ShadowBase, bool DoPoison) {
703 size_t ShadowRZSize = RedzoneSize >> MappingScale;
704 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
705 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
706 Type *RZPtrTy = PointerType::get(RZTy, 0);
707
708 Value *PoisonLeft = ConstantInt::get(RZTy,
709 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
710 Value *PoisonMid = ConstantInt::get(RZTy,
711 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
712 Value *PoisonRight = ConstantInt::get(RZTy,
713 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
714
715 // poison the first red zone.
716 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
717
718 // poison all other red zones.
719 uint64_t Pos = RedzoneSize;
720 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
721 AllocaInst *AI = AllocaVec[i];
722 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
723 uint64_t AlignedSize = getAlignedAllocaSize(AI);
724 assert(AlignedSize - SizeInBytes < RedzoneSize);
725 Value *Ptr = NULL;
726
727 Pos += AlignedSize;
728
729 assert(ShadowBase->getType() == IntptrTy);
730 if (SizeInBytes < AlignedSize) {
731 // Poison the partial redzone at right
732 Ptr = IRB.CreateAdd(
733 ShadowBase, ConstantInt::get(IntptrTy,
734 (Pos >> MappingScale) - ShadowRZSize));
735 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
736 uint32_t Poison = 0;
737 if (DoPoison) {
738 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
739 RedzoneSize,
740 1ULL << MappingScale,
741 kAsanStackPartialRedzoneMagic);
742 }
743 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
744 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
745 }
746
747 // Poison the full redzone at right.
748 Ptr = IRB.CreateAdd(ShadowBase,
749 ConstantInt::get(IntptrTy, Pos >> MappingScale));
750 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
751 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
752
753 Pos += RedzoneSize;
754 }
755}
756
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000757// Workaround for bug 11395: we don't want to instrument stack in functions
758// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
Kostya Serebryanyd2703de2011-11-23 02:10:54 +0000759// FIXME: remove once the bug 11395 is fixed.
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000760bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
761 if (LongSize != 32) return false;
762 CallInst *CI = dyn_cast<CallInst>(I);
763 if (!CI || !CI->isInlineAsm()) return false;
764 if (CI->getNumArgOperands() <= 5) return false;
765 // We have inline assembly with quite a few arguments.
766 return true;
767}
768
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000769// Find all static Alloca instructions and put
770// poisoned red zones around all of them.
771// Then unpoison everything back before the function returns.
772//
773// Stack poisoning does not play well with exception handling.
774// When an exception is thrown, we essentially bypass the code
775// that unpoisones the stack. This is why the run-time library has
776// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
777// stack in the interceptor. This however does not work inside the
778// actual function which catches the exception. Most likely because the
779// compiler hoists the load of the shadow value somewhere too high.
780// This causes asan to report a non-existing bug on 453.povray.
781// It sounds like an LLVM bug.
782bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
783 if (!ClStack) return false;
784 SmallVector<AllocaInst*, 16> AllocaVec;
785 SmallVector<Instruction*, 8> RetVec;
786 uint64_t TotalSize = 0;
787
788 // Filter out Alloca instructions we want (and can) handle.
789 // Collect Ret instructions.
790 for (Function::iterator FI = F.begin(), FE = F.end();
791 FI != FE; ++FI) {
792 BasicBlock &BB = *FI;
793 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
794 BI != BE; ++BI) {
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000795 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000796 if (isa<ReturnInst>(BI)) {
797 RetVec.push_back(BI);
798 continue;
799 }
800
801 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
802 if (!AI) continue;
803 if (AI->isArrayAllocation()) continue;
804 if (!AI->isStaticAlloca()) continue;
805 if (!AI->getAllocatedType()->isSized()) continue;
806 if (AI->getAlignment() > RedzoneSize) continue;
807 AllocaVec.push_back(AI);
808 uint64_t AlignedSize = getAlignedAllocaSize(AI);
809 TotalSize += AlignedSize;
810 }
811 }
812
813 if (AllocaVec.empty()) return false;
814
815 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
816
817 bool DoStackMalloc = ClUseAfterReturn
818 && LocalStackSize <= kMaxStackMallocSize;
819
820 Instruction *InsBefore = AllocaVec[0];
821 IRBuilder<> IRB(InsBefore);
822
823
824 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
825 AllocaInst *MyAlloca =
826 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
827 MyAlloca->setAlignment(RedzoneSize);
828 assert(MyAlloca->isStaticAlloca());
829 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
830 Value *LocalStackBase = OrigStackBase;
831
832 if (DoStackMalloc) {
833 Value *AsanStackMallocFunc = M.getOrInsertFunction(
834 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
835 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
836 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
837 }
838
839 // This string will be parsed by the run-time (DescribeStackAddress).
840 SmallString<2048> StackDescriptionStorage;
841 raw_svector_ostream StackDescription(StackDescriptionStorage);
842 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
843
844 uint64_t Pos = RedzoneSize;
845 // Replace Alloca instructions with base+offset.
846 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
847 AllocaInst *AI = AllocaVec[i];
848 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
849 StringRef Name = AI->getName();
850 StackDescription << Pos << " " << SizeInBytes << " "
851 << Name.size() << " " << Name << " ";
852 uint64_t AlignedSize = getAlignedAllocaSize(AI);
853 assert((AlignedSize % RedzoneSize) == 0);
854 AI->replaceAllUsesWith(
855 IRB.CreateIntToPtr(
856 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
857 AI->getType()));
858 Pos += AlignedSize + RedzoneSize;
859 }
860 assert(Pos == LocalStackSize);
861
862 // Write the Magic value and the frame description constant to the redzone.
863 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
864 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
865 BasePlus0);
866 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
867 ConstantInt::get(IntptrTy, LongSize/8));
868 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
869 Value *Description = IRB.CreatePointerCast(
870 createPrivateGlobalForString(M, StackDescription.str()),
871 IntptrTy);
872 IRB.CreateStore(Description, BasePlus1);
873
874 // Poison the stack redzones at the entry.
875 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
876 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
877
878 Value *AsanStackFreeFunc = NULL;
879 if (DoStackMalloc) {
880 AsanStackFreeFunc = M.getOrInsertFunction(
881 kAsanStackFreeName, IRB.getVoidTy(),
882 IntptrTy, IntptrTy, IntptrTy, NULL);
883 }
884
885 // Unpoison the stack before all ret instructions.
886 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
887 Instruction *Ret = RetVec[i];
888 IRBuilder<> IRBRet(Ret);
889
890 // Mark the current frame as retired.
891 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
892 BasePlus0);
893 // Unpoison the stack.
894 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
895
896 if (DoStackMalloc) {
897 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
898 ConstantInt::get(IntptrTy, LocalStackSize),
899 OrigStackBase);
900 }
901 }
902
903 if (ClDebugStack) {
904 DEBUG(dbgs() << F);
905 }
906
907 return true;
908}
909
910BlackList::BlackList(const std::string &Path) {
911 Functions = NULL;
912 const char *kFunPrefix = "fun:";
913 if (!ClBlackListFile.size()) return;
914 std::string Fun;
915
916 OwningPtr<MemoryBuffer> File;
917 if (error_code EC = MemoryBuffer::getFile(ClBlackListFile.c_str(), File)) {
Kostya Serebryanycc1d8562011-12-01 18:54:53 +0000918 report_fatal_error("Can't open blacklist file " + ClBlackListFile + ": " +
919 EC.message());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000920 }
921 MemoryBuffer *Buff = File.take();
922 const char *Data = Buff->getBufferStart();
923 size_t DataLen = Buff->getBufferSize();
924 SmallVector<StringRef, 16> Lines;
925 SplitString(StringRef(Data, DataLen), Lines, "\n\r");
926 for (size_t i = 0, numLines = Lines.size(); i < numLines; i++) {
927 if (Lines[i].startswith(kFunPrefix)) {
928 std::string ThisFunc = Lines[i].substr(strlen(kFunPrefix));
Kostya Serebryany085cb8f2011-12-13 19:34:53 +0000929 std::string ThisFuncRE;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000930 // add ThisFunc replacing * with .*
931 for (size_t j = 0, n = ThisFunc.size(); j < n; j++) {
932 if (ThisFunc[j] == '*')
Kostya Serebryany085cb8f2011-12-13 19:34:53 +0000933 ThisFuncRE += '.';
934 ThisFuncRE += ThisFunc[j];
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000935 }
Kostya Serebryany085cb8f2011-12-13 19:34:53 +0000936 // Check that the regexp is valid.
937 Regex CheckRE(ThisFuncRE);
938 std::string Error;
939 if (!CheckRE.isValid(Error))
940 report_fatal_error("malformed blacklist regex: " + ThisFunc +
941 ": " + Error);
942 // Append to the final regexp.
943 if (Fun.size())
944 Fun += "|";
945 Fun += ThisFuncRE;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000946 }
947 }
948 if (Fun.size()) {
949 Functions = new Regex(Fun);
950 }
951}
952
953bool BlackList::isIn(const Function &F) {
954 if (Functions) {
955 bool Res = Functions->match(F.getName());
956 return Res;
957 }
958 return false;
959}