blob: c0690f58c6064e97e9b4a23905a7d11f6794895a [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 Serebryanyb5b86d22012-08-24 16:44:47 +000018#include "BlackList.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"
Micah Villmow3574eca2012-10-08 16:38:25 +000038#include "llvm/DataLayout.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000039#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 Serebryany9b9f87a2012-08-21 08:24:25 +000064static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
65static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000066static const char *kAsanInitName = "__asan_init";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000067static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000068static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
69static const char *kAsanMappingScaleName = "__asan_mapping_scale";
70static const char *kAsanStackMallocName = "__asan_stack_malloc";
71static const char *kAsanStackFreeName = "__asan_stack_free";
Kostya Serebryany51c7c652012-11-20 14:16:08 +000072static const char *kAsanGenPrefix = "__asan_gen_";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000073
74static const int kAsanStackLeftRedzoneMagic = 0xf1;
75static const int kAsanStackMidRedzoneMagic = 0xf2;
76static const int kAsanStackRightRedzoneMagic = 0xf3;
77static const int kAsanStackPartialRedzoneMagic = 0xf4;
78
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000079// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
80static const size_t kNumberOfAccessSizes = 5;
81
Kostya Serebryany800e03f2011-11-16 01:35:23 +000082// Command-line flags.
83
84// This flag may need to be replaced with -f[no-]asan-reads.
85static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
86 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
87static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
88 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000089static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
90 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
91 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +000092static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
93 cl::desc("use instrumentation with slow path for all accesses"),
94 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000095// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +000096// in any given BB. Normally, this should be set to unlimited (INT_MAX),
97// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
98// set it to 10000.
99static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
100 cl::init(10000),
101 cl::desc("maximal number of instructions to instrument in any given BB"),
102 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000103// This flag may need to be replaced with -f[no]asan-stack.
104static cl::opt<bool> ClStack("asan-stack",
105 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
106// This flag may need to be replaced with -f[no]asan-use-after-return.
107static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
108 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
109// This flag may need to be replaced with -f[no]asan-globals.
110static cl::opt<bool> ClGlobals("asan-globals",
111 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000112static cl::opt<bool> ClInitializers("asan-initialization-order",
113 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000114static cl::opt<bool> ClMemIntrin("asan-memintrin",
115 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
116// This flag may need to be replaced with -fasan-blacklist.
117static cl::opt<std::string> ClBlackListFile("asan-blacklist",
118 cl::desc("File containing the list of functions to ignore "
119 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000120
121// These flags allow to change the shadow mapping.
122// The shadow mapping looks like
123// Shadow = (Mem >> scale) + (1 << offset_log)
124static cl::opt<int> ClMappingScale("asan-mapping-scale",
125 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
126static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
127 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
128
129// Optimization flags. Not user visible, used mostly for testing
130// and benchmarking the tool.
131static cl::opt<bool> ClOpt("asan-opt",
132 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
133static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
134 cl::desc("Instrument the same temp just once"), cl::Hidden,
135 cl::init(true));
136static cl::opt<bool> ClOptGlobals("asan-opt-globals",
137 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
138
Alexey Samsonovee548272012-11-29 18:14:24 +0000139static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
140 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
141 cl::Hidden, cl::init(false));
142
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000143// Debug flags.
144static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
145 cl::init(0));
146static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
147 cl::Hidden, cl::init(0));
148static cl::opt<std::string> ClDebugFunc("asan-debug-func",
149 cl::Hidden, cl::desc("Debug func"));
150static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
151 cl::Hidden, cl::init(-1));
152static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
153 cl::Hidden, cl::init(-1));
154
155namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000156/// A set of dynamically initialized globals extracted from metadata.
157class SetOfDynamicallyInitializedGlobals {
158 public:
159 void Init(Module& M) {
160 // Clang generates metadata identifying all dynamically initialized globals.
161 NamedMDNode *DynamicGlobals =
162 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
163 if (!DynamicGlobals)
164 return;
165 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
166 MDNode *MDN = DynamicGlobals->getOperand(i);
167 assert(MDN->getNumOperands() == 1);
168 Value *VG = MDN->getOperand(0);
169 // The optimizer may optimize away a global entirely, in which case we
170 // cannot instrument access to it.
171 if (!VG)
172 continue;
173 DynInitGlobals.insert(cast<GlobalVariable>(VG));
174 }
175 }
176 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
177 private:
178 SmallSet<GlobalValue*, 32> DynInitGlobals;
179};
180
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000181static int MappingScale() {
182 return ClMappingScale ? ClMappingScale : kDefaultShadowScale;
183}
184
185static size_t RedzoneSize() {
186 // Redzone used for stack and globals is at least 32 bytes.
187 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
188 return std::max(32U, 1U << MappingScale());
189}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000190
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000191/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000192struct AddressSanitizer : public FunctionPass {
Alexey Samsonovee548272012-11-29 18:14:24 +0000193 AddressSanitizer(bool CheckInitOrder = false,
194 bool CheckUseAfterReturn = false,
195 bool CheckLifetime = false)
196 : FunctionPass(ID),
197 CheckInitOrder(CheckInitOrder || ClInitializers),
198 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
199 CheckLifetime(CheckLifetime || ClCheckLifetime) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000200 virtual const char *getPassName() const {
201 return "AddressSanitizerFunctionPass";
202 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000203 void instrumentMop(Instruction *I);
204 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000205 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000206 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
207 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000208 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000209 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000210 bool instrumentMemIntrinsic(MemIntrinsic *MI);
211 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000212 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000213 Instruction *InsertBefore, bool IsWrite);
214 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000215 bool runOnFunction(Function &F);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000216 void createInitializerPoisonCalls(Module &M,
217 Value *FirstAddr, Value *LastAddr);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000218 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000219 bool poisonStackInFunction(Function &F);
220 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000221 static char ID; // Pass identification, replacement for typeid
222
223 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000224 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000225 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
226 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanovd8313be2012-03-02 10:41:08 +0000227 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000228 return SizeInBytes;
229 }
230 uint64_t getAlignedSize(uint64_t SizeInBytes) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000231 size_t RZ = RedzoneSize();
232 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000233 }
234 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
235 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
236 return getAlignedSize(SizeInBytes);
237 }
238
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000239 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000240 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
241 Value *ShadowBase, bool DoPoison);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000242 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000243 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000244
Alexey Samsonovee548272012-11-29 18:14:24 +0000245 bool CheckInitOrder;
246 bool CheckUseAfterReturn;
247 bool CheckLifetime;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000248 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000249 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000250 uint64_t MappingOffset;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000251 int LongSize;
252 Type *IntptrTy;
253 Type *IntptrPtrTy;
254 Function *AsanCtorFunction;
255 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000256 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
257 Function *AsanHandleNoReturnFunc;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000258 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000259 // This array is indexed by AccessIsWrite and log2(AccessSize).
260 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000261 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000262 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000263};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000264
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000265class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000266 public:
Alexey Samsonovee548272012-11-29 18:14:24 +0000267 AddressSanitizerModule(bool CheckInitOrder = false)
268 : ModulePass(ID),
269 CheckInitOrder(CheckInitOrder || ClInitializers) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000270 bool runOnModule(Module &M);
271 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000272 virtual const char *getPassName() const {
273 return "AddressSanitizerModule";
274 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000275 private:
276 bool ShouldInstrumentGlobal(GlobalVariable *G);
277 void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
278 Value *LastAddr);
279
Alexey Samsonovee548272012-11-29 18:14:24 +0000280 bool CheckInitOrder;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000281 OwningPtr<BlackList> BL;
282 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
283 Type *IntptrTy;
284 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000285 DataLayout *TD;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000286};
287
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000288} // namespace
289
290char AddressSanitizer::ID = 0;
291INITIALIZE_PASS(AddressSanitizer, "asan",
292 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
293 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000294FunctionPass *llvm::createAddressSanitizerFunctionPass(
295 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime) {
296 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
297 CheckLifetime);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000298}
299
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000300char AddressSanitizerModule::ID = 0;
301INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
302 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
303 "ModulePass", false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000304ModulePass *llvm::createAddressSanitizerModulePass(bool CheckInitOrder) {
305 return new AddressSanitizerModule(CheckInitOrder);
Alexander Potapenko25878042012-01-23 11:22:43 +0000306}
307
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000308static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
309 size_t Res = CountTrailingZeros_32(TypeSize / 8);
310 assert(Res < kNumberOfAccessSizes);
311 return Res;
312}
313
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000314// Create a constant for Str so that we can pass it to the run-time lib.
315static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000316 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000317 return new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000318 GlobalValue::PrivateLinkage, StrConst,
319 kAsanGenPrefix);
320}
321
322static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
323 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000324}
325
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000326Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
327 // Shadow >> scale
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000328 Shadow = IRB.CreateLShr(Shadow, MappingScale());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000329 if (MappingOffset == 0)
330 return Shadow;
331 // (Shadow >> scale) | offset
332 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
333 MappingOffset));
334}
335
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000336void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000337 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000338 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
339 // Check the first byte.
340 {
341 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000342 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000343 }
344 // Check the last byte.
345 {
346 IRBuilder<> IRB(InsertBefore);
347 Value *SizeMinusOne = IRB.CreateSub(
348 Size, ConstantInt::get(Size->getType(), 1));
349 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
350 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
351 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000352 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000353 }
354}
355
356// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000357bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000358 Value *Dst = MI->getDest();
359 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000360 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000361 Value *Length = MI->getLength();
362
363 Constant *ConstLength = dyn_cast<Constant>(Length);
364 Instruction *InsertBefore = MI;
365 if (ConstLength) {
366 if (ConstLength->isNullValue()) return false;
367 } else {
368 // The size is not a constant so it could be zero -- check at run-time.
369 IRBuilder<> IRB(InsertBefore);
370
371 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000372 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000373 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000374 }
375
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000376 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000377 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000378 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000379 return true;
380}
381
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000382// If I is an interesting memory access, return the PointerOperand
383// and set IsWrite. Otherwise return NULL.
384static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000385 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000386 if (!ClInstrumentReads) return NULL;
387 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000388 return LI->getPointerOperand();
389 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000390 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
391 if (!ClInstrumentWrites) return NULL;
392 *IsWrite = true;
393 return SI->getPointerOperand();
394 }
395 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
396 if (!ClInstrumentAtomics) return NULL;
397 *IsWrite = true;
398 return RMW->getPointerOperand();
399 }
400 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
401 if (!ClInstrumentAtomics) return NULL;
402 *IsWrite = true;
403 return XCHG->getPointerOperand();
404 }
405 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000406}
407
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000408void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000409 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000410 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
411 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000412 if (ClOpt && ClOptGlobals) {
413 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
414 // If initialization order checking is disabled, a simple access to a
415 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000416 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000417 return;
418 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000419 // have to instrument it. However, if a global does not have initailizer
420 // at all, we assume it has dynamic initializer (in other TU).
421 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000422 return;
423 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000424 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000425
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000426 Type *OrigPtrTy = Addr->getType();
427 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
428
429 assert(OrigTy->isSized());
430 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
431
432 if (TypeSize != 8 && TypeSize != 16 &&
433 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
434 // Ignore all unusual sizes.
435 return;
436 }
437
438 IRBuilder<> IRB(I);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000439 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000440}
441
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000442// Validate the result of Module::getOrInsertFunction called for an interface
443// function of AddressSanitizer. If the instrumented module defines a function
444// with the same name, their prototypes must match, otherwise
445// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000446static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000447 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
448 FuncOrBitcast->dump();
449 report_fatal_error("trying to redefine an AddressSanitizer "
450 "interface function");
451}
452
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000453Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000454 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000455 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000456 IRBuilder<> IRB(InsertBefore);
457 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
458 Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000459 // We don't do Call->setDoesNotReturn() because the BB already has
460 // UnreachableInst at the end.
461 // This EmptyAsm is required to avoid callback merge.
462 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000463 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000464}
465
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000466Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000467 Value *ShadowValue,
468 uint32_t TypeSize) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000469 size_t Granularity = 1 << MappingScale();
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000470 // Addr & (Granularity - 1)
471 Value *LastAccessedByte = IRB.CreateAnd(
472 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
473 // (Addr & (Granularity - 1)) + size - 1
474 if (TypeSize / 8 > 1)
475 LastAccessedByte = IRB.CreateAdd(
476 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
477 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
478 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000479 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000480 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
481 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
482}
483
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000484void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000485 IRBuilder<> &IRB, Value *Addr,
486 uint32_t TypeSize, bool IsWrite) {
487 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
488
489 Type *ShadowTy = IntegerType::get(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000490 *C, std::max(8U, TypeSize >> MappingScale()));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000491 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
492 Value *ShadowPtr = memToShadow(AddrLong, IRB);
493 Value *CmpVal = Constant::getNullValue(ShadowTy);
494 Value *ShadowValue = IRB.CreateLoad(
495 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
496
497 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000498 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000499 size_t Granularity = 1 << MappingScale();
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000500 TerminatorInst *CrashTerm = 0;
501
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000502 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000503 TerminatorInst *CheckTerm =
504 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000505 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000506 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000507 IRB.SetInsertPoint(CheckTerm);
508 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000509 BasicBlock *CrashBlock =
510 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000511 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000512 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
513 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000514 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000515 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000516 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000517
518 Instruction *Crash =
519 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
520 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000521}
522
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000523void AddressSanitizerModule::createInitializerPoisonCalls(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000524 Module &M, Value *FirstAddr, Value *LastAddr) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000525 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
526 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
527 // If that function is not present, this TU contains no globals, or they have
528 // all been optimized away
529 if (!GlobalInit)
530 return;
531
532 // Set up the arguments to our poison/unpoison functions.
533 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
534
535 // Declare our poisoning and unpoisoning functions.
536 Function *AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
537 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
538 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
539 Function *AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
540 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
541 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
542
543 // Add a call to poison all external globals before the given function starts.
544 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
545
546 // Add calls to unpoison all globals before each return instruction.
547 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
548 I != E; ++I) {
549 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
550 CallInst::Create(AsanUnpoisonGlobals, "", RI);
551 }
552 }
553}
554
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000555bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000556 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000557 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000558
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000559 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000560 if (!Ty->isSized()) return false;
561 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000562 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000563 // Touch only those globals that will not be defined in other modules.
564 // Don't handle ODR type linkages since other modules may be built w/o asan.
565 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
566 G->getLinkage() != GlobalVariable::PrivateLinkage &&
567 G->getLinkage() != GlobalVariable::InternalLinkage)
568 return false;
569 // Two problems with thread-locals:
570 // - The address of the main thread's copy can't be computed at link-time.
571 // - Need to poison all copies, not just the main thread's one.
572 if (G->isThreadLocal())
573 return false;
574 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000575 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000576
577 // Ignore all the globals with the names starting with "\01L_OBJC_".
578 // Many of those are put into the .cstring section. The linker compresses
579 // that section by removing the spare \0s after the string terminator, so
580 // our redzones get broken.
581 if ((G->getName().find("\01L_OBJC_") == 0) ||
582 (G->getName().find("\01l_OBJC_") == 0)) {
583 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
584 return false;
585 }
586
587 if (G->hasSection()) {
588 StringRef Section(G->getSection());
589 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
590 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
591 // them.
592 if ((Section.find("__OBJC,") == 0) ||
593 (Section.find("__DATA, __objc_") == 0)) {
594 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
595 return false;
596 }
597 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
598 // Constant CFString instances are compiled in the following way:
599 // -- the string buffer is emitted into
600 // __TEXT,__cstring,cstring_literals
601 // -- the constant NSConstantString structure referencing that buffer
602 // is placed into __DATA,__cfstring
603 // Therefore there's no point in placing redzones into __DATA,__cfstring.
604 // Moreover, it causes the linker to crash on OS X 10.7
605 if (Section.find("__DATA,__cfstring") == 0) {
606 DEBUG(dbgs() << "Ignoring CFString: " << *G);
607 return false;
608 }
609 }
610
611 return true;
612}
613
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000614// This function replaces all global variables with new variables that have
615// trailing redzones. It also creates a function that poisons
616// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000617bool AddressSanitizerModule::runOnModule(Module &M) {
618 if (!ClGlobals) return false;
619 TD = getAnalysisIfAvailable<DataLayout>();
620 if (!TD)
621 return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000622 BL.reset(new BlackList(ClBlackListFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000623 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000624 DynamicallyInitializedGlobals.Init(M);
625 C = &(M.getContext());
626 IntptrTy = Type::getIntNTy(*C, TD->getPointerSizeInBits());
627
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000628 SmallVector<GlobalVariable *, 16> GlobalsToChange;
629
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000630 for (Module::GlobalListType::iterator G = M.global_begin(),
631 E = M.global_end(); G != E; ++G) {
632 if (ShouldInstrumentGlobal(G))
633 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000634 }
635
636 size_t n = GlobalsToChange.size();
637 if (n == 0) return false;
638
639 // A global is described by a structure
640 // size_t beg;
641 // size_t size;
642 // size_t size_with_redzone;
643 // const char *name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000644 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000645 // We initialize an array of such structures and pass it to a run-time call.
646 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000647 IntptrTy, IntptrTy,
648 IntptrTy, NULL);
649 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000650
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000651
652 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
653 assert(CtorFunc);
654 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000655
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000656 // The addresses of the first and last dynamically initialized globals in
657 // this TU. Used in initialization order checking.
658 Value *FirstDynamic = 0, *LastDynamic = 0;
659
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000660 for (size_t i = 0; i < n; i++) {
661 GlobalVariable *G = GlobalsToChange[i];
662 PointerType *PtrTy = cast<PointerType>(G->getType());
663 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000664 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000665 size_t RZ = RedzoneSize();
666 uint64_t RightRedzoneSize = RZ + (RZ - (SizeInBytes % RZ));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000667 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000668 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000669 bool GlobalHasDynamicInitializer =
670 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000671 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000672 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000673
674 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
675 Constant *NewInitializer = ConstantStruct::get(
676 NewTy, G->getInitializer(),
677 Constant::getNullValue(RightRedZoneTy), NULL);
678
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000679 SmallString<2048> DescriptionOfGlobal = G->getName();
680 DescriptionOfGlobal += " (";
681 DescriptionOfGlobal += M.getModuleIdentifier();
682 DescriptionOfGlobal += ")";
683 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000684
685 // Create a new global variable with enough space for a redzone.
686 GlobalVariable *NewGlobal = new GlobalVariable(
687 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000688 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000689 NewGlobal->copyAttributesFrom(G);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000690 NewGlobal->setAlignment(RZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000691
692 Value *Indices2[2];
693 Indices2[0] = IRB.getInt32(0);
694 Indices2[1] = IRB.getInt32(0);
695
696 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000697 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000698 NewGlobal->takeName(G);
699 G->eraseFromParent();
700
701 Initializers[i] = ConstantStruct::get(
702 GlobalStructTy,
703 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
704 ConstantInt::get(IntptrTy, SizeInBytes),
705 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
706 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000707 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000708 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000709
710 // Populate the first and last globals declared in this TU.
Alexey Samsonovee548272012-11-29 18:14:24 +0000711 if (CheckInitOrder && GlobalHasDynamicInitializer) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000712 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
713 if (FirstDynamic == 0)
714 FirstDynamic = LastDynamic;
715 }
716
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000717 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000718 }
719
720 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
721 GlobalVariable *AllGlobals = new GlobalVariable(
722 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
723 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
724
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000725 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovee548272012-11-29 18:14:24 +0000726 if (CheckInitOrder && FirstDynamic && LastDynamic)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000727 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
728
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000729 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000730 kAsanRegisterGlobalsName, IRB.getVoidTy(),
731 IntptrTy, IntptrTy, NULL));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000732 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
733
734 IRB.CreateCall2(AsanRegisterGlobals,
735 IRB.CreatePointerCast(AllGlobals, IntptrTy),
736 ConstantInt::get(IntptrTy, n));
737
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000738 // We also need to unregister globals at the end, e.g. when a shared library
739 // gets closed.
740 Function *AsanDtorFunction = Function::Create(
741 FunctionType::get(Type::getVoidTy(*C), false),
742 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
743 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
744 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000745 Function *AsanUnregisterGlobals =
746 checkInterfaceFunction(M.getOrInsertFunction(
747 kAsanUnregisterGlobalsName,
748 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000749 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
750
751 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
752 IRB.CreatePointerCast(AllGlobals, IntptrTy),
753 ConstantInt::get(IntptrTy, n));
754 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
755
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000756 DEBUG(dbgs() << M);
757 return true;
758}
759
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000760void AddressSanitizer::initializeCallbacks(Module &M) {
761 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000762 // Create __asan_report* callbacks.
763 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
764 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
765 AccessSizeIndex++) {
766 // IsWrite and TypeSize are encoded in the function name.
767 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
768 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000769 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +0000770 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
771 checkInterfaceFunction(M.getOrInsertFunction(
772 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000773 }
774 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000775
776 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
777 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
778 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
779 kAsanStackFreeName, IRB.getVoidTy(),
780 IntptrTy, IntptrTy, IntptrTy, NULL));
781 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
782 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
783
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000784 // We insert an empty inline asm after __asan_report* to avoid callback merge.
785 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
786 StringRef(""), StringRef(""),
787 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000788}
789
790// virtual
791bool AddressSanitizer::doInitialization(Module &M) {
792 // Initialize the private fields. No one has accessed them before.
793 TD = getAnalysisIfAvailable<DataLayout>();
794
795 if (!TD)
796 return false;
797 BL.reset(new BlackList(ClBlackListFile));
798 DynamicallyInitializedGlobals.Init(M);
799
800 C = &(M.getContext());
801 LongSize = TD->getPointerSizeInBits();
802 IntptrTy = Type::getIntNTy(*C, LongSize);
803 IntptrPtrTy = PointerType::get(IntptrTy, 0);
804
805 AsanCtorFunction = Function::Create(
806 FunctionType::get(Type::getVoidTy(*C), false),
807 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
808 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
809 // call __asan_init in the module ctor.
810 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
811 AsanInitFunction = checkInterfaceFunction(
812 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
813 AsanInitFunction->setLinkage(Function::ExternalLinkage);
814 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000815
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000816 llvm::Triple targetTriple(M.getTargetTriple());
Logan Chien43bf7092012-09-02 09:29:46 +0000817 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000818
819 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
820 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000821 if (ClMappingOffsetLog >= 0) {
822 if (ClMappingOffsetLog == 0) {
823 // special case
824 MappingOffset = 0;
825 } else {
826 MappingOffset = 1ULL << ClMappingOffsetLog;
827 }
828 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000829
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000830
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000831 if (ClMappingOffsetLog >= 0) {
832 // Tell the run-time the current values of mapping offset and scale.
833 GlobalValue *asan_mapping_offset =
834 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
835 ConstantInt::get(IntptrTy, MappingOffset),
836 kAsanMappingOffsetName);
837 // Read the global, otherwise it may be optimized away.
838 IRB.CreateLoad(asan_mapping_offset, true);
839 }
840 if (ClMappingScale) {
841 GlobalValue *asan_mapping_scale =
842 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000843 ConstantInt::get(IntptrTy, MappingScale()),
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000844 kAsanMappingScaleName);
845 // Read the global, otherwise it may be optimized away.
846 IRB.CreateLoad(asan_mapping_scale, true);
847 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000848
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000849 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryany9b027412011-12-12 18:01:46 +0000850
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000851 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000852}
853
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000854bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
855 // For each NSObject descendant having a +load method, this method is invoked
856 // by the ObjC runtime before any of the static constructors is called.
857 // Therefore we need to instrument such methods with a call to __asan_init
858 // at the beginning in order to initialize our runtime before any access to
859 // the shadow memory.
860 // We cannot just ignore these methods, because they may call other
861 // instrumented functions.
862 if (F.getName().find(" load]") != std::string::npos) {
863 IRBuilder<> IRB(F.begin()->begin());
864 IRB.CreateCall(AsanInitFunction);
865 return true;
866 }
867 return false;
868}
869
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000870bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000871 if (BL->isIn(F)) return false;
872 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000873 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000874 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000875
876 // If needed, insert __asan_init before checking for AddressSafety attr.
877 maybeInsertAsanInitAtFunctionEntry(F);
878
Bill Wendling67658342012-10-09 07:45:08 +0000879 if (!F.getFnAttributes().hasAttribute(Attributes::AddressSafety))
880 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000881
882 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
883 return false;
Bill Wendling67658342012-10-09 07:45:08 +0000884
885 // We want to instrument every address only once per basic block (unless there
886 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000887 SmallSet<Value*, 16> TempsToInstrument;
888 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000889 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000890 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000891
892 // Fill the set of memory operations to instrument.
893 for (Function::iterator FI = F.begin(), FE = F.end();
894 FI != FE; ++FI) {
895 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000896 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000897 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
898 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +0000899 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000900 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000901 if (ClOpt && ClOptSameTemp) {
902 if (!TempsToInstrument.insert(Addr))
903 continue; // We've seen this temp in the current BB.
904 }
905 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
906 // ok, take it.
907 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000908 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000909 // A call inside BB.
910 TempsToInstrument.clear();
Kostya Serebryanya17babb2012-11-30 11:08:59 +0000911 if (CI->doesNotReturn()) {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000912 NoReturnCalls.push_back(CI);
913 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000914 }
915 continue;
916 }
917 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000918 NumInsnsPerBB++;
919 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
920 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000921 }
922 }
923
924 // Instrument.
925 int NumInstrumented = 0;
926 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
927 Instruction *Inst = ToInstrument[i];
928 if (ClDebugMin < 0 || ClDebugMax < 0 ||
929 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000930 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000931 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000932 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000933 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000934 }
935 NumInstrumented++;
936 }
937
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000938 bool ChangedStack = poisonStackInFunction(F);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000939
940 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
941 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
942 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
943 Instruction *CI = NoReturnCalls[i];
944 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000945 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000946 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000947 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000948
949 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000950}
951
952static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
953 if (ShadowRedzoneSize == 1) return PoisonByte;
954 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
955 if (ShadowRedzoneSize == 4)
956 return (PoisonByte << 24) + (PoisonByte << 16) +
957 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +0000958 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000959}
960
961static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
962 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000963 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000964 size_t ShadowGranularity,
965 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000966 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000967 i+= ShadowGranularity, Shadow++) {
968 if (i + ShadowGranularity <= Size) {
969 *Shadow = 0; // fully addressable
970 } else if (i >= Size) {
971 *Shadow = Magic; // unaddressable
972 } else {
973 *Shadow = Size - i; // first Size-i bytes are addressable
974 }
975 }
976}
977
978void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
979 IRBuilder<> IRB,
980 Value *ShadowBase, bool DoPoison) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000981 size_t ShadowRZSize = RedzoneSize() >> MappingScale();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000982 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
983 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
984 Type *RZPtrTy = PointerType::get(RZTy, 0);
985
986 Value *PoisonLeft = ConstantInt::get(RZTy,
987 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
988 Value *PoisonMid = ConstantInt::get(RZTy,
989 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
990 Value *PoisonRight = ConstantInt::get(RZTy,
991 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
992
993 // poison the first red zone.
994 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
995
996 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000997 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000998 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
999 AllocaInst *AI = AllocaVec[i];
1000 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1001 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001002 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001003 Value *Ptr = NULL;
1004
1005 Pos += AlignedSize;
1006
1007 assert(ShadowBase->getType() == IntptrTy);
1008 if (SizeInBytes < AlignedSize) {
1009 // Poison the partial redzone at right
1010 Ptr = IRB.CreateAdd(
1011 ShadowBase, ConstantInt::get(IntptrTy,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001012 (Pos >> MappingScale()) - ShadowRZSize));
1013 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001014 uint32_t Poison = 0;
1015 if (DoPoison) {
1016 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001017 RedzoneSize(),
1018 1ULL << MappingScale(),
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001019 kAsanStackPartialRedzoneMagic);
1020 }
1021 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1022 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1023 }
1024
1025 // Poison the full redzone at right.
1026 Ptr = IRB.CreateAdd(ShadowBase,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001027 ConstantInt::get(IntptrTy, Pos >> MappingScale()));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001028 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
1029 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1030
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001031 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001032 }
1033}
1034
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +00001035// Workaround for bug 11395: we don't want to instrument stack in functions
1036// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
Kostya Serebryanyd2703de2011-11-23 02:10:54 +00001037// FIXME: remove once the bug 11395 is fixed.
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +00001038bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1039 if (LongSize != 32) return false;
1040 CallInst *CI = dyn_cast<CallInst>(I);
1041 if (!CI || !CI->isInlineAsm()) return false;
1042 if (CI->getNumArgOperands() <= 5) return false;
1043 // We have inline assembly with quite a few arguments.
1044 return true;
1045}
1046
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001047// Find all static Alloca instructions and put
1048// poisoned red zones around all of them.
1049// Then unpoison everything back before the function returns.
1050//
1051// Stack poisoning does not play well with exception handling.
1052// When an exception is thrown, we essentially bypass the code
1053// that unpoisones the stack. This is why the run-time library has
1054// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
1055// stack in the interceptor. This however does not work inside the
1056// actual function which catches the exception. Most likely because the
1057// compiler hoists the load of the shadow value somewhere too high.
1058// This causes asan to report a non-existing bug on 453.povray.
1059// It sounds like an LLVM bug.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001060bool AddressSanitizer::poisonStackInFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001061 if (!ClStack) return false;
1062 SmallVector<AllocaInst*, 16> AllocaVec;
1063 SmallVector<Instruction*, 8> RetVec;
1064 uint64_t TotalSize = 0;
1065
1066 // Filter out Alloca instructions we want (and can) handle.
1067 // Collect Ret instructions.
1068 for (Function::iterator FI = F.begin(), FE = F.end();
1069 FI != FE; ++FI) {
1070 BasicBlock &BB = *FI;
1071 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
1072 BI != BE; ++BI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001073 if (isa<ReturnInst>(BI)) {
1074 RetVec.push_back(BI);
1075 continue;
1076 }
1077
1078 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
1079 if (!AI) continue;
1080 if (AI->isArrayAllocation()) continue;
1081 if (!AI->isStaticAlloca()) continue;
1082 if (!AI->getAllocatedType()->isSized()) continue;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001083 if (AI->getAlignment() > RedzoneSize()) continue;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001084 AllocaVec.push_back(AI);
1085 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1086 TotalSize += AlignedSize;
1087 }
1088 }
1089
1090 if (AllocaVec.empty()) return false;
1091
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001092 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001093
Alexey Samsonovee548272012-11-29 18:14:24 +00001094 bool DoStackMalloc = CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001095 && LocalStackSize <= kMaxStackMallocSize;
1096
1097 Instruction *InsBefore = AllocaVec[0];
1098 IRBuilder<> IRB(InsBefore);
1099
1100
1101 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1102 AllocaInst *MyAlloca =
1103 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001104 MyAlloca->setAlignment(RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001105 assert(MyAlloca->isStaticAlloca());
1106 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1107 Value *LocalStackBase = OrigStackBase;
1108
1109 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001110 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1111 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1112 }
1113
1114 // This string will be parsed by the run-time (DescribeStackAddress).
1115 SmallString<2048> StackDescriptionStorage;
1116 raw_svector_ostream StackDescription(StackDescriptionStorage);
1117 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1118
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001119 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001120 // Replace Alloca instructions with base+offset.
1121 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1122 AllocaInst *AI = AllocaVec[i];
1123 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1124 StringRef Name = AI->getName();
1125 StackDescription << Pos << " " << SizeInBytes << " "
1126 << Name.size() << " " << Name << " ";
1127 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001128 assert((AlignedSize % RedzoneSize()) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001129 AI->replaceAllUsesWith(
1130 IRB.CreateIntToPtr(
1131 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1132 AI->getType()));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001133 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001134 }
1135 assert(Pos == LocalStackSize);
1136
1137 // Write the Magic value and the frame description constant to the redzone.
1138 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1139 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1140 BasePlus0);
1141 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1142 ConstantInt::get(IntptrTy, LongSize/8));
1143 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001144 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001145 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001146 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001147 IRB.CreateStore(Description, BasePlus1);
1148
1149 // Poison the stack redzones at the entry.
1150 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1151 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1152
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001153 // Unpoison the stack before all ret instructions.
1154 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1155 Instruction *Ret = RetVec[i];
1156 IRBuilder<> IRBRet(Ret);
1157
1158 // Mark the current frame as retired.
1159 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1160 BasePlus0);
1161 // Unpoison the stack.
1162 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1163
1164 if (DoStackMalloc) {
1165 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1166 ConstantInt::get(IntptrTy, LocalStackSize),
1167 OrigStackBase);
1168 }
1169 }
1170
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001171 // We are done. Remove the old unused alloca instructions.
1172 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1173 AllocaVec[i]->eraseFromParent();
1174
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001175 if (ClDebugStack) {
1176 DEBUG(dbgs() << F);
1177 }
1178
1179 return true;
1180}