blob: 3d5424951c1857138723e580afbf6a1d3c29189c [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 Serebryanyebd64542012-08-14 14:04:51 +0000162 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
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 Serebryanyebd64542012-08-14 14:04:51 +0000254// ThenBlock block is created and its terminator is returned.
255// If Unreachable, ThenBlock is terminated with UnreachableInst, otherwise
256// it is terminated with BranchInst to Tail.
257static TerminatorInst *splitBlockAndInsertIfThen(Value *Cmp, bool Unreachable) {
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 Serebryanyebd64542012-08-14 14:04:51 +0000262 LLVMContext &C = Head->getParent()->getParent()->getContext();
263 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
264 TerminatorInst *CheckTerm;
265 if (Unreachable)
266 CheckTerm = new UnreachableInst(C, ThenBlock);
267 else
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000268 CheckTerm = BranchInst::Create(Tail, ThenBlock);
Chandler Carruth349f14c2012-07-16 10:01:02 +0000269 BranchInst *HeadNewTerm =
270 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cmp);
271 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
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()));
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000323 InsertBefore = splitBlockAndInsertIfThen(Cmp, false);
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 Serebryanyebd64542012-08-14 14:04:51 +0000394 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000395 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000396 IRBuilder<> IRB(InsertBefore);
397 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
398 Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000399 // We don't do Call->setDoesNotReturn() because the BB already has
400 // UnreachableInst at the end.
401 // This EmptyAsm is required to avoid callback merge.
402 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000403 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000404}
405
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000406Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000407 Value *ShadowValue,
408 uint32_t TypeSize) {
409 size_t Granularity = 1 << MappingScale;
410 // Addr & (Granularity - 1)
411 Value *LastAccessedByte = IRB.CreateAnd(
412 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
413 // (Addr & (Granularity - 1)) + size - 1
414 if (TypeSize / 8 > 1)
415 LastAccessedByte = IRB.CreateAdd(
416 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
417 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
418 LastAccessedByte = IRB.CreateIntCast(
419 LastAccessedByte, IRB.getInt8Ty(), false);
420 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
421 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
422}
423
424void AddressSanitizer::instrumentAddress(AsanFunctionContext &AFC,
425 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000426 IRBuilder<> &IRB, Value *Addr,
427 uint32_t TypeSize, bool IsWrite) {
428 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
429
430 Type *ShadowTy = IntegerType::get(
431 *C, std::max(8U, TypeSize >> MappingScale));
432 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
433 Value *ShadowPtr = memToShadow(AddrLong, IRB);
434 Value *CmpVal = Constant::getNullValue(ShadowTy);
435 Value *ShadowValue = IRB.CreateLoad(
436 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
437
438 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000439 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000440 size_t Granularity = 1 << MappingScale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000441 TerminatorInst *CrashTerm = 0;
442
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000443 if (TypeSize < 8 * Granularity) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000444 TerminatorInst *CheckTerm = splitBlockAndInsertIfThen(Cmp, false);
445 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000446 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000447 IRB.SetInsertPoint(CheckTerm);
448 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000449 BasicBlock *CrashBlock = BasicBlock::Create(*C, "", &AFC.F, NextBB);
450 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000451 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
452 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000453 } else {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000454 CrashTerm = splitBlockAndInsertIfThen(Cmp, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000455 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000456
457 Instruction *Crash =
458 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
459 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000460}
461
462// This function replaces all global variables with new variables that have
463// trailing redzones. It also creates a function that poisons
464// redzones and inserts this function into llvm.global_ctors.
465bool AddressSanitizer::insertGlobalRedzones(Module &M) {
466 SmallVector<GlobalVariable *, 16> GlobalsToChange;
467
468 for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
469 E = M.getGlobalList().end(); G != E; ++G) {
470 Type *Ty = cast<PointerType>(G->getType())->getElementType();
471 DEBUG(dbgs() << "GLOBAL: " << *G);
472
473 if (!Ty->isSized()) continue;
474 if (!G->hasInitializer()) continue;
Kostya Serebryany7cf2a042011-11-17 23:14:59 +0000475 // Touch only those globals that will not be defined in other modules.
476 // Don't handle ODR type linkages since other modules may be built w/o asan.
Kostya Serebryany2e7fb2f2011-11-17 23:37:53 +0000477 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
478 G->getLinkage() != GlobalVariable::PrivateLinkage &&
479 G->getLinkage() != GlobalVariable::InternalLinkage)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000480 continue;
Kostya Serebryanyd2703de2011-11-23 02:10:54 +0000481 // Two problems with thread-locals:
482 // - The address of the main thread's copy can't be computed at link-time.
483 // - Need to poison all copies, not just the main thread's one.
484 if (G->isThreadLocal())
485 continue;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000486 // For now, just ignore this Alloca if the alignment is large.
487 if (G->getAlignment() > RedzoneSize) continue;
488
489 // Ignore all the globals with the names starting with "\01L_OBJC_".
490 // Many of those are put into the .cstring section. The linker compresses
491 // that section by removing the spare \0s after the string terminator, so
492 // our redzones get broken.
493 if ((G->getName().find("\01L_OBJC_") == 0) ||
494 (G->getName().find("\01l_OBJC_") == 0)) {
495 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
496 continue;
497 }
498
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000499 if (G->hasSection()) {
500 StringRef Section(G->getSection());
Alexander Potapenko8375bc92012-01-30 10:40:22 +0000501 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
502 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
503 // them.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000504 if ((Section.find("__OBJC,") == 0) ||
505 (Section.find("__DATA, __objc_") == 0)) {
506 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
507 continue;
508 }
Alexander Potapenko8375bc92012-01-30 10:40:22 +0000509 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
510 // Constant CFString instances are compiled in the following way:
511 // -- the string buffer is emitted into
512 // __TEXT,__cstring,cstring_literals
513 // -- the constant NSConstantString structure referencing that buffer
514 // is placed into __DATA,__cfstring
515 // Therefore there's no point in placing redzones into __DATA,__cfstring.
516 // Moreover, it causes the linker to crash on OS X 10.7
517 if (Section.find("__DATA,__cfstring") == 0) {
518 DEBUG(dbgs() << "Ignoring CFString: " << *G);
519 continue;
520 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000521 }
522
523 GlobalsToChange.push_back(G);
524 }
525
526 size_t n = GlobalsToChange.size();
527 if (n == 0) return false;
528
529 // A global is described by a structure
530 // size_t beg;
531 // size_t size;
532 // size_t size_with_redzone;
533 // const char *name;
534 // We initialize an array of such structures and pass it to a run-time call.
535 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
536 IntptrTy, IntptrTy, NULL);
537 SmallVector<Constant *, 16> Initializers(n);
538
539 IRBuilder<> IRB(CtorInsertBefore);
540
541 for (size_t i = 0; i < n; i++) {
542 GlobalVariable *G = GlobalsToChange[i];
543 PointerType *PtrTy = cast<PointerType>(G->getType());
544 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000545 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000546 uint64_t RightRedzoneSize = RedzoneSize +
547 (RedzoneSize - (SizeInBytes % RedzoneSize));
548 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
549
550 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
551 Constant *NewInitializer = ConstantStruct::get(
552 NewTy, G->getInitializer(),
553 Constant::getNullValue(RightRedZoneTy), NULL);
554
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000555 SmallString<2048> DescriptionOfGlobal = G->getName();
556 DescriptionOfGlobal += " (";
557 DescriptionOfGlobal += M.getModuleIdentifier();
558 DescriptionOfGlobal += ")";
559 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000560
561 // Create a new global variable with enough space for a redzone.
562 GlobalVariable *NewGlobal = new GlobalVariable(
563 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000564 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000565 NewGlobal->copyAttributesFrom(G);
566 NewGlobal->setAlignment(RedzoneSize);
567
568 Value *Indices2[2];
569 Indices2[0] = IRB.getInt32(0);
570 Indices2[1] = IRB.getInt32(0);
571
572 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000573 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000574 NewGlobal->takeName(G);
575 G->eraseFromParent();
576
577 Initializers[i] = ConstantStruct::get(
578 GlobalStructTy,
579 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
580 ConstantInt::get(IntptrTy, SizeInBytes),
581 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
582 ConstantExpr::getPointerCast(Name, IntptrTy),
583 NULL);
584 DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
585 }
586
587 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
588 GlobalVariable *AllGlobals = new GlobalVariable(
589 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
590 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
591
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000592 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000593 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
594 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
595
596 IRB.CreateCall2(AsanRegisterGlobals,
597 IRB.CreatePointerCast(AllGlobals, IntptrTy),
598 ConstantInt::get(IntptrTy, n));
599
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000600 // We also need to unregister globals at the end, e.g. when a shared library
601 // gets closed.
602 Function *AsanDtorFunction = Function::Create(
603 FunctionType::get(Type::getVoidTy(*C), false),
604 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
605 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
606 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000607 Function *AsanUnregisterGlobals =
608 checkInterfaceFunction(M.getOrInsertFunction(
609 kAsanUnregisterGlobalsName,
610 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000611 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
612
613 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
614 IRB.CreatePointerCast(AllGlobals, IntptrTy),
615 ConstantInt::get(IntptrTy, n));
616 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
617
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000618 DEBUG(dbgs() << M);
619 return true;
620}
621
622// virtual
623bool AddressSanitizer::runOnModule(Module &M) {
624 // Initialize the private fields. No one has accessed them before.
625 TD = getAnalysisIfAvailable<TargetData>();
626 if (!TD)
627 return false;
Kostya Serebryanya1c45042012-03-14 23:22:10 +0000628 BL.reset(new FunctionBlackList(ClBlackListFile));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000629
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000630 C = &(M.getContext());
631 LongSize = TD->getPointerSizeInBits();
632 IntptrTy = Type::getIntNTy(*C, LongSize);
633 IntptrPtrTy = PointerType::get(IntptrTy, 0);
634
635 AsanCtorFunction = Function::Create(
636 FunctionType::get(Type::getVoidTy(*C), false),
637 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
638 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
639 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
640
641 // call __asan_init in the module ctor.
642 IRBuilder<> IRB(CtorInsertBefore);
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000643 AsanInitFunction = checkInterfaceFunction(
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000644 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
645 AsanInitFunction->setLinkage(Function::ExternalLinkage);
646 IRB.CreateCall(AsanInitFunction);
647
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000648 // Create __asan_report* callbacks.
649 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
650 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
651 AccessSizeIndex++) {
652 // IsWrite and TypeSize are encoded in the function name.
653 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
654 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000655 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000656 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>(
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000657 M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000658 }
659 }
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000660 // We insert an empty inline asm after __asan_report* to avoid callback merge.
661 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
662 StringRef(""), StringRef(""),
663 /*hasSideEffects=*/true);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000664
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000665 llvm::Triple targetTriple(M.getTargetTriple());
666 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::ANDROIDEABI;
667
668 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
669 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000670 if (ClMappingOffsetLog >= 0) {
671 if (ClMappingOffsetLog == 0) {
672 // special case
673 MappingOffset = 0;
674 } else {
675 MappingOffset = 1ULL << ClMappingOffsetLog;
676 }
677 }
678 MappingScale = kDefaultShadowScale;
679 if (ClMappingScale) {
680 MappingScale = ClMappingScale;
681 }
682 // Redzone used for stack and globals is at least 32 bytes.
683 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
684 RedzoneSize = std::max(32, (int)(1 << MappingScale));
685
686 bool Res = false;
687
688 if (ClGlobals)
689 Res |= insertGlobalRedzones(M);
690
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000691 if (ClMappingOffsetLog >= 0) {
692 // Tell the run-time the current values of mapping offset and scale.
693 GlobalValue *asan_mapping_offset =
694 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
695 ConstantInt::get(IntptrTy, MappingOffset),
696 kAsanMappingOffsetName);
697 // Read the global, otherwise it may be optimized away.
698 IRB.CreateLoad(asan_mapping_offset, true);
699 }
700 if (ClMappingScale) {
701 GlobalValue *asan_mapping_scale =
702 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
703 ConstantInt::get(IntptrTy, MappingScale),
704 kAsanMappingScaleName);
705 // Read the global, otherwise it may be optimized away.
706 IRB.CreateLoad(asan_mapping_scale, true);
707 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000708
709
710 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
711 if (F->isDeclaration()) continue;
712 Res |= handleFunction(M, *F);
713 }
714
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000715 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryany9b027412011-12-12 18:01:46 +0000716
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000717 return Res;
718}
719
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000720bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
721 // For each NSObject descendant having a +load method, this method is invoked
722 // by the ObjC runtime before any of the static constructors is called.
723 // Therefore we need to instrument such methods with a call to __asan_init
724 // at the beginning in order to initialize our runtime before any access to
725 // the shadow memory.
726 // We cannot just ignore these methods, because they may call other
727 // instrumented functions.
728 if (F.getName().find(" load]") != std::string::npos) {
729 IRBuilder<> IRB(F.begin()->begin());
730 IRB.CreateCall(AsanInitFunction);
731 return true;
732 }
733 return false;
734}
735
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000736bool AddressSanitizer::handleFunction(Module &M, Function &F) {
737 if (BL->isIn(F)) return false;
738 if (&F == AsanCtorFunction) return false;
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000739
740 // If needed, insert __asan_init before checking for AddressSafety attr.
741 maybeInsertAsanInitAtFunctionEntry(F);
742
Kostya Serebryany0307b9a2012-01-24 19:34:43 +0000743 if (!F.hasFnAttr(Attribute::AddressSafety)) return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000744
745 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
746 return false;
747 // We want to instrument every address only once per basic block
748 // (unless there are calls between uses).
749 SmallSet<Value*, 16> TempsToInstrument;
750 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000751 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000752 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000753
754 // Fill the set of memory operations to instrument.
755 for (Function::iterator FI = F.begin(), FE = F.end();
756 FI != FE; ++FI) {
757 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000758 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000759 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
760 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +0000761 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000762 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000763 if (ClOpt && ClOptSameTemp) {
764 if (!TempsToInstrument.insert(Addr))
765 continue; // We've seen this temp in the current BB.
766 }
767 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
768 // ok, take it.
769 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000770 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000771 // A call inside BB.
772 TempsToInstrument.clear();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000773 if (CI->doesNotReturn()) {
774 NoReturnCalls.push_back(CI);
775 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000776 }
777 continue;
778 }
779 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000780 NumInsnsPerBB++;
781 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
782 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000783 }
784 }
785
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000786 AsanFunctionContext AFC(F);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000787
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000788 // Instrument.
789 int NumInstrumented = 0;
790 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
791 Instruction *Inst = ToInstrument[i];
792 if (ClDebugMin < 0 || ClDebugMax < 0 ||
793 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000794 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000795 instrumentMop(AFC, Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000796 else
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000797 instrumentMemIntrinsic(AFC, cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000798 }
799 NumInstrumented++;
800 }
801
802 DEBUG(dbgs() << F);
803
804 bool ChangedStack = poisonStackInFunction(M, F);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000805
806 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
807 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
808 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
809 Instruction *CI = NoReturnCalls[i];
810 IRBuilder<> IRB(CI);
811 IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
812 IRB.getVoidTy(), NULL));
813 }
814
815 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000816}
817
818static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
819 if (ShadowRedzoneSize == 1) return PoisonByte;
820 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
821 if (ShadowRedzoneSize == 4)
822 return (PoisonByte << 24) + (PoisonByte << 16) +
823 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +0000824 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000825}
826
827static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
828 size_t Size,
829 size_t RedzoneSize,
830 size_t ShadowGranularity,
831 uint8_t Magic) {
832 for (size_t i = 0; i < RedzoneSize;
833 i+= ShadowGranularity, Shadow++) {
834 if (i + ShadowGranularity <= Size) {
835 *Shadow = 0; // fully addressable
836 } else if (i >= Size) {
837 *Shadow = Magic; // unaddressable
838 } else {
839 *Shadow = Size - i; // first Size-i bytes are addressable
840 }
841 }
842}
843
844void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
845 IRBuilder<> IRB,
846 Value *ShadowBase, bool DoPoison) {
847 size_t ShadowRZSize = RedzoneSize >> MappingScale;
848 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
849 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
850 Type *RZPtrTy = PointerType::get(RZTy, 0);
851
852 Value *PoisonLeft = ConstantInt::get(RZTy,
853 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
854 Value *PoisonMid = ConstantInt::get(RZTy,
855 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
856 Value *PoisonRight = ConstantInt::get(RZTy,
857 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
858
859 // poison the first red zone.
860 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
861
862 // poison all other red zones.
863 uint64_t Pos = RedzoneSize;
864 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
865 AllocaInst *AI = AllocaVec[i];
866 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
867 uint64_t AlignedSize = getAlignedAllocaSize(AI);
868 assert(AlignedSize - SizeInBytes < RedzoneSize);
869 Value *Ptr = NULL;
870
871 Pos += AlignedSize;
872
873 assert(ShadowBase->getType() == IntptrTy);
874 if (SizeInBytes < AlignedSize) {
875 // Poison the partial redzone at right
876 Ptr = IRB.CreateAdd(
877 ShadowBase, ConstantInt::get(IntptrTy,
878 (Pos >> MappingScale) - ShadowRZSize));
879 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
880 uint32_t Poison = 0;
881 if (DoPoison) {
882 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
883 RedzoneSize,
884 1ULL << MappingScale,
885 kAsanStackPartialRedzoneMagic);
886 }
887 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
888 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
889 }
890
891 // Poison the full redzone at right.
892 Ptr = IRB.CreateAdd(ShadowBase,
893 ConstantInt::get(IntptrTy, Pos >> MappingScale));
894 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
895 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
896
897 Pos += RedzoneSize;
898 }
899}
900
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000901// Workaround for bug 11395: we don't want to instrument stack in functions
902// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
Kostya Serebryanyd2703de2011-11-23 02:10:54 +0000903// FIXME: remove once the bug 11395 is fixed.
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000904bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
905 if (LongSize != 32) return false;
906 CallInst *CI = dyn_cast<CallInst>(I);
907 if (!CI || !CI->isInlineAsm()) return false;
908 if (CI->getNumArgOperands() <= 5) return false;
909 // We have inline assembly with quite a few arguments.
910 return true;
911}
912
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000913// Find all static Alloca instructions and put
914// poisoned red zones around all of them.
915// Then unpoison everything back before the function returns.
916//
917// Stack poisoning does not play well with exception handling.
918// When an exception is thrown, we essentially bypass the code
919// that unpoisones the stack. This is why the run-time library has
920// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
921// stack in the interceptor. This however does not work inside the
922// actual function which catches the exception. Most likely because the
923// compiler hoists the load of the shadow value somewhere too high.
924// This causes asan to report a non-existing bug on 453.povray.
925// It sounds like an LLVM bug.
926bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
927 if (!ClStack) return false;
928 SmallVector<AllocaInst*, 16> AllocaVec;
929 SmallVector<Instruction*, 8> RetVec;
930 uint64_t TotalSize = 0;
931
932 // Filter out Alloca instructions we want (and can) handle.
933 // Collect Ret instructions.
934 for (Function::iterator FI = F.begin(), FE = F.end();
935 FI != FE; ++FI) {
936 BasicBlock &BB = *FI;
937 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
938 BI != BE; ++BI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000939 if (isa<ReturnInst>(BI)) {
940 RetVec.push_back(BI);
941 continue;
942 }
943
944 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
945 if (!AI) continue;
946 if (AI->isArrayAllocation()) continue;
947 if (!AI->isStaticAlloca()) continue;
948 if (!AI->getAllocatedType()->isSized()) continue;
949 if (AI->getAlignment() > RedzoneSize) continue;
950 AllocaVec.push_back(AI);
951 uint64_t AlignedSize = getAlignedAllocaSize(AI);
952 TotalSize += AlignedSize;
953 }
954 }
955
956 if (AllocaVec.empty()) return false;
957
958 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
959
960 bool DoStackMalloc = ClUseAfterReturn
961 && LocalStackSize <= kMaxStackMallocSize;
962
963 Instruction *InsBefore = AllocaVec[0];
964 IRBuilder<> IRB(InsBefore);
965
966
967 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
968 AllocaInst *MyAlloca =
969 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
970 MyAlloca->setAlignment(RedzoneSize);
971 assert(MyAlloca->isStaticAlloca());
972 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
973 Value *LocalStackBase = OrigStackBase;
974
975 if (DoStackMalloc) {
976 Value *AsanStackMallocFunc = M.getOrInsertFunction(
977 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
978 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
979 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
980 }
981
982 // This string will be parsed by the run-time (DescribeStackAddress).
983 SmallString<2048> StackDescriptionStorage;
984 raw_svector_ostream StackDescription(StackDescriptionStorage);
985 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
986
987 uint64_t Pos = RedzoneSize;
988 // Replace Alloca instructions with base+offset.
989 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
990 AllocaInst *AI = AllocaVec[i];
991 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
992 StringRef Name = AI->getName();
993 StackDescription << Pos << " " << SizeInBytes << " "
994 << Name.size() << " " << Name << " ";
995 uint64_t AlignedSize = getAlignedAllocaSize(AI);
996 assert((AlignedSize % RedzoneSize) == 0);
997 AI->replaceAllUsesWith(
998 IRB.CreateIntToPtr(
999 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1000 AI->getType()));
1001 Pos += AlignedSize + RedzoneSize;
1002 }
1003 assert(Pos == LocalStackSize);
1004
1005 // Write the Magic value and the frame description constant to the redzone.
1006 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1007 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1008 BasePlus0);
1009 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1010 ConstantInt::get(IntptrTy, LongSize/8));
1011 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1012 Value *Description = IRB.CreatePointerCast(
1013 createPrivateGlobalForString(M, StackDescription.str()),
1014 IntptrTy);
1015 IRB.CreateStore(Description, BasePlus1);
1016
1017 // Poison the stack redzones at the entry.
1018 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1019 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1020
1021 Value *AsanStackFreeFunc = NULL;
1022 if (DoStackMalloc) {
1023 AsanStackFreeFunc = M.getOrInsertFunction(
1024 kAsanStackFreeName, IRB.getVoidTy(),
1025 IntptrTy, IntptrTy, IntptrTy, NULL);
1026 }
1027
1028 // Unpoison the stack before all ret instructions.
1029 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1030 Instruction *Ret = RetVec[i];
1031 IRBuilder<> IRBRet(Ret);
1032
1033 // Mark the current frame as retired.
1034 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1035 BasePlus0);
1036 // Unpoison the stack.
1037 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1038
1039 if (DoStackMalloc) {
1040 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1041 ConstantInt::get(IntptrTy, LocalStackSize),
1042 OrigStackBase);
1043 }
1044 }
1045
1046 if (ClDebugStack) {
1047 DEBUG(dbgs() << F);
1048 }
1049
1050 return true;
1051}