blob: bf35eacd69fa04090d3b8621941a5f37d5ef8c54 [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"
Kostya Serebryanyf7b08222012-07-20 09:54:50 +000021#include "llvm/InlineAsm.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000022#include "llvm/IntrinsicInst.h"
23#include "llvm/LLVMContext.h"
24#include "llvm/Module.h"
25#include "llvm/Type.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000026#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/SmallSet.h"
29#include "llvm/ADT/SmallString.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000032#include "llvm/ADT/Triple.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/DataTypes.h"
35#include "llvm/Support/Debug.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000036#include "llvm/Support/raw_ostream.h"
37#include "llvm/Support/system_error.h"
38#include "llvm/Target/TargetData.h"
39#include "llvm/Target/TargetMachine.h"
40#include "llvm/Transforms/Instrumentation.h"
41#include "llvm/Transforms/Utils/BasicBlockUtils.h"
42#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000043
44#include <string>
45#include <algorithm>
46
47using namespace llvm;
48
49static const uint64_t kDefaultShadowScale = 3;
50static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
51static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000052static const uint64_t kDefaultShadowOffsetAndroid = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000053
54static const size_t kMaxStackMallocSize = 1 << 16; // 64K
55static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
56static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
57
58static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000059static const char *kAsanModuleDtorName = "asan.module_dtor";
60static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000061static const char *kAsanReportErrorTemplate = "__asan_report_";
62static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000063static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000064static const char *kAsanInitName = "__asan_init";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000065static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000066static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
67static const char *kAsanMappingScaleName = "__asan_mapping_scale";
68static const char *kAsanStackMallocName = "__asan_stack_malloc";
69static const char *kAsanStackFreeName = "__asan_stack_free";
70
71static const int kAsanStackLeftRedzoneMagic = 0xf1;
72static const int kAsanStackMidRedzoneMagic = 0xf2;
73static const int kAsanStackRightRedzoneMagic = 0xf3;
74static const int kAsanStackPartialRedzoneMagic = 0xf4;
75
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000076// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
77static const size_t kNumberOfAccessSizes = 5;
78
Kostya Serebryany800e03f2011-11-16 01:35:23 +000079// Command-line flags.
80
81// This flag may need to be replaced with -f[no-]asan-reads.
82static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
83 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
84static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
85 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000086static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
87 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
88 cl::Hidden, cl::init(true));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000089// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +000090// in any given BB. Normally, this should be set to unlimited (INT_MAX),
91// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
92// set it to 10000.
93static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
94 cl::init(10000),
95 cl::desc("maximal number of instructions to instrument in any given BB"),
96 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +000097// This flag may need to be replaced with -f[no]asan-stack.
98static cl::opt<bool> ClStack("asan-stack",
99 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
100// This flag may need to be replaced with -f[no]asan-use-after-return.
101static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
102 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
103// This flag may need to be replaced with -f[no]asan-globals.
104static cl::opt<bool> ClGlobals("asan-globals",
105 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
106static cl::opt<bool> ClMemIntrin("asan-memintrin",
107 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
108// This flag may need to be replaced with -fasan-blacklist.
109static cl::opt<std::string> ClBlackListFile("asan-blacklist",
110 cl::desc("File containing the list of functions to ignore "
111 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000112
113// These flags allow to change the shadow mapping.
114// The shadow mapping looks like
115// Shadow = (Mem >> scale) + (1 << offset_log)
116static cl::opt<int> ClMappingScale("asan-mapping-scale",
117 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
118static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
119 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
120
121// Optimization flags. Not user visible, used mostly for testing
122// and benchmarking the tool.
123static cl::opt<bool> ClOpt("asan-opt",
124 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
125static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
126 cl::desc("Instrument the same temp just once"), cl::Hidden,
127 cl::init(true));
128static cl::opt<bool> ClOptGlobals("asan-opt-globals",
129 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
130
131// Debug flags.
132static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
133 cl::init(0));
134static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
135 cl::Hidden, cl::init(0));
136static cl::opt<std::string> ClDebugFunc("asan-debug-func",
137 cl::Hidden, cl::desc("Debug func"));
138static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
139 cl::Hidden, cl::init(-1));
140static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
141 cl::Hidden, cl::init(-1));
142
143namespace {
144
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000145/// An object of this type is created while instrumenting every function.
146struct AsanFunctionContext {
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000147 AsanFunctionContext(Function &Function) : F(Function) { }
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000148
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000149 Function &F;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000150};
151
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000152/// AddressSanitizer: instrument the code in module to find memory bugs.
153struct AddressSanitizer : public ModulePass {
154 AddressSanitizer();
Alexander Potapenko25878042012-01-23 11:22:43 +0000155 virtual const char *getPassName() const;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000156 void instrumentMop(AsanFunctionContext &AFC, Instruction *I);
157 void instrumentAddress(AsanFunctionContext &AFC,
158 Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000159 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000160 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
161 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000162 Instruction *generateCrashCode(BasicBlock *BB, Value *Addr, Value *PC,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000163 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000164 bool instrumentMemIntrinsic(AsanFunctionContext &AFC, MemIntrinsic *MI);
165 void instrumentMemIntrinsicParam(AsanFunctionContext &AFC,
166 Instruction *OrigIns, Value *Addr,
167 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000168 Instruction *InsertBefore, bool IsWrite);
169 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
170 bool handleFunction(Module &M, Function &F);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000171 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000172 bool poisonStackInFunction(Module &M, Function &F);
173 virtual bool runOnModule(Module &M);
174 bool insertGlobalRedzones(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000175 static char ID; // Pass identification, replacement for typeid
176
177 private:
178
179 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
180 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanovd8313be2012-03-02 10:41:08 +0000181 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000182 return SizeInBytes;
183 }
184 uint64_t getAlignedSize(uint64_t SizeInBytes) {
185 return ((SizeInBytes + RedzoneSize - 1)
186 / RedzoneSize) * RedzoneSize;
187 }
188 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
189 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
190 return getAlignedSize(SizeInBytes);
191 }
192
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000193 Function *checkInterfaceFunction(Constant *FuncOrBitcast);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000194 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
195 Value *ShadowBase, bool DoPoison);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000196 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000197
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000198 LLVMContext *C;
199 TargetData *TD;
200 uint64_t MappingOffset;
201 int MappingScale;
202 size_t RedzoneSize;
203 int LongSize;
204 Type *IntptrTy;
205 Type *IntptrPtrTy;
206 Function *AsanCtorFunction;
207 Function *AsanInitFunction;
208 Instruction *CtorInsertBefore;
Kostya Serebryanya1c45042012-03-14 23:22:10 +0000209 OwningPtr<FunctionBlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000210 // This array is indexed by AccessIsWrite and log2(AccessSize).
211 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000212 InlineAsm *EmptyAsm;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000213};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000214
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000215} // namespace
216
217char AddressSanitizer::ID = 0;
218INITIALIZE_PASS(AddressSanitizer, "asan",
219 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
220 false, false)
221AddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
222ModulePass *llvm::createAddressSanitizerPass() {
223 return new AddressSanitizer();
224}
225
Alexander Potapenko25878042012-01-23 11:22:43 +0000226const char *AddressSanitizer::getPassName() const {
227 return "AddressSanitizer";
228}
229
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000230static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
231 size_t Res = CountTrailingZeros_32(TypeSize / 8);
232 assert(Res < kNumberOfAccessSizes);
233 return Res;
234}
235
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000236// Create a constant for Str so that we can pass it to the run-time lib.
237static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000238 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000239 return new GlobalVariable(M, StrConst->getType(), true,
240 GlobalValue::PrivateLinkage, StrConst, "");
241}
242
243// Split the basic block and insert an if-then code.
244// Before:
245// Head
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000246// Cmp
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000247// Tail
248// After:
249// Head
250// if (Cmp)
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000251// ThenBlock
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000252// Tail
253//
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000254// If ThenBlock is zero, a new block is created and its terminator is returned.
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000255// Otherwize 0 is returned.
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000256static BranchInst *splitBlockAndInsertIfThen(Value *Cmp,
257 BasicBlock *ThenBlock = 0) {
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000258 Instruction *SplitBefore = cast<Instruction>(Cmp)->getNextNode();
Chandler Carruthc3c8db92012-07-16 08:58:53 +0000259 BasicBlock *Head = SplitBefore->getParent();
Chandler Carruth349f14c2012-07-16 10:01:02 +0000260 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
Chandler Carruthc3c8db92012-07-16 08:58:53 +0000261 TerminatorInst *HeadOldTerm = Head->getTerminator();
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000262 BranchInst *CheckTerm = 0;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000263 if (!ThenBlock) {
264 LLVMContext &C = Head->getParent()->getParent()->getContext();
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000265 ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000266 CheckTerm = BranchInst::Create(Tail, ThenBlock);
267 }
Chandler Carruth349f14c2012-07-16 10:01:02 +0000268 BranchInst *HeadNewTerm =
269 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cmp);
270 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
Chandler Carruthc3c8db92012-07-16 08:58:53 +0000271
Chandler Carruth349f14c2012-07-16 10:01:02 +0000272 return CheckTerm;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000273}
274
275Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
276 // Shadow >> scale
277 Shadow = IRB.CreateLShr(Shadow, MappingScale);
278 if (MappingOffset == 0)
279 return Shadow;
280 // (Shadow >> scale) | offset
281 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
282 MappingOffset));
283}
284
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000285void AddressSanitizer::instrumentMemIntrinsicParam(
286 AsanFunctionContext &AFC, Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000287 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
288 // Check the first byte.
289 {
290 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000291 instrumentAddress(AFC, OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000292 }
293 // Check the last byte.
294 {
295 IRBuilder<> IRB(InsertBefore);
296 Value *SizeMinusOne = IRB.CreateSub(
297 Size, ConstantInt::get(Size->getType(), 1));
298 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
299 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
300 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000301 instrumentAddress(AFC, OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000302 }
303}
304
305// Instrument memset/memmove/memcpy
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000306bool AddressSanitizer::instrumentMemIntrinsic(AsanFunctionContext &AFC,
307 MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000308 Value *Dst = MI->getDest();
309 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000310 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000311 Value *Length = MI->getLength();
312
313 Constant *ConstLength = dyn_cast<Constant>(Length);
314 Instruction *InsertBefore = MI;
315 if (ConstLength) {
316 if (ConstLength->isNullValue()) return false;
317 } else {
318 // The size is not a constant so it could be zero -- check at run-time.
319 IRBuilder<> IRB(InsertBefore);
320
321 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000322 Constant::getNullValue(Length->getType()));
323 InsertBefore = splitBlockAndInsertIfThen(Cmp);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000324 }
325
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000326 instrumentMemIntrinsicParam(AFC, MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000327 if (Src)
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000328 instrumentMemIntrinsicParam(AFC, MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000329 return true;
330}
331
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000332// If I is an interesting memory access, return the PointerOperand
333// and set IsWrite. Otherwise return NULL.
334static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000335 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000336 if (!ClInstrumentReads) return NULL;
337 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000338 return LI->getPointerOperand();
339 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000340 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
341 if (!ClInstrumentWrites) return NULL;
342 *IsWrite = true;
343 return SI->getPointerOperand();
344 }
345 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
346 if (!ClInstrumentAtomics) return NULL;
347 *IsWrite = true;
348 return RMW->getPointerOperand();
349 }
350 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
351 if (!ClInstrumentAtomics) return NULL;
352 *IsWrite = true;
353 return XCHG->getPointerOperand();
354 }
355 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000356}
357
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000358void AddressSanitizer::instrumentMop(AsanFunctionContext &AFC, Instruction *I) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000359 bool IsWrite;
360 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
361 assert(Addr);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000362 if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
363 // We are accessing a global scalar variable. Nothing to catch here.
364 return;
365 }
366 Type *OrigPtrTy = Addr->getType();
367 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
368
369 assert(OrigTy->isSized());
370 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
371
372 if (TypeSize != 8 && TypeSize != 16 &&
373 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
374 // Ignore all unusual sizes.
375 return;
376 }
377
378 IRBuilder<> IRB(I);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000379 instrumentAddress(AFC, I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000380}
381
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000382// Validate the result of Module::getOrInsertFunction called for an interface
383// function of AddressSanitizer. If the instrumented module defines a function
384// with the same name, their prototypes must match, otherwise
385// getOrInsertFunction returns a bitcast.
386Function *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
387 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
388 FuncOrBitcast->dump();
389 report_fatal_error("trying to redefine an AddressSanitizer "
390 "interface function");
391}
392
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000393Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000394 BasicBlock *BB, Value *Addr, Value *PC,
395 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000396 IRBuilder<> IRB(BB->getFirstNonPHI());
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000397 CallInst *Call;
398 if (PC)
399 Call = IRB.CreateCall2(AsanErrorCallback[IsWrite][AccessSizeIndex],
400 Addr, PC);
401 else
402 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000403 // We don't do Call->setDoesNotReturn() because the BB already has
404 // UnreachableInst at the end.
405 // This EmptyAsm is required to avoid callback merge.
406 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000407 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000408}
409
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000410Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000411 Value *ShadowValue,
412 uint32_t TypeSize) {
413 size_t Granularity = 1 << MappingScale;
414 // Addr & (Granularity - 1)
415 Value *LastAccessedByte = IRB.CreateAnd(
416 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
417 // (Addr & (Granularity - 1)) + size - 1
418 if (TypeSize / 8 > 1)
419 LastAccessedByte = IRB.CreateAdd(
420 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
421 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
422 LastAccessedByte = IRB.CreateIntCast(
423 LastAccessedByte, IRB.getInt8Ty(), false);
424 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
425 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
426}
427
428void AddressSanitizer::instrumentAddress(AsanFunctionContext &AFC,
429 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000430 IRBuilder<> &IRB, Value *Addr,
431 uint32_t TypeSize, bool IsWrite) {
432 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
433
434 Type *ShadowTy = IntegerType::get(
435 *C, std::max(8U, TypeSize >> MappingScale));
436 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
437 Value *ShadowPtr = memToShadow(AddrLong, IRB);
438 Value *CmpVal = Constant::getNullValue(ShadowTy);
439 Value *ShadowValue = IRB.CreateLoad(
440 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
441
442 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
443
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000444 BasicBlock *CrashBlock = BasicBlock::Create(*C, "crash_bb", &AFC.F);
445 new UnreachableInst(*C, CrashBlock);
446 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
447 Instruction *Crash =
448 generateCrashCode(CrashBlock, AddrLong, 0, IsWrite, AccessSizeIndex);
449 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000450
451 size_t Granularity = 1 << MappingScale;
452 if (TypeSize < 8 * Granularity) {
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000453 BranchInst *CheckTerm = splitBlockAndInsertIfThen(Cmp);
454 assert(CheckTerm->isUnconditional());
455 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000456 IRB.SetInsertPoint(CheckTerm);
457 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000458 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
459 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000460 } else {
461 splitBlockAndInsertIfThen(Cmp, CrashBlock);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000462 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000463}
464
465// This function replaces all global variables with new variables that have
466// trailing redzones. It also creates a function that poisons
467// redzones and inserts this function into llvm.global_ctors.
468bool AddressSanitizer::insertGlobalRedzones(Module &M) {
469 SmallVector<GlobalVariable *, 16> GlobalsToChange;
470
471 for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
472 E = M.getGlobalList().end(); G != E; ++G) {
473 Type *Ty = cast<PointerType>(G->getType())->getElementType();
474 DEBUG(dbgs() << "GLOBAL: " << *G);
475
476 if (!Ty->isSized()) continue;
477 if (!G->hasInitializer()) continue;
Kostya Serebryany7cf2a042011-11-17 23:14:59 +0000478 // Touch only those globals that will not be defined in other modules.
479 // Don't handle ODR type linkages since other modules may be built w/o asan.
Kostya Serebryany2e7fb2f2011-11-17 23:37:53 +0000480 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
481 G->getLinkage() != GlobalVariable::PrivateLinkage &&
482 G->getLinkage() != GlobalVariable::InternalLinkage)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000483 continue;
Kostya Serebryanyd2703de2011-11-23 02:10:54 +0000484 // Two problems with thread-locals:
485 // - The address of the main thread's copy can't be computed at link-time.
486 // - Need to poison all copies, not just the main thread's one.
487 if (G->isThreadLocal())
488 continue;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000489 // For now, just ignore this Alloca if the alignment is large.
490 if (G->getAlignment() > RedzoneSize) continue;
491
492 // Ignore all the globals with the names starting with "\01L_OBJC_".
493 // Many of those are put into the .cstring section. The linker compresses
494 // that section by removing the spare \0s after the string terminator, so
495 // our redzones get broken.
496 if ((G->getName().find("\01L_OBJC_") == 0) ||
497 (G->getName().find("\01l_OBJC_") == 0)) {
498 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
499 continue;
500 }
501
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000502 if (G->hasSection()) {
503 StringRef Section(G->getSection());
Alexander Potapenko8375bc92012-01-30 10:40:22 +0000504 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
505 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
506 // them.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000507 if ((Section.find("__OBJC,") == 0) ||
508 (Section.find("__DATA, __objc_") == 0)) {
509 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
510 continue;
511 }
Alexander Potapenko8375bc92012-01-30 10:40:22 +0000512 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
513 // Constant CFString instances are compiled in the following way:
514 // -- the string buffer is emitted into
515 // __TEXT,__cstring,cstring_literals
516 // -- the constant NSConstantString structure referencing that buffer
517 // is placed into __DATA,__cfstring
518 // Therefore there's no point in placing redzones into __DATA,__cfstring.
519 // Moreover, it causes the linker to crash on OS X 10.7
520 if (Section.find("__DATA,__cfstring") == 0) {
521 DEBUG(dbgs() << "Ignoring CFString: " << *G);
522 continue;
523 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000524 }
525
526 GlobalsToChange.push_back(G);
527 }
528
529 size_t n = GlobalsToChange.size();
530 if (n == 0) return false;
531
532 // A global is described by a structure
533 // size_t beg;
534 // size_t size;
535 // size_t size_with_redzone;
536 // const char *name;
537 // We initialize an array of such structures and pass it to a run-time call.
538 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
539 IntptrTy, IntptrTy, NULL);
540 SmallVector<Constant *, 16> Initializers(n);
541
542 IRBuilder<> IRB(CtorInsertBefore);
543
544 for (size_t i = 0; i < n; i++) {
545 GlobalVariable *G = GlobalsToChange[i];
546 PointerType *PtrTy = cast<PointerType>(G->getType());
547 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000548 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000549 uint64_t RightRedzoneSize = RedzoneSize +
550 (RedzoneSize - (SizeInBytes % RedzoneSize));
551 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
552
553 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
554 Constant *NewInitializer = ConstantStruct::get(
555 NewTy, G->getInitializer(),
556 Constant::getNullValue(RightRedZoneTy), NULL);
557
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000558 SmallString<2048> DescriptionOfGlobal = G->getName();
559 DescriptionOfGlobal += " (";
560 DescriptionOfGlobal += M.getModuleIdentifier();
561 DescriptionOfGlobal += ")";
562 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000563
564 // Create a new global variable with enough space for a redzone.
565 GlobalVariable *NewGlobal = new GlobalVariable(
566 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000567 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000568 NewGlobal->copyAttributesFrom(G);
569 NewGlobal->setAlignment(RedzoneSize);
570
571 Value *Indices2[2];
572 Indices2[0] = IRB.getInt32(0);
573 Indices2[1] = IRB.getInt32(0);
574
575 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000576 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000577 NewGlobal->takeName(G);
578 G->eraseFromParent();
579
580 Initializers[i] = ConstantStruct::get(
581 GlobalStructTy,
582 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
583 ConstantInt::get(IntptrTy, SizeInBytes),
584 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
585 ConstantExpr::getPointerCast(Name, IntptrTy),
586 NULL);
587 DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
588 }
589
590 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
591 GlobalVariable *AllGlobals = new GlobalVariable(
592 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
593 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
594
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000595 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000596 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
597 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
598
599 IRB.CreateCall2(AsanRegisterGlobals,
600 IRB.CreatePointerCast(AllGlobals, IntptrTy),
601 ConstantInt::get(IntptrTy, n));
602
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000603 // We also need to unregister globals at the end, e.g. when a shared library
604 // gets closed.
605 Function *AsanDtorFunction = Function::Create(
606 FunctionType::get(Type::getVoidTy(*C), false),
607 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
608 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
609 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000610 Function *AsanUnregisterGlobals =
611 checkInterfaceFunction(M.getOrInsertFunction(
612 kAsanUnregisterGlobalsName,
613 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000614 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
615
616 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
617 IRB.CreatePointerCast(AllGlobals, IntptrTy),
618 ConstantInt::get(IntptrTy, n));
619 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
620
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000621 DEBUG(dbgs() << M);
622 return true;
623}
624
625// virtual
626bool AddressSanitizer::runOnModule(Module &M) {
627 // Initialize the private fields. No one has accessed them before.
628 TD = getAnalysisIfAvailable<TargetData>();
629 if (!TD)
630 return false;
Kostya Serebryanya1c45042012-03-14 23:22:10 +0000631 BL.reset(new FunctionBlackList(ClBlackListFile));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000632
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000633 C = &(M.getContext());
634 LongSize = TD->getPointerSizeInBits();
635 IntptrTy = Type::getIntNTy(*C, LongSize);
636 IntptrPtrTy = PointerType::get(IntptrTy, 0);
637
638 AsanCtorFunction = Function::Create(
639 FunctionType::get(Type::getVoidTy(*C), false),
640 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
641 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
642 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
643
644 // call __asan_init in the module ctor.
645 IRBuilder<> IRB(CtorInsertBefore);
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000646 AsanInitFunction = checkInterfaceFunction(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000647 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
648 AsanInitFunction->setLinkage(Function::ExternalLinkage);
649 IRB.CreateCall(AsanInitFunction);
650
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000651 // Create __asan_report* callbacks.
652 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
653 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
654 AccessSizeIndex++) {
655 // IsWrite and TypeSize are encoded in the function name.
656 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
657 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000658 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000659 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>(
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000660 M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000661 }
662 }
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000663 // We insert an empty inline asm after __asan_report* to avoid callback merge.
664 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
665 StringRef(""), StringRef(""),
666 /*hasSideEffects=*/true);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000667
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000668 llvm::Triple targetTriple(M.getTargetTriple());
669 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::ANDROIDEABI;
670
671 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
672 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000673 if (ClMappingOffsetLog >= 0) {
674 if (ClMappingOffsetLog == 0) {
675 // special case
676 MappingOffset = 0;
677 } else {
678 MappingOffset = 1ULL << ClMappingOffsetLog;
679 }
680 }
681 MappingScale = kDefaultShadowScale;
682 if (ClMappingScale) {
683 MappingScale = ClMappingScale;
684 }
685 // Redzone used for stack and globals is at least 32 bytes.
686 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
687 RedzoneSize = std::max(32, (int)(1 << MappingScale));
688
689 bool Res = false;
690
691 if (ClGlobals)
692 Res |= insertGlobalRedzones(M);
693
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000694 if (ClMappingOffsetLog >= 0) {
695 // Tell the run-time the current values of mapping offset and scale.
696 GlobalValue *asan_mapping_offset =
697 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
698 ConstantInt::get(IntptrTy, MappingOffset),
699 kAsanMappingOffsetName);
700 // Read the global, otherwise it may be optimized away.
701 IRB.CreateLoad(asan_mapping_offset, true);
702 }
703 if (ClMappingScale) {
704 GlobalValue *asan_mapping_scale =
705 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
706 ConstantInt::get(IntptrTy, MappingScale),
707 kAsanMappingScaleName);
708 // Read the global, otherwise it may be optimized away.
709 IRB.CreateLoad(asan_mapping_scale, true);
710 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000711
712
713 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
714 if (F->isDeclaration()) continue;
715 Res |= handleFunction(M, *F);
716 }
717
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000718 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryany9b027412011-12-12 18:01:46 +0000719
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000720 return Res;
721}
722
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000723bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
724 // For each NSObject descendant having a +load method, this method is invoked
725 // by the ObjC runtime before any of the static constructors is called.
726 // Therefore we need to instrument such methods with a call to __asan_init
727 // at the beginning in order to initialize our runtime before any access to
728 // the shadow memory.
729 // We cannot just ignore these methods, because they may call other
730 // instrumented functions.
731 if (F.getName().find(" load]") != std::string::npos) {
732 IRBuilder<> IRB(F.begin()->begin());
733 IRB.CreateCall(AsanInitFunction);
734 return true;
735 }
736 return false;
737}
738
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000739bool AddressSanitizer::handleFunction(Module &M, Function &F) {
740 if (BL->isIn(F)) return false;
741 if (&F == AsanCtorFunction) return false;
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000742
743 // If needed, insert __asan_init before checking for AddressSafety attr.
744 maybeInsertAsanInitAtFunctionEntry(F);
745
Kostya Serebryany0307b9a2012-01-24 19:34:43 +0000746 if (!F.hasFnAttr(Attribute::AddressSafety)) return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000747
748 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
749 return false;
750 // We want to instrument every address only once per basic block
751 // (unless there are calls between uses).
752 SmallSet<Value*, 16> TempsToInstrument;
753 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000754 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000755 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000756
757 // Fill the set of memory operations to instrument.
758 for (Function::iterator FI = F.begin(), FE = F.end();
759 FI != FE; ++FI) {
760 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000761 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000762 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
763 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +0000764 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000765 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000766 if (ClOpt && ClOptSameTemp) {
767 if (!TempsToInstrument.insert(Addr))
768 continue; // We've seen this temp in the current BB.
769 }
770 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
771 // ok, take it.
772 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000773 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000774 // A call inside BB.
775 TempsToInstrument.clear();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000776 if (CI->doesNotReturn()) {
777 NoReturnCalls.push_back(CI);
778 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000779 }
780 continue;
781 }
782 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000783 NumInsnsPerBB++;
784 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
785 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000786 }
787 }
788
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000789 AsanFunctionContext AFC(F);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000790
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000791 // Instrument.
792 int NumInstrumented = 0;
793 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
794 Instruction *Inst = ToInstrument[i];
795 if (ClDebugMin < 0 || ClDebugMax < 0 ||
796 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000797 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000798 instrumentMop(AFC, Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000799 else
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000800 instrumentMemIntrinsic(AFC, cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000801 }
802 NumInstrumented++;
803 }
804
805 DEBUG(dbgs() << F);
806
807 bool ChangedStack = poisonStackInFunction(M, F);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000808
809 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
810 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
811 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
812 Instruction *CI = NoReturnCalls[i];
813 IRBuilder<> IRB(CI);
814 IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
815 IRB.getVoidTy(), NULL));
816 }
817
818 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000819}
820
821static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
822 if (ShadowRedzoneSize == 1) return PoisonByte;
823 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
824 if (ShadowRedzoneSize == 4)
825 return (PoisonByte << 24) + (PoisonByte << 16) +
826 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +0000827 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000828}
829
830static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
831 size_t Size,
832 size_t RedzoneSize,
833 size_t ShadowGranularity,
834 uint8_t Magic) {
835 for (size_t i = 0; i < RedzoneSize;
836 i+= ShadowGranularity, Shadow++) {
837 if (i + ShadowGranularity <= Size) {
838 *Shadow = 0; // fully addressable
839 } else if (i >= Size) {
840 *Shadow = Magic; // unaddressable
841 } else {
842 *Shadow = Size - i; // first Size-i bytes are addressable
843 }
844 }
845}
846
847void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
848 IRBuilder<> IRB,
849 Value *ShadowBase, bool DoPoison) {
850 size_t ShadowRZSize = RedzoneSize >> MappingScale;
851 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
852 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
853 Type *RZPtrTy = PointerType::get(RZTy, 0);
854
855 Value *PoisonLeft = ConstantInt::get(RZTy,
856 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
857 Value *PoisonMid = ConstantInt::get(RZTy,
858 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
859 Value *PoisonRight = ConstantInt::get(RZTy,
860 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
861
862 // poison the first red zone.
863 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
864
865 // poison all other red zones.
866 uint64_t Pos = RedzoneSize;
867 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
868 AllocaInst *AI = AllocaVec[i];
869 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
870 uint64_t AlignedSize = getAlignedAllocaSize(AI);
871 assert(AlignedSize - SizeInBytes < RedzoneSize);
872 Value *Ptr = NULL;
873
874 Pos += AlignedSize;
875
876 assert(ShadowBase->getType() == IntptrTy);
877 if (SizeInBytes < AlignedSize) {
878 // Poison the partial redzone at right
879 Ptr = IRB.CreateAdd(
880 ShadowBase, ConstantInt::get(IntptrTy,
881 (Pos >> MappingScale) - ShadowRZSize));
882 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
883 uint32_t Poison = 0;
884 if (DoPoison) {
885 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
886 RedzoneSize,
887 1ULL << MappingScale,
888 kAsanStackPartialRedzoneMagic);
889 }
890 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
891 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
892 }
893
894 // Poison the full redzone at right.
895 Ptr = IRB.CreateAdd(ShadowBase,
896 ConstantInt::get(IntptrTy, Pos >> MappingScale));
897 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
898 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
899
900 Pos += RedzoneSize;
901 }
902}
903
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000904// Workaround for bug 11395: we don't want to instrument stack in functions
905// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
Kostya Serebryanyd2703de2011-11-23 02:10:54 +0000906// FIXME: remove once the bug 11395 is fixed.
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000907bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
908 if (LongSize != 32) return false;
909 CallInst *CI = dyn_cast<CallInst>(I);
910 if (!CI || !CI->isInlineAsm()) return false;
911 if (CI->getNumArgOperands() <= 5) return false;
912 // We have inline assembly with quite a few arguments.
913 return true;
914}
915
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000916// Find all static Alloca instructions and put
917// poisoned red zones around all of them.
918// Then unpoison everything back before the function returns.
919//
920// Stack poisoning does not play well with exception handling.
921// When an exception is thrown, we essentially bypass the code
922// that unpoisones the stack. This is why the run-time library has
923// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
924// stack in the interceptor. This however does not work inside the
925// actual function which catches the exception. Most likely because the
926// compiler hoists the load of the shadow value somewhere too high.
927// This causes asan to report a non-existing bug on 453.povray.
928// It sounds like an LLVM bug.
929bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
930 if (!ClStack) return false;
931 SmallVector<AllocaInst*, 16> AllocaVec;
932 SmallVector<Instruction*, 8> RetVec;
933 uint64_t TotalSize = 0;
934
935 // Filter out Alloca instructions we want (and can) handle.
936 // Collect Ret instructions.
937 for (Function::iterator FI = F.begin(), FE = F.end();
938 FI != FE; ++FI) {
939 BasicBlock &BB = *FI;
940 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
941 BI != BE; ++BI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000942 if (isa<ReturnInst>(BI)) {
943 RetVec.push_back(BI);
944 continue;
945 }
946
947 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
948 if (!AI) continue;
949 if (AI->isArrayAllocation()) continue;
950 if (!AI->isStaticAlloca()) continue;
951 if (!AI->getAllocatedType()->isSized()) continue;
952 if (AI->getAlignment() > RedzoneSize) continue;
953 AllocaVec.push_back(AI);
954 uint64_t AlignedSize = getAlignedAllocaSize(AI);
955 TotalSize += AlignedSize;
956 }
957 }
958
959 if (AllocaVec.empty()) return false;
960
961 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
962
963 bool DoStackMalloc = ClUseAfterReturn
964 && LocalStackSize <= kMaxStackMallocSize;
965
966 Instruction *InsBefore = AllocaVec[0];
967 IRBuilder<> IRB(InsBefore);
968
969
970 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
971 AllocaInst *MyAlloca =
972 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
973 MyAlloca->setAlignment(RedzoneSize);
974 assert(MyAlloca->isStaticAlloca());
975 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
976 Value *LocalStackBase = OrigStackBase;
977
978 if (DoStackMalloc) {
979 Value *AsanStackMallocFunc = M.getOrInsertFunction(
980 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
981 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
982 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
983 }
984
985 // This string will be parsed by the run-time (DescribeStackAddress).
986 SmallString<2048> StackDescriptionStorage;
987 raw_svector_ostream StackDescription(StackDescriptionStorage);
988 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
989
990 uint64_t Pos = RedzoneSize;
991 // Replace Alloca instructions with base+offset.
992 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
993 AllocaInst *AI = AllocaVec[i];
994 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
995 StringRef Name = AI->getName();
996 StackDescription << Pos << " " << SizeInBytes << " "
997 << Name.size() << " " << Name << " ";
998 uint64_t AlignedSize = getAlignedAllocaSize(AI);
999 assert((AlignedSize % RedzoneSize) == 0);
1000 AI->replaceAllUsesWith(
1001 IRB.CreateIntToPtr(
1002 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1003 AI->getType()));
1004 Pos += AlignedSize + RedzoneSize;
1005 }
1006 assert(Pos == LocalStackSize);
1007
1008 // Write the Magic value and the frame description constant to the redzone.
1009 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1010 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1011 BasePlus0);
1012 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1013 ConstantInt::get(IntptrTy, LongSize/8));
1014 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1015 Value *Description = IRB.CreatePointerCast(
1016 createPrivateGlobalForString(M, StackDescription.str()),
1017 IntptrTy);
1018 IRB.CreateStore(Description, BasePlus1);
1019
1020 // Poison the stack redzones at the entry.
1021 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1022 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1023
1024 Value *AsanStackFreeFunc = NULL;
1025 if (DoStackMalloc) {
1026 AsanStackFreeFunc = M.getOrInsertFunction(
1027 kAsanStackFreeName, IRB.getVoidTy(),
1028 IntptrTy, IntptrTy, IntptrTy, NULL);
1029 }
1030
1031 // Unpoison the stack before all ret instructions.
1032 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1033 Instruction *Ret = RetVec[i];
1034 IRBuilder<> IRBRet(Ret);
1035
1036 // Mark the current frame as retired.
1037 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1038 BasePlus0);
1039 // Unpoison the stack.
1040 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1041
1042 if (DoStackMalloc) {
1043 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1044 ConstantInt::get(IntptrTy, LocalStackSize),
1045 OrigStackBase);
1046 }
1047 }
1048
1049 if (ClDebugStack) {
1050 DEBUG(dbgs() << F);
1051 }
1052
1053 return true;
1054}