blob: 318e393afeaedd12622bea92f166d1b0da82f204 [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
139// Debug flags.
140static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
141 cl::init(0));
142static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
143 cl::Hidden, cl::init(0));
144static cl::opt<std::string> ClDebugFunc("asan-debug-func",
145 cl::Hidden, cl::desc("Debug func"));
146static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
147 cl::Hidden, cl::init(-1));
148static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
149 cl::Hidden, cl::init(-1));
150
151namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000152/// A set of dynamically initialized globals extracted from metadata.
153class SetOfDynamicallyInitializedGlobals {
154 public:
155 void Init(Module& M) {
156 // Clang generates metadata identifying all dynamically initialized globals.
157 NamedMDNode *DynamicGlobals =
158 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
159 if (!DynamicGlobals)
160 return;
161 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
162 MDNode *MDN = DynamicGlobals->getOperand(i);
163 assert(MDN->getNumOperands() == 1);
164 Value *VG = MDN->getOperand(0);
165 // The optimizer may optimize away a global entirely, in which case we
166 // cannot instrument access to it.
167 if (!VG)
168 continue;
169 DynInitGlobals.insert(cast<GlobalVariable>(VG));
170 }
171 }
172 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
173 private:
174 SmallSet<GlobalValue*, 32> DynInitGlobals;
175};
176
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000177static int MappingScale() {
178 return ClMappingScale ? ClMappingScale : kDefaultShadowScale;
179}
180
181static size_t RedzoneSize() {
182 // Redzone used for stack and globals is at least 32 bytes.
183 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
184 return std::max(32U, 1U << MappingScale());
185}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000186
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000187/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000188struct AddressSanitizer : public FunctionPass {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000189 AddressSanitizer();
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000190 virtual const char *getPassName() const {
191 return "AddressSanitizerFunctionPass";
192 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000193 void instrumentMop(Instruction *I);
194 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000195 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000196 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
197 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000198 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000199 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000200 bool instrumentMemIntrinsic(MemIntrinsic *MI);
201 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000202 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000203 Instruction *InsertBefore, bool IsWrite);
204 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000205 bool runOnFunction(Function &F);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000206 void createInitializerPoisonCalls(Module &M,
207 Value *FirstAddr, Value *LastAddr);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000208 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000209 bool poisonStackInFunction(Function &F);
210 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000211 static char ID; // Pass identification, replacement for typeid
212
213 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000214 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000215 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
216 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanovd8313be2012-03-02 10:41:08 +0000217 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000218 return SizeInBytes;
219 }
220 uint64_t getAlignedSize(uint64_t SizeInBytes) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000221 size_t RZ = RedzoneSize();
222 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000223 }
224 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
225 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
226 return getAlignedSize(SizeInBytes);
227 }
228
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000229 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000230 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
231 Value *ShadowBase, bool DoPoison);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000232 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000233 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000234
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000235 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000236 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000237 uint64_t MappingOffset;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000238 int LongSize;
239 Type *IntptrTy;
240 Type *IntptrPtrTy;
241 Function *AsanCtorFunction;
242 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000243 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
244 Function *AsanHandleNoReturnFunc;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000245 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000246 // This array is indexed by AccessIsWrite and log2(AccessSize).
247 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000248 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000249 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000250};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000251
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000252class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000253 public:
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000254 bool runOnModule(Module &M);
255 static char ID; // Pass identification, replacement for typeid
256 AddressSanitizerModule() : ModulePass(ID) { }
257 virtual const char *getPassName() const {
258 return "AddressSanitizerModule";
259 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000260 private:
261 bool ShouldInstrumentGlobal(GlobalVariable *G);
262 void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
263 Value *LastAddr);
264
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000265 OwningPtr<BlackList> BL;
266 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
267 Type *IntptrTy;
268 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000269 DataLayout *TD;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000270};
271
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000272} // namespace
273
274char AddressSanitizer::ID = 0;
275INITIALIZE_PASS(AddressSanitizer, "asan",
276 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
277 false, false)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000278AddressSanitizer::AddressSanitizer() : FunctionPass(ID) { }
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000279FunctionPass *llvm::createAddressSanitizerFunctionPass() {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000280 return new AddressSanitizer();
281}
282
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000283char AddressSanitizerModule::ID = 0;
284INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
285 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
286 "ModulePass", false, false)
287ModulePass *llvm::createAddressSanitizerModulePass() {
288 return new AddressSanitizerModule();
Alexander Potapenko25878042012-01-23 11:22:43 +0000289}
290
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000291static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
292 size_t Res = CountTrailingZeros_32(TypeSize / 8);
293 assert(Res < kNumberOfAccessSizes);
294 return Res;
295}
296
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000297// Create a constant for Str so that we can pass it to the run-time lib.
298static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000299 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000300 return new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000301 GlobalValue::PrivateLinkage, StrConst,
302 kAsanGenPrefix);
303}
304
305static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
306 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000307}
308
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000309Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
310 // Shadow >> scale
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000311 Shadow = IRB.CreateLShr(Shadow, MappingScale());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000312 if (MappingOffset == 0)
313 return Shadow;
314 // (Shadow >> scale) | offset
315 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
316 MappingOffset));
317}
318
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000319void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000320 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000321 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
322 // Check the first byte.
323 {
324 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000325 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000326 }
327 // Check the last byte.
328 {
329 IRBuilder<> IRB(InsertBefore);
330 Value *SizeMinusOne = IRB.CreateSub(
331 Size, ConstantInt::get(Size->getType(), 1));
332 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
333 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
334 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000335 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000336 }
337}
338
339// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000340bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000341 Value *Dst = MI->getDest();
342 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000343 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000344 Value *Length = MI->getLength();
345
346 Constant *ConstLength = dyn_cast<Constant>(Length);
347 Instruction *InsertBefore = MI;
348 if (ConstLength) {
349 if (ConstLength->isNullValue()) return false;
350 } else {
351 // The size is not a constant so it could be zero -- check at run-time.
352 IRBuilder<> IRB(InsertBefore);
353
354 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000355 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000356 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000357 }
358
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000359 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000360 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000361 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000362 return true;
363}
364
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000365// If I is an interesting memory access, return the PointerOperand
366// and set IsWrite. Otherwise return NULL.
367static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000368 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000369 if (!ClInstrumentReads) return NULL;
370 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000371 return LI->getPointerOperand();
372 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000373 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
374 if (!ClInstrumentWrites) return NULL;
375 *IsWrite = true;
376 return SI->getPointerOperand();
377 }
378 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
379 if (!ClInstrumentAtomics) return NULL;
380 *IsWrite = true;
381 return RMW->getPointerOperand();
382 }
383 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
384 if (!ClInstrumentAtomics) return NULL;
385 *IsWrite = true;
386 return XCHG->getPointerOperand();
387 }
388 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000389}
390
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000391void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000392 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000393 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
394 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000395 if (ClOpt && ClOptGlobals) {
396 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
397 // If initialization order checking is disabled, a simple access to a
398 // dynamically initialized global is always valid.
399 if (!ClInitializers)
400 return;
401 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000402 // have to instrument it. However, if a global does not have initailizer
403 // at all, we assume it has dynamic initializer (in other TU).
404 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000405 return;
406 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000407 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000408
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000409 Type *OrigPtrTy = Addr->getType();
410 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
411
412 assert(OrigTy->isSized());
413 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
414
415 if (TypeSize != 8 && TypeSize != 16 &&
416 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
417 // Ignore all unusual sizes.
418 return;
419 }
420
421 IRBuilder<> IRB(I);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000422 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000423}
424
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000425// Validate the result of Module::getOrInsertFunction called for an interface
426// function of AddressSanitizer. If the instrumented module defines a function
427// with the same name, their prototypes must match, otherwise
428// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000429static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000430 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
431 FuncOrBitcast->dump();
432 report_fatal_error("trying to redefine an AddressSanitizer "
433 "interface function");
434}
435
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000436Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000437 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000438 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000439 IRBuilder<> IRB(InsertBefore);
440 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
441 Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000442 // We don't do Call->setDoesNotReturn() because the BB already has
443 // UnreachableInst at the end.
444 // This EmptyAsm is required to avoid callback merge.
445 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000446 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000447}
448
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000449Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000450 Value *ShadowValue,
451 uint32_t TypeSize) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000452 size_t Granularity = 1 << MappingScale();
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000453 // Addr & (Granularity - 1)
454 Value *LastAccessedByte = IRB.CreateAnd(
455 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
456 // (Addr & (Granularity - 1)) + size - 1
457 if (TypeSize / 8 > 1)
458 LastAccessedByte = IRB.CreateAdd(
459 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
460 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
461 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000462 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000463 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
464 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
465}
466
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000467void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000468 IRBuilder<> &IRB, Value *Addr,
469 uint32_t TypeSize, bool IsWrite) {
470 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
471
472 Type *ShadowTy = IntegerType::get(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000473 *C, std::max(8U, TypeSize >> MappingScale()));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000474 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
475 Value *ShadowPtr = memToShadow(AddrLong, IRB);
476 Value *CmpVal = Constant::getNullValue(ShadowTy);
477 Value *ShadowValue = IRB.CreateLoad(
478 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
479
480 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000481 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000482 size_t Granularity = 1 << MappingScale();
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000483 TerminatorInst *CrashTerm = 0;
484
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000485 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000486 TerminatorInst *CheckTerm =
487 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000488 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000489 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000490 IRB.SetInsertPoint(CheckTerm);
491 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000492 BasicBlock *CrashBlock =
493 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000494 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000495 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
496 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000497 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000498 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000499 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000500
501 Instruction *Crash =
502 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
503 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000504}
505
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000506void AddressSanitizerModule::createInitializerPoisonCalls(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000507 Module &M, Value *FirstAddr, Value *LastAddr) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000508 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
509 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
510 // If that function is not present, this TU contains no globals, or they have
511 // all been optimized away
512 if (!GlobalInit)
513 return;
514
515 // Set up the arguments to our poison/unpoison functions.
516 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
517
518 // Declare our poisoning and unpoisoning functions.
519 Function *AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
520 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
521 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
522 Function *AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
523 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
524 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
525
526 // Add a call to poison all external globals before the given function starts.
527 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
528
529 // Add calls to unpoison all globals before each return instruction.
530 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
531 I != E; ++I) {
532 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
533 CallInst::Create(AsanUnpoisonGlobals, "", RI);
534 }
535 }
536}
537
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000538bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000539 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000540 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000541
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000542 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000543 if (!Ty->isSized()) return false;
544 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000545 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000546 // Touch only those globals that will not be defined in other modules.
547 // Don't handle ODR type linkages since other modules may be built w/o asan.
548 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
549 G->getLinkage() != GlobalVariable::PrivateLinkage &&
550 G->getLinkage() != GlobalVariable::InternalLinkage)
551 return false;
552 // Two problems with thread-locals:
553 // - The address of the main thread's copy can't be computed at link-time.
554 // - Need to poison all copies, not just the main thread's one.
555 if (G->isThreadLocal())
556 return false;
557 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000558 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000559
560 // Ignore all the globals with the names starting with "\01L_OBJC_".
561 // Many of those are put into the .cstring section. The linker compresses
562 // that section by removing the spare \0s after the string terminator, so
563 // our redzones get broken.
564 if ((G->getName().find("\01L_OBJC_") == 0) ||
565 (G->getName().find("\01l_OBJC_") == 0)) {
566 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
567 return false;
568 }
569
570 if (G->hasSection()) {
571 StringRef Section(G->getSection());
572 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
573 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
574 // them.
575 if ((Section.find("__OBJC,") == 0) ||
576 (Section.find("__DATA, __objc_") == 0)) {
577 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
578 return false;
579 }
580 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
581 // Constant CFString instances are compiled in the following way:
582 // -- the string buffer is emitted into
583 // __TEXT,__cstring,cstring_literals
584 // -- the constant NSConstantString structure referencing that buffer
585 // is placed into __DATA,__cfstring
586 // Therefore there's no point in placing redzones into __DATA,__cfstring.
587 // Moreover, it causes the linker to crash on OS X 10.7
588 if (Section.find("__DATA,__cfstring") == 0) {
589 DEBUG(dbgs() << "Ignoring CFString: " << *G);
590 return false;
591 }
592 }
593
594 return true;
595}
596
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000597// This function replaces all global variables with new variables that have
598// trailing redzones. It also creates a function that poisons
599// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000600bool AddressSanitizerModule::runOnModule(Module &M) {
601 if (!ClGlobals) return false;
602 TD = getAnalysisIfAvailable<DataLayout>();
603 if (!TD)
604 return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000605 BL.reset(new BlackList(ClBlackListFile));
606 DynamicallyInitializedGlobals.Init(M);
607 C = &(M.getContext());
608 IntptrTy = Type::getIntNTy(*C, TD->getPointerSizeInBits());
609
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000610 SmallVector<GlobalVariable *, 16> GlobalsToChange;
611
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000612 for (Module::GlobalListType::iterator G = M.global_begin(),
613 E = M.global_end(); G != E; ++G) {
614 if (ShouldInstrumentGlobal(G))
615 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000616 }
617
618 size_t n = GlobalsToChange.size();
619 if (n == 0) return false;
620
621 // A global is described by a structure
622 // size_t beg;
623 // size_t size;
624 // size_t size_with_redzone;
625 // const char *name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000626 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000627 // We initialize an array of such structures and pass it to a run-time call.
628 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000629 IntptrTy, IntptrTy,
630 IntptrTy, NULL);
631 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000632
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000633
634 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
635 assert(CtorFunc);
636 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000637
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000638 // The addresses of the first and last dynamically initialized globals in
639 // this TU. Used in initialization order checking.
640 Value *FirstDynamic = 0, *LastDynamic = 0;
641
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000642 for (size_t i = 0; i < n; i++) {
643 GlobalVariable *G = GlobalsToChange[i];
644 PointerType *PtrTy = cast<PointerType>(G->getType());
645 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000646 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000647 size_t RZ = RedzoneSize();
648 uint64_t RightRedzoneSize = RZ + (RZ - (SizeInBytes % RZ));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000649 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000650 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000651 bool GlobalHasDynamicInitializer =
652 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000653 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000654 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000655
656 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
657 Constant *NewInitializer = ConstantStruct::get(
658 NewTy, G->getInitializer(),
659 Constant::getNullValue(RightRedZoneTy), NULL);
660
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000661 SmallString<2048> DescriptionOfGlobal = G->getName();
662 DescriptionOfGlobal += " (";
663 DescriptionOfGlobal += M.getModuleIdentifier();
664 DescriptionOfGlobal += ")";
665 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000666
667 // Create a new global variable with enough space for a redzone.
668 GlobalVariable *NewGlobal = new GlobalVariable(
669 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000670 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000671 NewGlobal->copyAttributesFrom(G);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000672 NewGlobal->setAlignment(RZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000673
674 Value *Indices2[2];
675 Indices2[0] = IRB.getInt32(0);
676 Indices2[1] = IRB.getInt32(0);
677
678 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000679 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000680 NewGlobal->takeName(G);
681 G->eraseFromParent();
682
683 Initializers[i] = ConstantStruct::get(
684 GlobalStructTy,
685 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
686 ConstantInt::get(IntptrTy, SizeInBytes),
687 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
688 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000689 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000690 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000691
692 // Populate the first and last globals declared in this TU.
693 if (ClInitializers && GlobalHasDynamicInitializer) {
694 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
695 if (FirstDynamic == 0)
696 FirstDynamic = LastDynamic;
697 }
698
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000699 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000700 }
701
702 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
703 GlobalVariable *AllGlobals = new GlobalVariable(
704 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
705 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
706
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000707 // Create calls for poisoning before initializers run and unpoisoning after.
708 if (ClInitializers && FirstDynamic && LastDynamic)
709 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
710
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000711 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000712 kAsanRegisterGlobalsName, IRB.getVoidTy(),
713 IntptrTy, IntptrTy, NULL));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000714 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
715
716 IRB.CreateCall2(AsanRegisterGlobals,
717 IRB.CreatePointerCast(AllGlobals, IntptrTy),
718 ConstantInt::get(IntptrTy, n));
719
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000720 // We also need to unregister globals at the end, e.g. when a shared library
721 // gets closed.
722 Function *AsanDtorFunction = Function::Create(
723 FunctionType::get(Type::getVoidTy(*C), false),
724 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
725 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
726 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000727 Function *AsanUnregisterGlobals =
728 checkInterfaceFunction(M.getOrInsertFunction(
729 kAsanUnregisterGlobalsName,
730 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000731 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
732
733 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
734 IRB.CreatePointerCast(AllGlobals, IntptrTy),
735 ConstantInt::get(IntptrTy, n));
736 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
737
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000738 DEBUG(dbgs() << M);
739 return true;
740}
741
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000742void AddressSanitizer::initializeCallbacks(Module &M) {
743 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000744 // Create __asan_report* callbacks.
745 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
746 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
747 AccessSizeIndex++) {
748 // IsWrite and TypeSize are encoded in the function name.
749 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
750 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000751 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +0000752 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
753 checkInterfaceFunction(M.getOrInsertFunction(
754 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000755 }
756 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000757
758 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
759 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
760 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
761 kAsanStackFreeName, IRB.getVoidTy(),
762 IntptrTy, IntptrTy, IntptrTy, NULL));
763 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
764 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
765
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000766 // We insert an empty inline asm after __asan_report* to avoid callback merge.
767 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
768 StringRef(""), StringRef(""),
769 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000770}
771
772// virtual
773bool AddressSanitizer::doInitialization(Module &M) {
774 // Initialize the private fields. No one has accessed them before.
775 TD = getAnalysisIfAvailable<DataLayout>();
776
777 if (!TD)
778 return false;
779 BL.reset(new BlackList(ClBlackListFile));
780 DynamicallyInitializedGlobals.Init(M);
781
782 C = &(M.getContext());
783 LongSize = TD->getPointerSizeInBits();
784 IntptrTy = Type::getIntNTy(*C, LongSize);
785 IntptrPtrTy = PointerType::get(IntptrTy, 0);
786
787 AsanCtorFunction = Function::Create(
788 FunctionType::get(Type::getVoidTy(*C), false),
789 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
790 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
791 // call __asan_init in the module ctor.
792 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
793 AsanInitFunction = checkInterfaceFunction(
794 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
795 AsanInitFunction->setLinkage(Function::ExternalLinkage);
796 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000797
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000798 llvm::Triple targetTriple(M.getTargetTriple());
Logan Chien43bf7092012-09-02 09:29:46 +0000799 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000800
801 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
802 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000803 if (ClMappingOffsetLog >= 0) {
804 if (ClMappingOffsetLog == 0) {
805 // special case
806 MappingOffset = 0;
807 } else {
808 MappingOffset = 1ULL << ClMappingOffsetLog;
809 }
810 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000811
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000812
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000813 if (ClMappingOffsetLog >= 0) {
814 // Tell the run-time the current values of mapping offset and scale.
815 GlobalValue *asan_mapping_offset =
816 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
817 ConstantInt::get(IntptrTy, MappingOffset),
818 kAsanMappingOffsetName);
819 // Read the global, otherwise it may be optimized away.
820 IRB.CreateLoad(asan_mapping_offset, true);
821 }
822 if (ClMappingScale) {
823 GlobalValue *asan_mapping_scale =
824 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000825 ConstantInt::get(IntptrTy, MappingScale()),
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000826 kAsanMappingScaleName);
827 // Read the global, otherwise it may be optimized away.
828 IRB.CreateLoad(asan_mapping_scale, true);
829 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000830
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000831 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryany9b027412011-12-12 18:01:46 +0000832
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000833 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000834}
835
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000836bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
837 // For each NSObject descendant having a +load method, this method is invoked
838 // by the ObjC runtime before any of the static constructors is called.
839 // Therefore we need to instrument such methods with a call to __asan_init
840 // at the beginning in order to initialize our runtime before any access to
841 // the shadow memory.
842 // We cannot just ignore these methods, because they may call other
843 // instrumented functions.
844 if (F.getName().find(" load]") != std::string::npos) {
845 IRBuilder<> IRB(F.begin()->begin());
846 IRB.CreateCall(AsanInitFunction);
847 return true;
848 }
849 return false;
850}
851
Kostya Serebryany5085eb82012-11-29 08:57:20 +0000852// Check both the call and the callee for doesNotReturn().
853static bool isNoReturnCall(CallInst *CI) {
854 if (CI->doesNotReturn()) return true;
855 Function *F = CI->getCalledFunction();
856 if (F && F->doesNotReturn()) return true;
857 return false;
858}
859
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000860bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000861 if (BL->isIn(F)) return false;
862 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000863 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000864 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000865
866 // If needed, insert __asan_init before checking for AddressSafety attr.
867 maybeInsertAsanInitAtFunctionEntry(F);
868
Bill Wendling67658342012-10-09 07:45:08 +0000869 if (!F.getFnAttributes().hasAttribute(Attributes::AddressSafety))
870 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000871
872 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
873 return false;
Bill Wendling67658342012-10-09 07:45:08 +0000874
875 // We want to instrument every address only once per basic block (unless there
876 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000877 SmallSet<Value*, 16> TempsToInstrument;
878 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000879 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000880 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000881
882 // Fill the set of memory operations to instrument.
883 for (Function::iterator FI = F.begin(), FE = F.end();
884 FI != FE; ++FI) {
885 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000886 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000887 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
888 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +0000889 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000890 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000891 if (ClOpt && ClOptSameTemp) {
892 if (!TempsToInstrument.insert(Addr))
893 continue; // We've seen this temp in the current BB.
894 }
895 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
896 // ok, take it.
897 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000898 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000899 // A call inside BB.
900 TempsToInstrument.clear();
Kostya Serebryany5085eb82012-11-29 08:57:20 +0000901 if (isNoReturnCall(CI)) {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000902 NoReturnCalls.push_back(CI);
903 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000904 }
905 continue;
906 }
907 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000908 NumInsnsPerBB++;
909 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
910 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000911 }
912 }
913
914 // Instrument.
915 int NumInstrumented = 0;
916 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
917 Instruction *Inst = ToInstrument[i];
918 if (ClDebugMin < 0 || ClDebugMax < 0 ||
919 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000920 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000921 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000922 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000923 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000924 }
925 NumInstrumented++;
926 }
927
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000928 bool ChangedStack = poisonStackInFunction(F);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000929
930 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
931 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
932 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
933 Instruction *CI = NoReturnCalls[i];
934 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000935 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000936 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000937 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000938
939 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000940}
941
942static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
943 if (ShadowRedzoneSize == 1) return PoisonByte;
944 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
945 if (ShadowRedzoneSize == 4)
946 return (PoisonByte << 24) + (PoisonByte << 16) +
947 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +0000948 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000949}
950
951static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
952 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000953 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000954 size_t ShadowGranularity,
955 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000956 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000957 i+= ShadowGranularity, Shadow++) {
958 if (i + ShadowGranularity <= Size) {
959 *Shadow = 0; // fully addressable
960 } else if (i >= Size) {
961 *Shadow = Magic; // unaddressable
962 } else {
963 *Shadow = Size - i; // first Size-i bytes are addressable
964 }
965 }
966}
967
968void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
969 IRBuilder<> IRB,
970 Value *ShadowBase, bool DoPoison) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000971 size_t ShadowRZSize = RedzoneSize() >> MappingScale();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000972 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
973 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
974 Type *RZPtrTy = PointerType::get(RZTy, 0);
975
976 Value *PoisonLeft = ConstantInt::get(RZTy,
977 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
978 Value *PoisonMid = ConstantInt::get(RZTy,
979 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
980 Value *PoisonRight = ConstantInt::get(RZTy,
981 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
982
983 // poison the first red zone.
984 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
985
986 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000987 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000988 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
989 AllocaInst *AI = AllocaVec[i];
990 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
991 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000992 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000993 Value *Ptr = NULL;
994
995 Pos += AlignedSize;
996
997 assert(ShadowBase->getType() == IntptrTy);
998 if (SizeInBytes < AlignedSize) {
999 // Poison the partial redzone at right
1000 Ptr = IRB.CreateAdd(
1001 ShadowBase, ConstantInt::get(IntptrTy,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001002 (Pos >> MappingScale()) - ShadowRZSize));
1003 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001004 uint32_t Poison = 0;
1005 if (DoPoison) {
1006 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001007 RedzoneSize(),
1008 1ULL << MappingScale(),
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001009 kAsanStackPartialRedzoneMagic);
1010 }
1011 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1012 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1013 }
1014
1015 // Poison the full redzone at right.
1016 Ptr = IRB.CreateAdd(ShadowBase,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001017 ConstantInt::get(IntptrTy, Pos >> MappingScale()));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001018 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
1019 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1020
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001021 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001022 }
1023}
1024
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +00001025// Workaround for bug 11395: we don't want to instrument stack in functions
1026// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
Kostya Serebryanyd2703de2011-11-23 02:10:54 +00001027// FIXME: remove once the bug 11395 is fixed.
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +00001028bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1029 if (LongSize != 32) return false;
1030 CallInst *CI = dyn_cast<CallInst>(I);
1031 if (!CI || !CI->isInlineAsm()) return false;
1032 if (CI->getNumArgOperands() <= 5) return false;
1033 // We have inline assembly with quite a few arguments.
1034 return true;
1035}
1036
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001037// Find all static Alloca instructions and put
1038// poisoned red zones around all of them.
1039// Then unpoison everything back before the function returns.
1040//
1041// Stack poisoning does not play well with exception handling.
1042// When an exception is thrown, we essentially bypass the code
1043// that unpoisones the stack. This is why the run-time library has
1044// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
1045// stack in the interceptor. This however does not work inside the
1046// actual function which catches the exception. Most likely because the
1047// compiler hoists the load of the shadow value somewhere too high.
1048// This causes asan to report a non-existing bug on 453.povray.
1049// It sounds like an LLVM bug.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001050bool AddressSanitizer::poisonStackInFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001051 if (!ClStack) return false;
1052 SmallVector<AllocaInst*, 16> AllocaVec;
1053 SmallVector<Instruction*, 8> RetVec;
1054 uint64_t TotalSize = 0;
1055
1056 // Filter out Alloca instructions we want (and can) handle.
1057 // Collect Ret instructions.
1058 for (Function::iterator FI = F.begin(), FE = F.end();
1059 FI != FE; ++FI) {
1060 BasicBlock &BB = *FI;
1061 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
1062 BI != BE; ++BI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001063 if (isa<ReturnInst>(BI)) {
1064 RetVec.push_back(BI);
1065 continue;
1066 }
1067
1068 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
1069 if (!AI) continue;
1070 if (AI->isArrayAllocation()) continue;
1071 if (!AI->isStaticAlloca()) continue;
1072 if (!AI->getAllocatedType()->isSized()) continue;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001073 if (AI->getAlignment() > RedzoneSize()) continue;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001074 AllocaVec.push_back(AI);
1075 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1076 TotalSize += AlignedSize;
1077 }
1078 }
1079
1080 if (AllocaVec.empty()) return false;
1081
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001082 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001083
1084 bool DoStackMalloc = ClUseAfterReturn
1085 && LocalStackSize <= kMaxStackMallocSize;
1086
1087 Instruction *InsBefore = AllocaVec[0];
1088 IRBuilder<> IRB(InsBefore);
1089
1090
1091 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1092 AllocaInst *MyAlloca =
1093 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001094 MyAlloca->setAlignment(RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001095 assert(MyAlloca->isStaticAlloca());
1096 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1097 Value *LocalStackBase = OrigStackBase;
1098
1099 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001100 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1101 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1102 }
1103
1104 // This string will be parsed by the run-time (DescribeStackAddress).
1105 SmallString<2048> StackDescriptionStorage;
1106 raw_svector_ostream StackDescription(StackDescriptionStorage);
1107 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1108
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001109 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001110 // Replace Alloca instructions with base+offset.
1111 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1112 AllocaInst *AI = AllocaVec[i];
1113 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1114 StringRef Name = AI->getName();
1115 StackDescription << Pos << " " << SizeInBytes << " "
1116 << Name.size() << " " << Name << " ";
1117 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001118 assert((AlignedSize % RedzoneSize()) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001119 AI->replaceAllUsesWith(
1120 IRB.CreateIntToPtr(
1121 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1122 AI->getType()));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001123 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001124 }
1125 assert(Pos == LocalStackSize);
1126
1127 // Write the Magic value and the frame description constant to the redzone.
1128 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1129 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1130 BasePlus0);
1131 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1132 ConstantInt::get(IntptrTy, LongSize/8));
1133 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001134 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001135 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001136 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001137 IRB.CreateStore(Description, BasePlus1);
1138
1139 // Poison the stack redzones at the entry.
1140 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1141 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1142
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001143 // Unpoison the stack before all ret instructions.
1144 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1145 Instruction *Ret = RetVec[i];
1146 IRBuilder<> IRBRet(Ret);
1147
1148 // Mark the current frame as retired.
1149 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1150 BasePlus0);
1151 // Unpoison the stack.
1152 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1153
1154 if (DoStackMalloc) {
1155 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1156 ConstantInt::get(IntptrTy, LocalStackSize),
1157 OrigStackBase);
1158 }
1159 }
1160
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001161 // We are done. Remove the old unused alloca instructions.
1162 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1163 AllocaVec[i]->eraseFromParent();
1164
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001165 if (ClDebugStack) {
1166 DEBUG(dbgs() << F);
1167 }
1168
1169 return true;
1170}