blob: a3bf76ef83aa33e1b15b1988624db0e346fed662 [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
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +000019#include "BlackList.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000020#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/OwningPtr.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000026#include "llvm/ADT/Triple.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/DataLayout.h"
28#include "llvm/Function.h"
29#include "llvm/IRBuilder.h"
30#include "llvm/InlineAsm.h"
31#include "llvm/IntrinsicInst.h"
32#include "llvm/LLVMContext.h"
33#include "llvm/Module.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000034#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/DataTypes.h"
36#include "llvm/Support/Debug.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000037#include "llvm/Support/raw_ostream.h"
38#include "llvm/Support/system_error.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000039#include "llvm/Target/TargetMachine.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000040#include "llvm/Transforms/Utils/BasicBlockUtils.h"
41#include "llvm/Transforms/Utils/ModuleUtils.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000042#include "llvm/Type.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000043#include <algorithm>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000044#include <string>
Kostya Serebryany800e03f2011-11-16 01:35:23 +000045
46using namespace llvm;
47
48static const uint64_t kDefaultShadowScale = 3;
49static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
50static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000051static const uint64_t kDefaultShadowOffsetAndroid = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000052
53static const size_t kMaxStackMallocSize = 1 << 16; // 64K
54static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
55static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
56
57static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000058static const char *kAsanModuleDtorName = "asan.module_dtor";
59static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000060static const char *kAsanReportErrorTemplate = "__asan_report_";
61static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000062static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +000063static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
64static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000065static const char *kAsanInitName = "__asan_init";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000066static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000067static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
68static const char *kAsanMappingScaleName = "__asan_mapping_scale";
69static const char *kAsanStackMallocName = "__asan_stack_malloc";
70static const char *kAsanStackFreeName = "__asan_stack_free";
Kostya Serebryany51c7c652012-11-20 14:16:08 +000071static const char *kAsanGenPrefix = "__asan_gen_";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000072
73static const int kAsanStackLeftRedzoneMagic = 0xf1;
74static const int kAsanStackMidRedzoneMagic = 0xf2;
75static const int kAsanStackRightRedzoneMagic = 0xf3;
76static const int kAsanStackPartialRedzoneMagic = 0xf4;
77
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000078// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
79static const size_t kNumberOfAccessSizes = 5;
80
Kostya Serebryany800e03f2011-11-16 01:35:23 +000081// Command-line flags.
82
83// This flag may need to be replaced with -f[no-]asan-reads.
84static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
85 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
86static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
87 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000088static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
89 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
90 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +000091static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
92 cl::desc("use instrumentation with slow path for all accesses"),
93 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000094// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +000095// in any given BB. Normally, this should be set to unlimited (INT_MAX),
96// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
97// set it to 10000.
98static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
99 cl::init(10000),
100 cl::desc("maximal number of instructions to instrument in any given BB"),
101 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000102// This flag may need to be replaced with -f[no]asan-stack.
103static cl::opt<bool> ClStack("asan-stack",
104 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
105// This flag may need to be replaced with -f[no]asan-use-after-return.
106static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
107 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
108// This flag may need to be replaced with -f[no]asan-globals.
109static cl::opt<bool> ClGlobals("asan-globals",
110 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000111static cl::opt<bool> ClInitializers("asan-initialization-order",
112 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000113static cl::opt<bool> ClMemIntrin("asan-memintrin",
114 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
115// This flag may need to be replaced with -fasan-blacklist.
116static cl::opt<std::string> ClBlackListFile("asan-blacklist",
117 cl::desc("File containing the list of functions to ignore "
118 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000119
120// These flags allow to change the shadow mapping.
121// The shadow mapping looks like
122// Shadow = (Mem >> scale) + (1 << offset_log)
123static cl::opt<int> ClMappingScale("asan-mapping-scale",
124 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
125static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
126 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
127
128// Optimization flags. Not user visible, used mostly for testing
129// and benchmarking the tool.
130static cl::opt<bool> ClOpt("asan-opt",
131 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
132static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
133 cl::desc("Instrument the same temp just once"), cl::Hidden,
134 cl::init(true));
135static cl::opt<bool> ClOptGlobals("asan-opt-globals",
136 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
137
Alexey Samsonovee548272012-11-29 18:14:24 +0000138static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
139 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
140 cl::Hidden, cl::init(false));
141
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000142// Debug flags.
143static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
144 cl::init(0));
145static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
146 cl::Hidden, cl::init(0));
147static cl::opt<std::string> ClDebugFunc("asan-debug-func",
148 cl::Hidden, cl::desc("Debug func"));
149static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
150 cl::Hidden, cl::init(-1));
151static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
152 cl::Hidden, cl::init(-1));
153
154namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000155/// A set of dynamically initialized globals extracted from metadata.
156class SetOfDynamicallyInitializedGlobals {
157 public:
158 void Init(Module& M) {
159 // Clang generates metadata identifying all dynamically initialized globals.
160 NamedMDNode *DynamicGlobals =
161 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
162 if (!DynamicGlobals)
163 return;
164 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
165 MDNode *MDN = DynamicGlobals->getOperand(i);
166 assert(MDN->getNumOperands() == 1);
167 Value *VG = MDN->getOperand(0);
168 // The optimizer may optimize away a global entirely, in which case we
169 // cannot instrument access to it.
170 if (!VG)
171 continue;
172 DynInitGlobals.insert(cast<GlobalVariable>(VG));
173 }
174 }
175 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
176 private:
177 SmallSet<GlobalValue*, 32> DynInitGlobals;
178};
179
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000180static int MappingScale() {
181 return ClMappingScale ? ClMappingScale : kDefaultShadowScale;
182}
183
184static size_t RedzoneSize() {
185 // Redzone used for stack and globals is at least 32 bytes.
186 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
187 return std::max(32U, 1U << MappingScale());
188}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000189
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000190/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000191struct AddressSanitizer : public FunctionPass {
Alexey Samsonovee548272012-11-29 18:14:24 +0000192 AddressSanitizer(bool CheckInitOrder = false,
193 bool CheckUseAfterReturn = false,
194 bool CheckLifetime = false)
195 : FunctionPass(ID),
196 CheckInitOrder(CheckInitOrder || ClInitializers),
197 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
198 CheckLifetime(CheckLifetime || ClCheckLifetime) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000199 virtual const char *getPassName() const {
200 return "AddressSanitizerFunctionPass";
201 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000202 void instrumentMop(Instruction *I);
203 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000204 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000205 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
206 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000207 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000208 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000209 bool instrumentMemIntrinsic(MemIntrinsic *MI);
210 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000211 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000212 Instruction *InsertBefore, bool IsWrite);
213 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000214 bool runOnFunction(Function &F);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000215 void createInitializerPoisonCalls(Module &M,
216 Value *FirstAddr, Value *LastAddr);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000217 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000218 bool poisonStackInFunction(Function &F);
219 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000220 static char ID; // Pass identification, replacement for typeid
221
222 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000223 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000224 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
225 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanovd8313be2012-03-02 10:41:08 +0000226 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000227 return SizeInBytes;
228 }
229 uint64_t getAlignedSize(uint64_t SizeInBytes) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000230 size_t RZ = RedzoneSize();
231 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000232 }
233 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
234 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
235 return getAlignedSize(SizeInBytes);
236 }
237
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000238 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000239 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
240 Value *ShadowBase, bool DoPoison);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000241 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000242 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000243
Alexey Samsonovee548272012-11-29 18:14:24 +0000244 bool CheckInitOrder;
245 bool CheckUseAfterReturn;
246 bool CheckLifetime;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000247 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000248 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000249 uint64_t MappingOffset;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000250 int LongSize;
251 Type *IntptrTy;
252 Type *IntptrPtrTy;
253 Function *AsanCtorFunction;
254 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000255 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
256 Function *AsanHandleNoReturnFunc;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000257 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000258 // This array is indexed by AccessIsWrite and log2(AccessSize).
259 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000260 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000261 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000262};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000263
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000264class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000265 public:
Alexey Samsonovee548272012-11-29 18:14:24 +0000266 AddressSanitizerModule(bool CheckInitOrder = false)
267 : ModulePass(ID),
268 CheckInitOrder(CheckInitOrder || ClInitializers) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000269 bool runOnModule(Module &M);
270 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000271 virtual const char *getPassName() const {
272 return "AddressSanitizerModule";
273 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000274 private:
275 bool ShouldInstrumentGlobal(GlobalVariable *G);
276 void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
277 Value *LastAddr);
278
Alexey Samsonovee548272012-11-29 18:14:24 +0000279 bool CheckInitOrder;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000280 OwningPtr<BlackList> BL;
281 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
282 Type *IntptrTy;
283 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000284 DataLayout *TD;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000285};
286
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000287} // namespace
288
289char AddressSanitizer::ID = 0;
290INITIALIZE_PASS(AddressSanitizer, "asan",
291 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
292 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000293FunctionPass *llvm::createAddressSanitizerFunctionPass(
294 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime) {
295 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
296 CheckLifetime);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000297}
298
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000299char AddressSanitizerModule::ID = 0;
300INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
301 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
302 "ModulePass", false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000303ModulePass *llvm::createAddressSanitizerModulePass(bool CheckInitOrder) {
304 return new AddressSanitizerModule(CheckInitOrder);
Alexander Potapenko25878042012-01-23 11:22:43 +0000305}
306
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000307static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
308 size_t Res = CountTrailingZeros_32(TypeSize / 8);
309 assert(Res < kNumberOfAccessSizes);
310 return Res;
311}
312
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000313// Create a constant for Str so that we can pass it to the run-time lib.
314static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000315 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000316 return new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000317 GlobalValue::PrivateLinkage, StrConst,
318 kAsanGenPrefix);
319}
320
321static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
322 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000323}
324
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000325Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
326 // Shadow >> scale
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000327 Shadow = IRB.CreateLShr(Shadow, MappingScale());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000328 if (MappingOffset == 0)
329 return Shadow;
330 // (Shadow >> scale) | offset
331 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
332 MappingOffset));
333}
334
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000335void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000336 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000337 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
338 // Check the first byte.
339 {
340 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000341 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000342 }
343 // Check the last byte.
344 {
345 IRBuilder<> IRB(InsertBefore);
346 Value *SizeMinusOne = IRB.CreateSub(
347 Size, ConstantInt::get(Size->getType(), 1));
348 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
349 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
350 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000351 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000352 }
353}
354
355// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000356bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000357 Value *Dst = MI->getDest();
358 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000359 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000360 Value *Length = MI->getLength();
361
362 Constant *ConstLength = dyn_cast<Constant>(Length);
363 Instruction *InsertBefore = MI;
364 if (ConstLength) {
365 if (ConstLength->isNullValue()) return false;
366 } else {
367 // The size is not a constant so it could be zero -- check at run-time.
368 IRBuilder<> IRB(InsertBefore);
369
370 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000371 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000372 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000373 }
374
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000375 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000376 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000377 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000378 return true;
379}
380
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000381// If I is an interesting memory access, return the PointerOperand
382// and set IsWrite. Otherwise return NULL.
383static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000384 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000385 if (!ClInstrumentReads) return NULL;
386 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000387 return LI->getPointerOperand();
388 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000389 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
390 if (!ClInstrumentWrites) return NULL;
391 *IsWrite = true;
392 return SI->getPointerOperand();
393 }
394 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
395 if (!ClInstrumentAtomics) return NULL;
396 *IsWrite = true;
397 return RMW->getPointerOperand();
398 }
399 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
400 if (!ClInstrumentAtomics) return NULL;
401 *IsWrite = true;
402 return XCHG->getPointerOperand();
403 }
404 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000405}
406
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000407void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000408 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000409 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
410 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000411 if (ClOpt && ClOptGlobals) {
412 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
413 // If initialization order checking is disabled, a simple access to a
414 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000415 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000416 return;
417 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000418 // have to instrument it. However, if a global does not have initailizer
419 // at all, we assume it has dynamic initializer (in other TU).
420 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000421 return;
422 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000423 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000424
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000425 Type *OrigPtrTy = Addr->getType();
426 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
427
428 assert(OrigTy->isSized());
429 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
430
431 if (TypeSize != 8 && TypeSize != 16 &&
432 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
433 // Ignore all unusual sizes.
434 return;
435 }
436
437 IRBuilder<> IRB(I);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000438 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000439}
440
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000441// Validate the result of Module::getOrInsertFunction called for an interface
442// function of AddressSanitizer. If the instrumented module defines a function
443// with the same name, their prototypes must match, otherwise
444// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000445static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000446 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
447 FuncOrBitcast->dump();
448 report_fatal_error("trying to redefine an AddressSanitizer "
449 "interface function");
450}
451
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000452Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000453 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000454 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000455 IRBuilder<> IRB(InsertBefore);
456 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
457 Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000458 // We don't do Call->setDoesNotReturn() because the BB already has
459 // UnreachableInst at the end.
460 // This EmptyAsm is required to avoid callback merge.
461 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000462 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000463}
464
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000465Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000466 Value *ShadowValue,
467 uint32_t TypeSize) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000468 size_t Granularity = 1 << MappingScale();
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000469 // Addr & (Granularity - 1)
470 Value *LastAccessedByte = IRB.CreateAnd(
471 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
472 // (Addr & (Granularity - 1)) + size - 1
473 if (TypeSize / 8 > 1)
474 LastAccessedByte = IRB.CreateAdd(
475 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
476 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
477 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000478 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000479 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
480 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
481}
482
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000483void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000484 IRBuilder<> &IRB, Value *Addr,
485 uint32_t TypeSize, bool IsWrite) {
486 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
487
488 Type *ShadowTy = IntegerType::get(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000489 *C, std::max(8U, TypeSize >> MappingScale()));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000490 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
491 Value *ShadowPtr = memToShadow(AddrLong, IRB);
492 Value *CmpVal = Constant::getNullValue(ShadowTy);
493 Value *ShadowValue = IRB.CreateLoad(
494 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
495
496 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000497 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000498 size_t Granularity = 1 << MappingScale();
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000499 TerminatorInst *CrashTerm = 0;
500
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000501 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000502 TerminatorInst *CheckTerm =
503 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000504 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000505 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000506 IRB.SetInsertPoint(CheckTerm);
507 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000508 BasicBlock *CrashBlock =
509 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000510 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000511 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
512 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000513 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000514 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000515 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000516
517 Instruction *Crash =
518 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
519 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000520}
521
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000522void AddressSanitizerModule::createInitializerPoisonCalls(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000523 Module &M, Value *FirstAddr, Value *LastAddr) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000524 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
525 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
526 // If that function is not present, this TU contains no globals, or they have
527 // all been optimized away
528 if (!GlobalInit)
529 return;
530
531 // Set up the arguments to our poison/unpoison functions.
532 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
533
534 // Declare our poisoning and unpoisoning functions.
535 Function *AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
536 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
537 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
538 Function *AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
539 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
540 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
541
542 // Add a call to poison all external globals before the given function starts.
543 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
544
545 // Add calls to unpoison all globals before each return instruction.
546 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
547 I != E; ++I) {
548 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
549 CallInst::Create(AsanUnpoisonGlobals, "", RI);
550 }
551 }
552}
553
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000554bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000555 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000556 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000557
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000558 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000559 if (!Ty->isSized()) return false;
560 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000561 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000562 // Touch only those globals that will not be defined in other modules.
563 // Don't handle ODR type linkages since other modules may be built w/o asan.
564 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
565 G->getLinkage() != GlobalVariable::PrivateLinkage &&
566 G->getLinkage() != GlobalVariable::InternalLinkage)
567 return false;
568 // Two problems with thread-locals:
569 // - The address of the main thread's copy can't be computed at link-time.
570 // - Need to poison all copies, not just the main thread's one.
571 if (G->isThreadLocal())
572 return false;
573 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000574 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000575
576 // Ignore all the globals with the names starting with "\01L_OBJC_".
577 // Many of those are put into the .cstring section. The linker compresses
578 // that section by removing the spare \0s after the string terminator, so
579 // our redzones get broken.
580 if ((G->getName().find("\01L_OBJC_") == 0) ||
581 (G->getName().find("\01l_OBJC_") == 0)) {
582 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
583 return false;
584 }
585
586 if (G->hasSection()) {
587 StringRef Section(G->getSection());
588 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
589 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
590 // them.
591 if ((Section.find("__OBJC,") == 0) ||
592 (Section.find("__DATA, __objc_") == 0)) {
593 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
594 return false;
595 }
596 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
597 // Constant CFString instances are compiled in the following way:
598 // -- the string buffer is emitted into
599 // __TEXT,__cstring,cstring_literals
600 // -- the constant NSConstantString structure referencing that buffer
601 // is placed into __DATA,__cfstring
602 // Therefore there's no point in placing redzones into __DATA,__cfstring.
603 // Moreover, it causes the linker to crash on OS X 10.7
604 if (Section.find("__DATA,__cfstring") == 0) {
605 DEBUG(dbgs() << "Ignoring CFString: " << *G);
606 return false;
607 }
608 }
609
610 return true;
611}
612
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000613// This function replaces all global variables with new variables that have
614// trailing redzones. It also creates a function that poisons
615// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000616bool AddressSanitizerModule::runOnModule(Module &M) {
617 if (!ClGlobals) return false;
618 TD = getAnalysisIfAvailable<DataLayout>();
619 if (!TD)
620 return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000621 BL.reset(new BlackList(ClBlackListFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000622 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000623 DynamicallyInitializedGlobals.Init(M);
624 C = &(M.getContext());
625 IntptrTy = Type::getIntNTy(*C, TD->getPointerSizeInBits());
626
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000627 SmallVector<GlobalVariable *, 16> GlobalsToChange;
628
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000629 for (Module::GlobalListType::iterator G = M.global_begin(),
630 E = M.global_end(); G != E; ++G) {
631 if (ShouldInstrumentGlobal(G))
632 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000633 }
634
635 size_t n = GlobalsToChange.size();
636 if (n == 0) return false;
637
638 // A global is described by a structure
639 // size_t beg;
640 // size_t size;
641 // size_t size_with_redzone;
642 // const char *name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000643 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000644 // We initialize an array of such structures and pass it to a run-time call.
645 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000646 IntptrTy, IntptrTy,
647 IntptrTy, NULL);
648 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000649
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000650
651 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
652 assert(CtorFunc);
653 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000654
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000655 // The addresses of the first and last dynamically initialized globals in
656 // this TU. Used in initialization order checking.
657 Value *FirstDynamic = 0, *LastDynamic = 0;
658
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000659 for (size_t i = 0; i < n; i++) {
660 GlobalVariable *G = GlobalsToChange[i];
661 PointerType *PtrTy = cast<PointerType>(G->getType());
662 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000663 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000664 size_t RZ = RedzoneSize();
665 uint64_t RightRedzoneSize = RZ + (RZ - (SizeInBytes % RZ));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000666 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000667 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000668 bool GlobalHasDynamicInitializer =
669 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000670 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000671 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000672
673 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
674 Constant *NewInitializer = ConstantStruct::get(
675 NewTy, G->getInitializer(),
676 Constant::getNullValue(RightRedZoneTy), NULL);
677
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000678 SmallString<2048> DescriptionOfGlobal = G->getName();
679 DescriptionOfGlobal += " (";
680 DescriptionOfGlobal += M.getModuleIdentifier();
681 DescriptionOfGlobal += ")";
682 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000683
684 // Create a new global variable with enough space for a redzone.
685 GlobalVariable *NewGlobal = new GlobalVariable(
686 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000687 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000688 NewGlobal->copyAttributesFrom(G);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000689 NewGlobal->setAlignment(RZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000690
691 Value *Indices2[2];
692 Indices2[0] = IRB.getInt32(0);
693 Indices2[1] = IRB.getInt32(0);
694
695 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000696 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000697 NewGlobal->takeName(G);
698 G->eraseFromParent();
699
700 Initializers[i] = ConstantStruct::get(
701 GlobalStructTy,
702 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
703 ConstantInt::get(IntptrTy, SizeInBytes),
704 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
705 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000706 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000707 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000708
709 // Populate the first and last globals declared in this TU.
Alexey Samsonovee548272012-11-29 18:14:24 +0000710 if (CheckInitOrder && GlobalHasDynamicInitializer) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000711 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
712 if (FirstDynamic == 0)
713 FirstDynamic = LastDynamic;
714 }
715
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000716 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000717 }
718
719 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
720 GlobalVariable *AllGlobals = new GlobalVariable(
721 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
722 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
723
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000724 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovee548272012-11-29 18:14:24 +0000725 if (CheckInitOrder && FirstDynamic && LastDynamic)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000726 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
727
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000728 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000729 kAsanRegisterGlobalsName, IRB.getVoidTy(),
730 IntptrTy, IntptrTy, NULL));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000731 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
732
733 IRB.CreateCall2(AsanRegisterGlobals,
734 IRB.CreatePointerCast(AllGlobals, IntptrTy),
735 ConstantInt::get(IntptrTy, n));
736
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000737 // We also need to unregister globals at the end, e.g. when a shared library
738 // gets closed.
739 Function *AsanDtorFunction = Function::Create(
740 FunctionType::get(Type::getVoidTy(*C), false),
741 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
742 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
743 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000744 Function *AsanUnregisterGlobals =
745 checkInterfaceFunction(M.getOrInsertFunction(
746 kAsanUnregisterGlobalsName,
747 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000748 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
749
750 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
751 IRB.CreatePointerCast(AllGlobals, IntptrTy),
752 ConstantInt::get(IntptrTy, n));
753 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
754
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000755 DEBUG(dbgs() << M);
756 return true;
757}
758
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000759void AddressSanitizer::initializeCallbacks(Module &M) {
760 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000761 // Create __asan_report* callbacks.
762 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
763 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
764 AccessSizeIndex++) {
765 // IsWrite and TypeSize are encoded in the function name.
766 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
767 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000768 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +0000769 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
770 checkInterfaceFunction(M.getOrInsertFunction(
771 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000772 }
773 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000774
775 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
776 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
777 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
778 kAsanStackFreeName, IRB.getVoidTy(),
779 IntptrTy, IntptrTy, IntptrTy, NULL));
780 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
781 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
782
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000783 // We insert an empty inline asm after __asan_report* to avoid callback merge.
784 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
785 StringRef(""), StringRef(""),
786 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000787}
788
789// virtual
790bool AddressSanitizer::doInitialization(Module &M) {
791 // Initialize the private fields. No one has accessed them before.
792 TD = getAnalysisIfAvailable<DataLayout>();
793
794 if (!TD)
795 return false;
796 BL.reset(new BlackList(ClBlackListFile));
797 DynamicallyInitializedGlobals.Init(M);
798
799 C = &(M.getContext());
800 LongSize = TD->getPointerSizeInBits();
801 IntptrTy = Type::getIntNTy(*C, LongSize);
802 IntptrPtrTy = PointerType::get(IntptrTy, 0);
803
804 AsanCtorFunction = Function::Create(
805 FunctionType::get(Type::getVoidTy(*C), false),
806 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
807 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
808 // call __asan_init in the module ctor.
809 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
810 AsanInitFunction = checkInterfaceFunction(
811 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
812 AsanInitFunction->setLinkage(Function::ExternalLinkage);
813 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000814
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000815 llvm::Triple targetTriple(M.getTargetTriple());
Logan Chien43bf7092012-09-02 09:29:46 +0000816 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000817
818 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
819 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000820 if (ClMappingOffsetLog >= 0) {
821 if (ClMappingOffsetLog == 0) {
822 // special case
823 MappingOffset = 0;
824 } else {
825 MappingOffset = 1ULL << ClMappingOffsetLog;
826 }
827 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000828
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000829
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000830 if (ClMappingOffsetLog >= 0) {
831 // Tell the run-time the current values of mapping offset and scale.
832 GlobalValue *asan_mapping_offset =
833 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
834 ConstantInt::get(IntptrTy, MappingOffset),
835 kAsanMappingOffsetName);
836 // Read the global, otherwise it may be optimized away.
837 IRB.CreateLoad(asan_mapping_offset, true);
838 }
839 if (ClMappingScale) {
840 GlobalValue *asan_mapping_scale =
841 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000842 ConstantInt::get(IntptrTy, MappingScale()),
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000843 kAsanMappingScaleName);
844 // Read the global, otherwise it may be optimized away.
845 IRB.CreateLoad(asan_mapping_scale, true);
846 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000847
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000848 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryany9b027412011-12-12 18:01:46 +0000849
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000850 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000851}
852
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000853bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
854 // For each NSObject descendant having a +load method, this method is invoked
855 // by the ObjC runtime before any of the static constructors is called.
856 // Therefore we need to instrument such methods with a call to __asan_init
857 // at the beginning in order to initialize our runtime before any access to
858 // the shadow memory.
859 // We cannot just ignore these methods, because they may call other
860 // instrumented functions.
861 if (F.getName().find(" load]") != std::string::npos) {
862 IRBuilder<> IRB(F.begin()->begin());
863 IRB.CreateCall(AsanInitFunction);
864 return true;
865 }
866 return false;
867}
868
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000869bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000870 if (BL->isIn(F)) return false;
871 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000872 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000873 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000874
875 // If needed, insert __asan_init before checking for AddressSafety attr.
876 maybeInsertAsanInitAtFunctionEntry(F);
877
Bill Wendling67658342012-10-09 07:45:08 +0000878 if (!F.getFnAttributes().hasAttribute(Attributes::AddressSafety))
879 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000880
881 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
882 return false;
Bill Wendling67658342012-10-09 07:45:08 +0000883
884 // We want to instrument every address only once per basic block (unless there
885 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000886 SmallSet<Value*, 16> TempsToInstrument;
887 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000888 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000889 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000890
891 // Fill the set of memory operations to instrument.
892 for (Function::iterator FI = F.begin(), FE = F.end();
893 FI != FE; ++FI) {
894 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000895 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000896 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
897 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +0000898 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000899 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000900 if (ClOpt && ClOptSameTemp) {
901 if (!TempsToInstrument.insert(Addr))
902 continue; // We've seen this temp in the current BB.
903 }
904 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
905 // ok, take it.
906 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000907 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000908 // A call inside BB.
909 TempsToInstrument.clear();
Kostya Serebryanya17babb2012-11-30 11:08:59 +0000910 if (CI->doesNotReturn()) {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000911 NoReturnCalls.push_back(CI);
912 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000913 }
914 continue;
915 }
916 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000917 NumInsnsPerBB++;
918 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
919 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000920 }
921 }
922
923 // Instrument.
924 int NumInstrumented = 0;
925 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
926 Instruction *Inst = ToInstrument[i];
927 if (ClDebugMin < 0 || ClDebugMax < 0 ||
928 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000929 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000930 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000931 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000932 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000933 }
934 NumInstrumented++;
935 }
936
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000937 bool ChangedStack = poisonStackInFunction(F);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000938
939 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
940 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
941 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
942 Instruction *CI = NoReturnCalls[i];
943 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000944 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000945 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000946 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000947
948 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000949}
950
951static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
952 if (ShadowRedzoneSize == 1) return PoisonByte;
953 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
954 if (ShadowRedzoneSize == 4)
955 return (PoisonByte << 24) + (PoisonByte << 16) +
956 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +0000957 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000958}
959
960static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
961 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000962 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000963 size_t ShadowGranularity,
964 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000965 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000966 i+= ShadowGranularity, Shadow++) {
967 if (i + ShadowGranularity <= Size) {
968 *Shadow = 0; // fully addressable
969 } else if (i >= Size) {
970 *Shadow = Magic; // unaddressable
971 } else {
972 *Shadow = Size - i; // first Size-i bytes are addressable
973 }
974 }
975}
976
977void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
978 IRBuilder<> IRB,
979 Value *ShadowBase, bool DoPoison) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000980 size_t ShadowRZSize = RedzoneSize() >> MappingScale();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000981 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
982 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
983 Type *RZPtrTy = PointerType::get(RZTy, 0);
984
985 Value *PoisonLeft = ConstantInt::get(RZTy,
986 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
987 Value *PoisonMid = ConstantInt::get(RZTy,
988 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
989 Value *PoisonRight = ConstantInt::get(RZTy,
990 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
991
992 // poison the first red zone.
993 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
994
995 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000996 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000997 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
998 AllocaInst *AI = AllocaVec[i];
999 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1000 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001001 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001002 Value *Ptr = NULL;
1003
1004 Pos += AlignedSize;
1005
1006 assert(ShadowBase->getType() == IntptrTy);
1007 if (SizeInBytes < AlignedSize) {
1008 // Poison the partial redzone at right
1009 Ptr = IRB.CreateAdd(
1010 ShadowBase, ConstantInt::get(IntptrTy,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001011 (Pos >> MappingScale()) - ShadowRZSize));
1012 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001013 uint32_t Poison = 0;
1014 if (DoPoison) {
1015 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001016 RedzoneSize(),
1017 1ULL << MappingScale(),
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001018 kAsanStackPartialRedzoneMagic);
1019 }
1020 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1021 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1022 }
1023
1024 // Poison the full redzone at right.
1025 Ptr = IRB.CreateAdd(ShadowBase,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001026 ConstantInt::get(IntptrTy, Pos >> MappingScale()));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001027 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
1028 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1029
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001030 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001031 }
1032}
1033
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +00001034// Workaround for bug 11395: we don't want to instrument stack in functions
1035// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
Kostya Serebryanyd2703de2011-11-23 02:10:54 +00001036// FIXME: remove once the bug 11395 is fixed.
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +00001037bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1038 if (LongSize != 32) return false;
1039 CallInst *CI = dyn_cast<CallInst>(I);
1040 if (!CI || !CI->isInlineAsm()) return false;
1041 if (CI->getNumArgOperands() <= 5) return false;
1042 // We have inline assembly with quite a few arguments.
1043 return true;
1044}
1045
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001046// Find all static Alloca instructions and put
1047// poisoned red zones around all of them.
1048// Then unpoison everything back before the function returns.
1049//
1050// Stack poisoning does not play well with exception handling.
1051// When an exception is thrown, we essentially bypass the code
1052// that unpoisones the stack. This is why the run-time library has
1053// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
1054// stack in the interceptor. This however does not work inside the
1055// actual function which catches the exception. Most likely because the
1056// compiler hoists the load of the shadow value somewhere too high.
1057// This causes asan to report a non-existing bug on 453.povray.
1058// It sounds like an LLVM bug.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001059bool AddressSanitizer::poisonStackInFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001060 if (!ClStack) return false;
1061 SmallVector<AllocaInst*, 16> AllocaVec;
1062 SmallVector<Instruction*, 8> RetVec;
1063 uint64_t TotalSize = 0;
1064
1065 // Filter out Alloca instructions we want (and can) handle.
1066 // Collect Ret instructions.
1067 for (Function::iterator FI = F.begin(), FE = F.end();
1068 FI != FE; ++FI) {
1069 BasicBlock &BB = *FI;
1070 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
1071 BI != BE; ++BI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001072 if (isa<ReturnInst>(BI)) {
1073 RetVec.push_back(BI);
1074 continue;
1075 }
1076
1077 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
1078 if (!AI) continue;
1079 if (AI->isArrayAllocation()) continue;
1080 if (!AI->isStaticAlloca()) continue;
1081 if (!AI->getAllocatedType()->isSized()) continue;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001082 if (AI->getAlignment() > RedzoneSize()) continue;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001083 AllocaVec.push_back(AI);
1084 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1085 TotalSize += AlignedSize;
1086 }
1087 }
1088
1089 if (AllocaVec.empty()) return false;
1090
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001091 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001092
Alexey Samsonovee548272012-11-29 18:14:24 +00001093 bool DoStackMalloc = CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001094 && LocalStackSize <= kMaxStackMallocSize;
1095
1096 Instruction *InsBefore = AllocaVec[0];
1097 IRBuilder<> IRB(InsBefore);
1098
1099
1100 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1101 AllocaInst *MyAlloca =
1102 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001103 MyAlloca->setAlignment(RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001104 assert(MyAlloca->isStaticAlloca());
1105 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1106 Value *LocalStackBase = OrigStackBase;
1107
1108 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001109 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1110 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1111 }
1112
1113 // This string will be parsed by the run-time (DescribeStackAddress).
1114 SmallString<2048> StackDescriptionStorage;
1115 raw_svector_ostream StackDescription(StackDescriptionStorage);
1116 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1117
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001118 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001119 // Replace Alloca instructions with base+offset.
1120 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1121 AllocaInst *AI = AllocaVec[i];
1122 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1123 StringRef Name = AI->getName();
1124 StackDescription << Pos << " " << SizeInBytes << " "
1125 << Name.size() << " " << Name << " ";
1126 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001127 assert((AlignedSize % RedzoneSize()) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001128 AI->replaceAllUsesWith(
1129 IRB.CreateIntToPtr(
1130 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1131 AI->getType()));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001132 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001133 }
1134 assert(Pos == LocalStackSize);
1135
1136 // Write the Magic value and the frame description constant to the redzone.
1137 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1138 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1139 BasePlus0);
1140 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1141 ConstantInt::get(IntptrTy, LongSize/8));
1142 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001143 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001144 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001145 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001146 IRB.CreateStore(Description, BasePlus1);
1147
1148 // Poison the stack redzones at the entry.
1149 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1150 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1151
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001152 // Unpoison the stack before all ret instructions.
1153 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1154 Instruction *Ret = RetVec[i];
1155 IRBuilder<> IRBRet(Ret);
1156
1157 // Mark the current frame as retired.
1158 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1159 BasePlus0);
1160 // Unpoison the stack.
1161 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1162
1163 if (DoStackMalloc) {
1164 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1165 ConstantInt::get(IntptrTy, LocalStackSize),
1166 OrigStackBase);
1167 }
1168 }
1169
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001170 // We are done. Remove the old unused alloca instructions.
1171 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1172 AllocaVec[i]->eraseFromParent();
1173
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001174 if (ClDebugStack) {
1175 DEBUG(dbgs() << F);
1176 }
1177
1178 return true;
1179}