blob: 25ca1659c6b73dd37eb6bdcea545e91eee52f74e [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"
Alexey Samsonov1c8b8252012-12-27 08:50:58 +000021#include "llvm/ADT/DenseMap.h"
Alexey Samsonov59cca132012-12-25 12:04:36 +000022#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000023#include "llvm/ADT/OwningPtr.h"
24#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/SmallString.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000028#include "llvm/ADT/Triple.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000029#include "llvm/DIBuilder.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/InlineAsm.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Module.h"
37#include "llvm/IR/Type.h"
Alexey Samsonov59cca132012-12-25 12:04:36 +000038#include "llvm/InstVisitor.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000039#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/DataTypes.h"
41#include "llvm/Support/Debug.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000042#include "llvm/Support/raw_ostream.h"
43#include "llvm/Support/system_error.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000044#include "llvm/Target/TargetMachine.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000046#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000047#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000048#include <algorithm>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000049#include <string>
Kostya Serebryany800e03f2011-11-16 01:35:23 +000050
51using namespace llvm;
52
53static const uint64_t kDefaultShadowScale = 3;
54static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
55static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +000056static const uint64_t kDefaultShadowOffsetPie = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000057
58static const size_t kMaxStackMallocSize = 1 << 16; // 64K
59static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
60static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
61
62static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000063static const char *kAsanModuleDtorName = "asan.module_dtor";
64static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000065static const char *kAsanReportErrorTemplate = "__asan_report_";
66static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000067static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +000068static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
69static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000070static const char *kAsanInitName = "__asan_init";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000071static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000072static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
73static const char *kAsanMappingScaleName = "__asan_mapping_scale";
74static const char *kAsanStackMallocName = "__asan_stack_malloc";
75static const char *kAsanStackFreeName = "__asan_stack_free";
Kostya Serebryany51c7c652012-11-20 14:16:08 +000076static const char *kAsanGenPrefix = "__asan_gen_";
Alexey Samsonovf985f442012-12-04 01:34:23 +000077static const char *kAsanPoisonStackMemoryName = "__asan_poison_stack_memory";
78static const char *kAsanUnpoisonStackMemoryName =
79 "__asan_unpoison_stack_memory";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000080
81static const int kAsanStackLeftRedzoneMagic = 0xf1;
82static const int kAsanStackMidRedzoneMagic = 0xf2;
83static const int kAsanStackRightRedzoneMagic = 0xf3;
84static const int kAsanStackPartialRedzoneMagic = 0xf4;
85
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000086// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
87static const size_t kNumberOfAccessSizes = 5;
88
Kostya Serebryany800e03f2011-11-16 01:35:23 +000089// Command-line flags.
90
91// This flag may need to be replaced with -f[no-]asan-reads.
92static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
93 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
94static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
95 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000096static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
97 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
98 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +000099static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
100 cl::desc("use instrumentation with slow path for all accesses"),
101 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000102// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000103// in any given BB. Normally, this should be set to unlimited (INT_MAX),
104// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
105// set it to 10000.
106static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
107 cl::init(10000),
108 cl::desc("maximal number of instructions to instrument in any given BB"),
109 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000110// This flag may need to be replaced with -f[no]asan-stack.
111static cl::opt<bool> ClStack("asan-stack",
112 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
113// This flag may need to be replaced with -f[no]asan-use-after-return.
114static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
115 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
116// This flag may need to be replaced with -f[no]asan-globals.
117static cl::opt<bool> ClGlobals("asan-globals",
118 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000119static cl::opt<bool> ClInitializers("asan-initialization-order",
120 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000121static cl::opt<bool> ClMemIntrin("asan-memintrin",
122 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Kostya Serebryany6c554122012-12-04 06:14:01 +0000123static cl::opt<bool> ClRealignStack("asan-realign-stack",
124 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000125static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
126 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000127 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000128
129// These flags allow to change the shadow mapping.
130// The shadow mapping looks like
131// Shadow = (Mem >> scale) + (1 << offset_log)
132static cl::opt<int> ClMappingScale("asan-mapping-scale",
133 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
134static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
135 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
136
137// Optimization flags. Not user visible, used mostly for testing
138// and benchmarking the tool.
139static cl::opt<bool> ClOpt("asan-opt",
140 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
141static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
142 cl::desc("Instrument the same temp just once"), cl::Hidden,
143 cl::init(true));
144static cl::opt<bool> ClOptGlobals("asan-opt-globals",
145 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
146
Alexey Samsonovee548272012-11-29 18:14:24 +0000147static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
148 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
149 cl::Hidden, cl::init(false));
150
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000151// Debug flags.
152static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
153 cl::init(0));
154static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
155 cl::Hidden, cl::init(0));
156static cl::opt<std::string> ClDebugFunc("asan-debug-func",
157 cl::Hidden, cl::desc("Debug func"));
158static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
159 cl::Hidden, cl::init(-1));
160static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
161 cl::Hidden, cl::init(-1));
162
163namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000164/// A set of dynamically initialized globals extracted from metadata.
165class SetOfDynamicallyInitializedGlobals {
166 public:
167 void Init(Module& M) {
168 // Clang generates metadata identifying all dynamically initialized globals.
169 NamedMDNode *DynamicGlobals =
170 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
171 if (!DynamicGlobals)
172 return;
173 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
174 MDNode *MDN = DynamicGlobals->getOperand(i);
175 assert(MDN->getNumOperands() == 1);
176 Value *VG = MDN->getOperand(0);
177 // The optimizer may optimize away a global entirely, in which case we
178 // cannot instrument access to it.
179 if (!VG)
180 continue;
181 DynInitGlobals.insert(cast<GlobalVariable>(VG));
182 }
183 }
184 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
185 private:
186 SmallSet<GlobalValue*, 32> DynInitGlobals;
187};
188
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000189/// This struct defines the shadow mapping using the rule:
190/// shadow = (mem >> Scale) + Offset.
191struct ShadowMapping {
192 int Scale;
193 uint64_t Offset;
194};
195
196static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
197 llvm::Triple targetTriple(M.getTargetTriple());
198 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android;
199
200 ShadowMapping Mapping;
201
202 Mapping.Offset = isAndroid ? kDefaultShadowOffsetPie :
203 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
204 if (ClMappingOffsetLog >= 0) {
205 // Zero offset log is the special case.
206 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
207 }
208
209 Mapping.Scale = kDefaultShadowScale;
210 if (ClMappingScale) {
211 Mapping.Scale = ClMappingScale;
212 }
213
214 return Mapping;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000215}
216
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000217static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000218 // Redzone used for stack and globals is at least 32 bytes.
219 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000220 return std::max(32U, 1U << MappingScale);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000221}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000222
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000223/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000224struct AddressSanitizer : public FunctionPass {
Alexey Samsonovee548272012-11-29 18:14:24 +0000225 AddressSanitizer(bool CheckInitOrder = false,
226 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000227 bool CheckLifetime = false,
228 StringRef BlacklistFile = StringRef())
Alexey Samsonovee548272012-11-29 18:14:24 +0000229 : FunctionPass(ID),
230 CheckInitOrder(CheckInitOrder || ClInitializers),
231 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000232 CheckLifetime(CheckLifetime || ClCheckLifetime),
233 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
234 : BlacklistFile) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000235 virtual const char *getPassName() const {
236 return "AddressSanitizerFunctionPass";
237 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000238 void instrumentMop(Instruction *I);
239 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000240 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000241 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
242 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000243 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000244 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000245 bool instrumentMemIntrinsic(MemIntrinsic *MI);
246 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000247 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000248 Instruction *InsertBefore, bool IsWrite);
249 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000250 bool runOnFunction(Function &F);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000251 void createInitializerPoisonCalls(Module &M,
252 Value *FirstAddr, Value *LastAddr);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000253 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000254 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000255 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000256 static char ID; // Pass identification, replacement for typeid
257
258 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000259 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000260
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000261 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000262 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000263 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000264
Alexey Samsonovee548272012-11-29 18:14:24 +0000265 bool CheckInitOrder;
266 bool CheckUseAfterReturn;
267 bool CheckLifetime;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000268 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000269 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000270 int LongSize;
271 Type *IntptrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000272 ShadowMapping Mapping;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000273 Function *AsanCtorFunction;
274 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000275 Function *AsanHandleNoReturnFunc;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000276 SmallString<64> BlacklistFile;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000277 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000278 // This array is indexed by AccessIsWrite and log2(AccessSize).
279 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000280 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000281 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000282
283 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000284};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000285
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000286class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000287 public:
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000288 AddressSanitizerModule(bool CheckInitOrder = false,
289 StringRef BlacklistFile = StringRef())
Alexey Samsonovee548272012-11-29 18:14:24 +0000290 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000291 CheckInitOrder(CheckInitOrder || ClInitializers),
292 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
293 : BlacklistFile) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000294 bool runOnModule(Module &M);
295 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000296 virtual const char *getPassName() const {
297 return "AddressSanitizerModule";
298 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000299
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000300 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000301 void initializeCallbacks(Module &M);
302
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000303 bool ShouldInstrumentGlobal(GlobalVariable *G);
304 void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
305 Value *LastAddr);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000306 size_t RedzoneSize() const {
307 return RedzoneSizeForScale(Mapping.Scale);
308 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000309
Alexey Samsonovee548272012-11-29 18:14:24 +0000310 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000311 SmallString<64> BlacklistFile;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000312 OwningPtr<BlackList> BL;
313 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
314 Type *IntptrTy;
315 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000316 DataLayout *TD;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000317 ShadowMapping Mapping;
Alexey Samsonov46848582012-12-25 12:28:20 +0000318 Function *AsanPoisonGlobals;
319 Function *AsanUnpoisonGlobals;
320 Function *AsanRegisterGlobals;
321 Function *AsanUnregisterGlobals;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000322};
323
Alexey Samsonov59cca132012-12-25 12:04:36 +0000324// Stack poisoning does not play well with exception handling.
325// When an exception is thrown, we essentially bypass the code
326// that unpoisones the stack. This is why the run-time library has
327// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
328// stack in the interceptor. This however does not work inside the
329// actual function which catches the exception. Most likely because the
330// compiler hoists the load of the shadow value somewhere too high.
331// This causes asan to report a non-existing bug on 453.povray.
332// It sounds like an LLVM bug.
333struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
334 Function &F;
335 AddressSanitizer &ASan;
336 DIBuilder DIB;
337 LLVMContext *C;
338 Type *IntptrTy;
339 Type *IntptrPtrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000340 ShadowMapping Mapping;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000341
342 SmallVector<AllocaInst*, 16> AllocaVec;
343 SmallVector<Instruction*, 8> RetVec;
344 uint64_t TotalStackSize;
345 unsigned StackAlignment;
346
347 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
348 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
349
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000350 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
351 struct AllocaPoisonCall {
352 IntrinsicInst *InsBefore;
353 uint64_t Size;
354 bool DoPoison;
355 };
356 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
357
358 // Maps Value to an AllocaInst from which the Value is originated.
359 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
360 AllocaForValueMapTy AllocaForValue;
361
Alexey Samsonov59cca132012-12-25 12:04:36 +0000362 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
363 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
364 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000365 Mapping(ASan.Mapping),
366 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov59cca132012-12-25 12:04:36 +0000367
368 bool runOnFunction() {
369 if (!ClStack) return false;
370 // Collect alloca, ret, lifetime instructions etc.
371 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
372 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
373 BasicBlock *BB = *DI;
374 visit(*BB);
375 }
376 if (AllocaVec.empty()) return false;
377
378 initializeCallbacks(*F.getParent());
379
380 poisonStack();
381
382 if (ClDebugStack) {
383 DEBUG(dbgs() << F);
384 }
385 return true;
386 }
387
388 // Finds all static Alloca instructions and puts
389 // poisoned red zones around all of them.
390 // Then unpoison everything back before the function returns.
391 void poisonStack();
392
393 // ----------------------- Visitors.
394 /// \brief Collect all Ret instructions.
395 void visitReturnInst(ReturnInst &RI) {
396 RetVec.push_back(&RI);
397 }
398
399 /// \brief Collect Alloca instructions we want (and can) handle.
400 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000401 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000402
403 StackAlignment = std::max(StackAlignment, AI.getAlignment());
404 AllocaVec.push_back(&AI);
405 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
406 TotalStackSize += AlignedSize;
407 }
408
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000409 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
410 /// errors.
411 void visitIntrinsicInst(IntrinsicInst &II) {
412 if (!ASan.CheckLifetime) return;
413 Intrinsic::ID ID = II.getIntrinsicID();
414 if (ID != Intrinsic::lifetime_start &&
415 ID != Intrinsic::lifetime_end)
416 return;
417 // Found lifetime intrinsic, add ASan instrumentation if necessary.
418 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
419 // If size argument is undefined, don't do anything.
420 if (Size->isMinusOne()) return;
421 // Check that size doesn't saturate uint64_t and can
422 // be stored in IntptrTy.
423 const uint64_t SizeValue = Size->getValue().getLimitedValue();
424 if (SizeValue == ~0ULL ||
425 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
426 return;
427 // Find alloca instruction that corresponds to llvm.lifetime argument.
428 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
429 if (!AI) return;
430 bool DoPoison = (ID == Intrinsic::lifetime_end);
431 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
432 AllocaPoisonCallVec.push_back(APC);
433 }
434
Alexey Samsonov59cca132012-12-25 12:04:36 +0000435 // ---------------------- Helpers.
436 void initializeCallbacks(Module &M);
437
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000438 // Check if we want (and can) handle this alloca.
439 bool isInterestingAlloca(AllocaInst &AI) {
440 return (!AI.isArrayAllocation() &&
441 AI.isStaticAlloca() &&
442 AI.getAllocatedType()->isSized());
443 }
444
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000445 size_t RedzoneSize() const {
446 return RedzoneSizeForScale(Mapping.Scale);
447 }
Alexey Samsonov59cca132012-12-25 12:04:36 +0000448 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
449 Type *Ty = AI->getAllocatedType();
450 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
451 return SizeInBytes;
452 }
453 uint64_t getAlignedSize(uint64_t SizeInBytes) {
454 size_t RZ = RedzoneSize();
455 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
456 }
457 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
458 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
459 return getAlignedSize(SizeInBytes);
460 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000461 /// Finds alloca where the value comes from.
462 AllocaInst *findAllocaForValue(Value *V);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000463 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
464 Value *ShadowBase, bool DoPoison);
465 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000466};
467
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000468} // namespace
469
470char AddressSanitizer::ID = 0;
471INITIALIZE_PASS(AddressSanitizer, "asan",
472 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
473 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000474FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000475 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
476 StringRef BlacklistFile) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000477 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000478 CheckLifetime, BlacklistFile);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000479}
480
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000481char AddressSanitizerModule::ID = 0;
482INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
483 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
484 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000485ModulePass *llvm::createAddressSanitizerModulePass(
486 bool CheckInitOrder, StringRef BlacklistFile) {
487 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile);
Alexander Potapenko25878042012-01-23 11:22:43 +0000488}
489
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000490static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
491 size_t Res = CountTrailingZeros_32(TypeSize / 8);
492 assert(Res < kNumberOfAccessSizes);
493 return Res;
494}
495
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000496// Create a constant for Str so that we can pass it to the run-time lib.
497static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000498 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000499 return new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000500 GlobalValue::PrivateLinkage, StrConst,
501 kAsanGenPrefix);
502}
503
504static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
505 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000506}
507
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000508Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
509 // Shadow >> scale
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000510 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
511 if (Mapping.Offset == 0)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000512 return Shadow;
513 // (Shadow >> scale) | offset
514 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000515 Mapping.Offset));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000516}
517
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000518void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000519 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000520 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
521 // Check the first byte.
522 {
523 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000524 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000525 }
526 // Check the last byte.
527 {
528 IRBuilder<> IRB(InsertBefore);
529 Value *SizeMinusOne = IRB.CreateSub(
530 Size, ConstantInt::get(Size->getType(), 1));
531 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
532 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
533 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000534 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000535 }
536}
537
538// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000539bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000540 Value *Dst = MI->getDest();
541 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000542 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000543 Value *Length = MI->getLength();
544
545 Constant *ConstLength = dyn_cast<Constant>(Length);
546 Instruction *InsertBefore = MI;
547 if (ConstLength) {
548 if (ConstLength->isNullValue()) return false;
549 } else {
550 // The size is not a constant so it could be zero -- check at run-time.
551 IRBuilder<> IRB(InsertBefore);
552
553 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000554 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000555 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000556 }
557
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000558 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000559 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000560 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000561 return true;
562}
563
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000564// If I is an interesting memory access, return the PointerOperand
565// and set IsWrite. Otherwise return NULL.
566static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000567 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000568 if (!ClInstrumentReads) return NULL;
569 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000570 return LI->getPointerOperand();
571 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000572 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
573 if (!ClInstrumentWrites) return NULL;
574 *IsWrite = true;
575 return SI->getPointerOperand();
576 }
577 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
578 if (!ClInstrumentAtomics) return NULL;
579 *IsWrite = true;
580 return RMW->getPointerOperand();
581 }
582 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
583 if (!ClInstrumentAtomics) return NULL;
584 *IsWrite = true;
585 return XCHG->getPointerOperand();
586 }
587 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000588}
589
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000590void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000591 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000592 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
593 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000594 if (ClOpt && ClOptGlobals) {
595 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
596 // If initialization order checking is disabled, a simple access to a
597 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000598 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000599 return;
600 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000601 // have to instrument it. However, if a global does not have initailizer
602 // at all, we assume it has dynamic initializer (in other TU).
603 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000604 return;
605 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000606 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000607
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000608 Type *OrigPtrTy = Addr->getType();
609 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
610
611 assert(OrigTy->isSized());
612 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
613
614 if (TypeSize != 8 && TypeSize != 16 &&
615 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
616 // Ignore all unusual sizes.
617 return;
618 }
619
620 IRBuilder<> IRB(I);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000621 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000622}
623
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000624// Validate the result of Module::getOrInsertFunction called for an interface
625// function of AddressSanitizer. If the instrumented module defines a function
626// with the same name, their prototypes must match, otherwise
627// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000628static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000629 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
630 FuncOrBitcast->dump();
631 report_fatal_error("trying to redefine an AddressSanitizer "
632 "interface function");
633}
634
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000635Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000636 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000637 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000638 IRBuilder<> IRB(InsertBefore);
639 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
640 Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000641 // We don't do Call->setDoesNotReturn() because the BB already has
642 // UnreachableInst at the end.
643 // This EmptyAsm is required to avoid callback merge.
644 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000645 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000646}
647
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000648Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000649 Value *ShadowValue,
650 uint32_t TypeSize) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000651 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000652 // Addr & (Granularity - 1)
653 Value *LastAccessedByte = IRB.CreateAnd(
654 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
655 // (Addr & (Granularity - 1)) + size - 1
656 if (TypeSize / 8 > 1)
657 LastAccessedByte = IRB.CreateAdd(
658 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
659 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
660 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000661 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000662 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
663 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
664}
665
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000666void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000667 IRBuilder<> &IRB, Value *Addr,
668 uint32_t TypeSize, bool IsWrite) {
669 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
670
671 Type *ShadowTy = IntegerType::get(
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000672 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000673 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
674 Value *ShadowPtr = memToShadow(AddrLong, IRB);
675 Value *CmpVal = Constant::getNullValue(ShadowTy);
676 Value *ShadowValue = IRB.CreateLoad(
677 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
678
679 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000680 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000681 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000682 TerminatorInst *CrashTerm = 0;
683
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000684 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000685 TerminatorInst *CheckTerm =
686 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000687 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000688 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000689 IRB.SetInsertPoint(CheckTerm);
690 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000691 BasicBlock *CrashBlock =
692 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000693 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000694 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
695 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000696 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000697 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000698 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000699
700 Instruction *Crash =
701 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
702 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000703}
704
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000705void AddressSanitizerModule::createInitializerPoisonCalls(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000706 Module &M, Value *FirstAddr, Value *LastAddr) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000707 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
708 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
709 // If that function is not present, this TU contains no globals, or they have
710 // all been optimized away
711 if (!GlobalInit)
712 return;
713
714 // Set up the arguments to our poison/unpoison functions.
715 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
716
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000717 // Add a call to poison all external globals before the given function starts.
718 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
719
720 // Add calls to unpoison all globals before each return instruction.
721 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
722 I != E; ++I) {
723 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
724 CallInst::Create(AsanUnpoisonGlobals, "", RI);
725 }
726 }
727}
728
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000729bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000730 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000731 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000732
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000733 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000734 if (!Ty->isSized()) return false;
735 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000736 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000737 // Touch only those globals that will not be defined in other modules.
738 // Don't handle ODR type linkages since other modules may be built w/o asan.
739 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
740 G->getLinkage() != GlobalVariable::PrivateLinkage &&
741 G->getLinkage() != GlobalVariable::InternalLinkage)
742 return false;
743 // Two problems with thread-locals:
744 // - The address of the main thread's copy can't be computed at link-time.
745 // - Need to poison all copies, not just the main thread's one.
746 if (G->isThreadLocal())
747 return false;
748 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000749 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000750
751 // Ignore all the globals with the names starting with "\01L_OBJC_".
752 // Many of those are put into the .cstring section. The linker compresses
753 // that section by removing the spare \0s after the string terminator, so
754 // our redzones get broken.
755 if ((G->getName().find("\01L_OBJC_") == 0) ||
756 (G->getName().find("\01l_OBJC_") == 0)) {
757 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
758 return false;
759 }
760
761 if (G->hasSection()) {
762 StringRef Section(G->getSection());
763 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
764 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
765 // them.
766 if ((Section.find("__OBJC,") == 0) ||
767 (Section.find("__DATA, __objc_") == 0)) {
768 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
769 return false;
770 }
771 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
772 // Constant CFString instances are compiled in the following way:
773 // -- the string buffer is emitted into
774 // __TEXT,__cstring,cstring_literals
775 // -- the constant NSConstantString structure referencing that buffer
776 // is placed into __DATA,__cfstring
777 // Therefore there's no point in placing redzones into __DATA,__cfstring.
778 // Moreover, it causes the linker to crash on OS X 10.7
779 if (Section.find("__DATA,__cfstring") == 0) {
780 DEBUG(dbgs() << "Ignoring CFString: " << *G);
781 return false;
782 }
783 }
784
785 return true;
786}
787
Alexey Samsonov46848582012-12-25 12:28:20 +0000788void AddressSanitizerModule::initializeCallbacks(Module &M) {
789 IRBuilder<> IRB(*C);
790 // Declare our poisoning and unpoisoning functions.
791 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
792 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
793 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
794 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
795 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
796 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
797 // Declare functions that register/unregister globals.
798 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
799 kAsanRegisterGlobalsName, IRB.getVoidTy(),
800 IntptrTy, IntptrTy, NULL));
801 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
802 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
803 kAsanUnregisterGlobalsName,
804 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
805 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
806}
807
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000808// This function replaces all global variables with new variables that have
809// trailing redzones. It also creates a function that poisons
810// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000811bool AddressSanitizerModule::runOnModule(Module &M) {
812 if (!ClGlobals) return false;
813 TD = getAnalysisIfAvailable<DataLayout>();
814 if (!TD)
815 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000816 BL.reset(new BlackList(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000817 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000818 C = &(M.getContext());
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000819 int LongSize = TD->getPointerSizeInBits();
820 IntptrTy = Type::getIntNTy(*C, LongSize);
821 Mapping = getShadowMapping(M, LongSize);
Alexey Samsonov46848582012-12-25 12:28:20 +0000822 initializeCallbacks(M);
823 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000824
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000825 SmallVector<GlobalVariable *, 16> GlobalsToChange;
826
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000827 for (Module::GlobalListType::iterator G = M.global_begin(),
828 E = M.global_end(); G != E; ++G) {
829 if (ShouldInstrumentGlobal(G))
830 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000831 }
832
833 size_t n = GlobalsToChange.size();
834 if (n == 0) return false;
835
836 // A global is described by a structure
837 // size_t beg;
838 // size_t size;
839 // size_t size_with_redzone;
840 // const char *name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000841 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000842 // We initialize an array of such structures and pass it to a run-time call.
843 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000844 IntptrTy, IntptrTy,
845 IntptrTy, NULL);
846 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000847
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000848
849 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
850 assert(CtorFunc);
851 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000852
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000853 // The addresses of the first and last dynamically initialized globals in
854 // this TU. Used in initialization order checking.
855 Value *FirstDynamic = 0, *LastDynamic = 0;
856
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000857 for (size_t i = 0; i < n; i++) {
858 GlobalVariable *G = GlobalsToChange[i];
859 PointerType *PtrTy = cast<PointerType>(G->getType());
860 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000861 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000862 size_t RZ = RedzoneSize();
863 uint64_t RightRedzoneSize = RZ + (RZ - (SizeInBytes % RZ));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000864 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000865 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000866 bool GlobalHasDynamicInitializer =
867 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000868 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000869 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000870
871 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
872 Constant *NewInitializer = ConstantStruct::get(
873 NewTy, G->getInitializer(),
874 Constant::getNullValue(RightRedZoneTy), NULL);
875
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000876 SmallString<2048> DescriptionOfGlobal = G->getName();
877 DescriptionOfGlobal += " (";
878 DescriptionOfGlobal += M.getModuleIdentifier();
879 DescriptionOfGlobal += ")";
880 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000881
882 // Create a new global variable with enough space for a redzone.
883 GlobalVariable *NewGlobal = new GlobalVariable(
884 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000885 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000886 NewGlobal->copyAttributesFrom(G);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000887 NewGlobal->setAlignment(RZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000888
889 Value *Indices2[2];
890 Indices2[0] = IRB.getInt32(0);
891 Indices2[1] = IRB.getInt32(0);
892
893 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000894 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000895 NewGlobal->takeName(G);
896 G->eraseFromParent();
897
898 Initializers[i] = ConstantStruct::get(
899 GlobalStructTy,
900 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
901 ConstantInt::get(IntptrTy, SizeInBytes),
902 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
903 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000904 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000905 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000906
907 // Populate the first and last globals declared in this TU.
Alexey Samsonovee548272012-11-29 18:14:24 +0000908 if (CheckInitOrder && GlobalHasDynamicInitializer) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000909 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
910 if (FirstDynamic == 0)
911 FirstDynamic = LastDynamic;
912 }
913
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000914 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000915 }
916
917 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
918 GlobalVariable *AllGlobals = new GlobalVariable(
919 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
920 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
921
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000922 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovee548272012-11-29 18:14:24 +0000923 if (CheckInitOrder && FirstDynamic && LastDynamic)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000924 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000925 IRB.CreateCall2(AsanRegisterGlobals,
926 IRB.CreatePointerCast(AllGlobals, IntptrTy),
927 ConstantInt::get(IntptrTy, n));
928
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000929 // We also need to unregister globals at the end, e.g. when a shared library
930 // gets closed.
931 Function *AsanDtorFunction = Function::Create(
932 FunctionType::get(Type::getVoidTy(*C), false),
933 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
934 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
935 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000936 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
937 IRB.CreatePointerCast(AllGlobals, IntptrTy),
938 ConstantInt::get(IntptrTy, n));
939 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
940
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000941 DEBUG(dbgs() << M);
942 return true;
943}
944
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000945void AddressSanitizer::initializeCallbacks(Module &M) {
946 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000947 // Create __asan_report* callbacks.
948 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
949 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
950 AccessSizeIndex++) {
951 // IsWrite and TypeSize are encoded in the function name.
952 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
953 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000954 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +0000955 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
956 checkInterfaceFunction(M.getOrInsertFunction(
957 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000958 }
959 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000960
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000961 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
962 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000963 // We insert an empty inline asm after __asan_report* to avoid callback merge.
964 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
965 StringRef(""), StringRef(""),
966 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000967}
968
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000969void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
970 // Tell the values of mapping offset and scale to the run-time if they are
971 // specified by command-line flags.
972 if (ClMappingOffsetLog >= 0) {
973 GlobalValue *asan_mapping_offset =
974 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
975 ConstantInt::get(IntptrTy, Mapping.Offset),
976 kAsanMappingOffsetName);
977 // Read the global, otherwise it may be optimized away.
978 IRB.CreateLoad(asan_mapping_offset, true);
979 }
980
981 if (ClMappingScale) {
982 GlobalValue *asan_mapping_scale =
983 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
984 ConstantInt::get(IntptrTy, Mapping.Scale),
985 kAsanMappingScaleName);
986 // Read the global, otherwise it may be optimized away.
987 IRB.CreateLoad(asan_mapping_scale, true);
988 }
989}
990
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000991// virtual
992bool AddressSanitizer::doInitialization(Module &M) {
993 // Initialize the private fields. No one has accessed them before.
994 TD = getAnalysisIfAvailable<DataLayout>();
995
996 if (!TD)
997 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000998 BL.reset(new BlackList(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000999 DynamicallyInitializedGlobals.Init(M);
1000
1001 C = &(M.getContext());
1002 LongSize = TD->getPointerSizeInBits();
1003 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001004
1005 AsanCtorFunction = Function::Create(
1006 FunctionType::get(Type::getVoidTy(*C), false),
1007 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1008 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1009 // call __asan_init in the module ctor.
1010 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1011 AsanInitFunction = checkInterfaceFunction(
1012 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1013 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1014 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001015
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001016 Mapping = getShadowMapping(M, LongSize);
1017 emitShadowMapping(M, IRB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001018
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001019 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001020 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001021}
1022
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001023bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1024 // For each NSObject descendant having a +load method, this method is invoked
1025 // by the ObjC runtime before any of the static constructors is called.
1026 // Therefore we need to instrument such methods with a call to __asan_init
1027 // at the beginning in order to initialize our runtime before any access to
1028 // the shadow memory.
1029 // We cannot just ignore these methods, because they may call other
1030 // instrumented functions.
1031 if (F.getName().find(" load]") != std::string::npos) {
1032 IRBuilder<> IRB(F.begin()->begin());
1033 IRB.CreateCall(AsanInitFunction);
1034 return true;
1035 }
1036 return false;
1037}
1038
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001039bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001040 if (BL->isIn(F)) return false;
1041 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001042 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001043 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001044
1045 // If needed, insert __asan_init before checking for AddressSafety attr.
1046 maybeInsertAsanInitAtFunctionEntry(F);
1047
Bill Wendling831737d2012-12-30 10:32:01 +00001048 if (!F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1049 Attribute::AddressSafety))
Bill Wendling67658342012-10-09 07:45:08 +00001050 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001051
1052 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1053 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001054
1055 // We want to instrument every address only once per basic block (unless there
1056 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001057 SmallSet<Value*, 16> TempsToInstrument;
1058 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001059 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001060 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001061
1062 // Fill the set of memory operations to instrument.
1063 for (Function::iterator FI = F.begin(), FE = F.end();
1064 FI != FE; ++FI) {
1065 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001066 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001067 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1068 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001069 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001070 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001071 if (ClOpt && ClOptSameTemp) {
1072 if (!TempsToInstrument.insert(Addr))
1073 continue; // We've seen this temp in the current BB.
1074 }
1075 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1076 // ok, take it.
1077 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001078 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001079 // A call inside BB.
1080 TempsToInstrument.clear();
Kostya Serebryanya17babb2012-11-30 11:08:59 +00001081 if (CI->doesNotReturn()) {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001082 NoReturnCalls.push_back(CI);
1083 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001084 }
1085 continue;
1086 }
1087 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001088 NumInsnsPerBB++;
1089 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1090 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001091 }
1092 }
1093
1094 // Instrument.
1095 int NumInstrumented = 0;
1096 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1097 Instruction *Inst = ToInstrument[i];
1098 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1099 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001100 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001101 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001102 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001103 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001104 }
1105 NumInstrumented++;
1106 }
1107
Alexey Samsonov59cca132012-12-25 12:04:36 +00001108 FunctionStackPoisoner FSP(F, *this);
1109 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001110
1111 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1112 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1113 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1114 Instruction *CI = NoReturnCalls[i];
1115 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001116 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001117 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001118 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001119
1120 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001121}
1122
1123static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1124 if (ShadowRedzoneSize == 1) return PoisonByte;
1125 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1126 if (ShadowRedzoneSize == 4)
1127 return (PoisonByte << 24) + (PoisonByte << 16) +
1128 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001129 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001130}
1131
1132static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1133 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001134 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001135 size_t ShadowGranularity,
1136 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001137 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001138 i+= ShadowGranularity, Shadow++) {
1139 if (i + ShadowGranularity <= Size) {
1140 *Shadow = 0; // fully addressable
1141 } else if (i >= Size) {
1142 *Shadow = Magic; // unaddressable
1143 } else {
1144 *Shadow = Size - i; // first Size-i bytes are addressable
1145 }
1146 }
1147}
1148
Alexey Samsonov59cca132012-12-25 12:04:36 +00001149// Workaround for bug 11395: we don't want to instrument stack in functions
1150// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1151// FIXME: remove once the bug 11395 is fixed.
1152bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1153 if (LongSize != 32) return false;
1154 CallInst *CI = dyn_cast<CallInst>(I);
1155 if (!CI || !CI->isInlineAsm()) return false;
1156 if (CI->getNumArgOperands() <= 5) return false;
1157 // We have inline assembly with quite a few arguments.
1158 return true;
1159}
1160
1161void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1162 IRBuilder<> IRB(*C);
1163 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
1164 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
1165 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
1166 kAsanStackFreeName, IRB.getVoidTy(),
1167 IntptrTy, IntptrTy, IntptrTy, NULL));
1168 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1169 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1170 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1171 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1172}
1173
1174void FunctionStackPoisoner::poisonRedZones(
1175 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
1176 bool DoPoison) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001177 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001178 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1179 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1180 Type *RZPtrTy = PointerType::get(RZTy, 0);
1181
1182 Value *PoisonLeft = ConstantInt::get(RZTy,
1183 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1184 Value *PoisonMid = ConstantInt::get(RZTy,
1185 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1186 Value *PoisonRight = ConstantInt::get(RZTy,
1187 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1188
1189 // poison the first red zone.
1190 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1191
1192 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001193 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001194 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1195 AllocaInst *AI = AllocaVec[i];
1196 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1197 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001198 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001199 Value *Ptr = NULL;
1200
1201 Pos += AlignedSize;
1202
1203 assert(ShadowBase->getType() == IntptrTy);
1204 if (SizeInBytes < AlignedSize) {
1205 // Poison the partial redzone at right
1206 Ptr = IRB.CreateAdd(
1207 ShadowBase, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001208 (Pos >> Mapping.Scale) - ShadowRZSize));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001209 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001210 uint32_t Poison = 0;
1211 if (DoPoison) {
1212 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001213 RedzoneSize(),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001214 1ULL << Mapping.Scale,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001215 kAsanStackPartialRedzoneMagic);
1216 }
1217 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1218 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1219 }
1220
1221 // Poison the full redzone at right.
1222 Ptr = IRB.CreateAdd(ShadowBase,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001223 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001224 bool LastAlloca = (i == AllocaVec.size() - 1);
1225 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001226 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1227
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001228 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001229 }
1230}
1231
Alexey Samsonov59cca132012-12-25 12:04:36 +00001232void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001233 uint64_t LocalStackSize = TotalStackSize +
1234 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001235
Alexey Samsonov59cca132012-12-25 12:04:36 +00001236 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001237 && LocalStackSize <= kMaxStackMallocSize;
1238
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001239 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001240 Instruction *InsBefore = AllocaVec[0];
1241 IRBuilder<> IRB(InsBefore);
1242
1243
1244 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1245 AllocaInst *MyAlloca =
1246 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001247 if (ClRealignStack && StackAlignment < RedzoneSize())
1248 StackAlignment = RedzoneSize();
1249 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001250 assert(MyAlloca->isStaticAlloca());
1251 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1252 Value *LocalStackBase = OrigStackBase;
1253
1254 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001255 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1256 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1257 }
1258
1259 // This string will be parsed by the run-time (DescribeStackAddress).
1260 SmallString<2048> StackDescriptionStorage;
1261 raw_svector_ostream StackDescription(StackDescriptionStorage);
1262 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1263
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001264 // Insert poison calls for lifetime intrinsics for alloca.
1265 bool HavePoisonedAllocas = false;
1266 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1267 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1268 IntrinsicInst *II = APC.InsBefore;
1269 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1270 assert(AI);
1271 IRBuilder<> IRB(II);
1272 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1273 HavePoisonedAllocas |= APC.DoPoison;
1274 }
1275
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001276 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001277 // Replace Alloca instructions with base+offset.
1278 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1279 AllocaInst *AI = AllocaVec[i];
1280 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1281 StringRef Name = AI->getName();
1282 StackDescription << Pos << " " << SizeInBytes << " "
1283 << Name.size() << " " << Name << " ";
1284 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001285 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001286 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001287 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001288 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001289 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001290 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001291 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001292 }
1293 assert(Pos == LocalStackSize);
1294
1295 // Write the Magic value and the frame description constant to the redzone.
1296 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1297 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1298 BasePlus0);
1299 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
Alexey Samsonov59cca132012-12-25 12:04:36 +00001300 ConstantInt::get(IntptrTy,
1301 ASan.LongSize/8));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001302 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001303 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001304 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001305 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1306 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001307 IRB.CreateStore(Description, BasePlus1);
1308
1309 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001310 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1311 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001312
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001313 // Unpoison the stack before all ret instructions.
1314 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1315 Instruction *Ret = RetVec[i];
1316 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001317 // Mark the current frame as retired.
1318 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1319 BasePlus0);
1320 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001321 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001322 if (DoStackMalloc) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001323 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001324 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1325 ConstantInt::get(IntptrTy, LocalStackSize),
1326 OrigStackBase);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001327 } else if (HavePoisonedAllocas) {
1328 // If we poisoned some allocas in llvm.lifetime analysis,
1329 // unpoison whole stack frame now.
1330 assert(LocalStackBase == OrigStackBase);
1331 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001332 }
1333 }
1334
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001335 // We are done. Remove the old unused alloca instructions.
1336 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1337 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001338}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001339
Alexey Samsonov59cca132012-12-25 12:04:36 +00001340void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1341 IRBuilder<> IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001342 // For now just insert the call to ASan runtime.
1343 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1344 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1345 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1346 : AsanUnpoisonStackMemoryFunc,
1347 AddrArg, SizeArg);
1348}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001349
1350// Handling llvm.lifetime intrinsics for a given %alloca:
1351// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1352// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1353// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1354// could be poisoned by previous llvm.lifetime.end instruction, as the
1355// variable may go in and out of scope several times, e.g. in loops).
1356// (3) if we poisoned at least one %alloca in a function,
1357// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001358
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001359AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1360 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1361 // We're intested only in allocas we can handle.
1362 return isInterestingAlloca(*AI) ? AI : 0;
1363 // See if we've already calculated (or started to calculate) alloca for a
1364 // given value.
1365 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1366 if (I != AllocaForValue.end())
1367 return I->second;
1368 // Store 0 while we're calculating alloca for value V to avoid
1369 // infinite recursion if the value references itself.
1370 AllocaForValue[V] = 0;
1371 AllocaInst *Res = 0;
1372 if (CastInst *CI = dyn_cast<CastInst>(V))
1373 Res = findAllocaForValue(CI->getOperand(0));
1374 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1375 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1376 Value *IncValue = PN->getIncomingValue(i);
1377 // Allow self-referencing phi-nodes.
1378 if (IncValue == PN) continue;
1379 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1380 // AI for incoming values should exist and should all be equal.
1381 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1382 return 0;
1383 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001384 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001385 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001386 if (Res != 0)
1387 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001388 return Res;
1389}