blob: 1d59ba51d94164f78a0d4d3c69cae50a808d5207 [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 Serebryany800e03f2011-11-16 01:35:23 +000019#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov1c8b8252012-12-27 08:50:58 +000020#include "llvm/ADT/DenseMap.h"
Alexey Samsonov59cca132012-12-25 12:04:36 +000021#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000022#include "llvm/ADT/OwningPtr.h"
23#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000027#include "llvm/ADT/Triple.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000028#include "llvm/DIBuilder.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/InlineAsm.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/Type.h"
Alexey Samsonov59cca132012-12-25 12:04:36 +000037#include "llvm/InstVisitor.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000038#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/DataTypes.h"
40#include "llvm/Support/Debug.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000041#include "llvm/Support/raw_ostream.h"
42#include "llvm/Support/system_error.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000043#include "llvm/Target/TargetMachine.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruth90230c82013-01-19 08:03:47 +000045#include "llvm/Transforms/Utils/BlackList.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;
Kostya Serebryany117de482013-02-11 14:36:01 +000056static const uint64_t kDefaultShort64bitShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany48a615f2013-01-23 12:54:55 +000057static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000058
59static const size_t kMaxStackMallocSize = 1 << 16; // 64K
60static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
61static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
62
63static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000064static const char *kAsanModuleDtorName = "asan.module_dtor";
65static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000066static const char *kAsanReportErrorTemplate = "__asan_report_";
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +000067static const char *kAsanReportLoadN = "__asan_report_load_n";
68static const char *kAsanReportStoreN = "__asan_report_store_n";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000069static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000070static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +000071static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
72static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kostya Serebryany0bc55d52013-02-12 11:11:02 +000073static const char *kAsanInitName = "__asan_init_v1";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000074static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000075static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
76static const char *kAsanMappingScaleName = "__asan_mapping_scale";
77static const char *kAsanStackMallocName = "__asan_stack_malloc";
78static const char *kAsanStackFreeName = "__asan_stack_free";
Kostya Serebryany51c7c652012-11-20 14:16:08 +000079static const char *kAsanGenPrefix = "__asan_gen_";
Alexey Samsonovf985f442012-12-04 01:34:23 +000080static const char *kAsanPoisonStackMemoryName = "__asan_poison_stack_memory";
81static const char *kAsanUnpoisonStackMemoryName =
82 "__asan_unpoison_stack_memory";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000083
84static const int kAsanStackLeftRedzoneMagic = 0xf1;
85static const int kAsanStackMidRedzoneMagic = 0xf2;
86static const int kAsanStackRightRedzoneMagic = 0xf3;
87static const int kAsanStackPartialRedzoneMagic = 0xf4;
88
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000089// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
90static const size_t kNumberOfAccessSizes = 5;
91
Kostya Serebryany800e03f2011-11-16 01:35:23 +000092// Command-line flags.
93
94// This flag may need to be replaced with -f[no-]asan-reads.
95static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
96 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
97static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
98 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000099static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
100 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
101 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000102static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
103 cl::desc("use instrumentation with slow path for all accesses"),
104 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000105// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000106// in any given BB. Normally, this should be set to unlimited (INT_MAX),
107// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
108// set it to 10000.
109static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
110 cl::init(10000),
111 cl::desc("maximal number of instructions to instrument in any given BB"),
112 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000113// This flag may need to be replaced with -f[no]asan-stack.
114static cl::opt<bool> ClStack("asan-stack",
115 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
116// This flag may need to be replaced with -f[no]asan-use-after-return.
117static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
118 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
119// This flag may need to be replaced with -f[no]asan-globals.
120static cl::opt<bool> ClGlobals("asan-globals",
121 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000122static cl::opt<bool> ClInitializers("asan-initialization-order",
123 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000124static cl::opt<bool> ClMemIntrin("asan-memintrin",
125 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Kostya Serebryany6c554122012-12-04 06:14:01 +0000126static cl::opt<bool> ClRealignStack("asan-realign-stack",
127 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000128static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
129 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000130 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000131
132// These flags allow to change the shadow mapping.
133// The shadow mapping looks like
134// Shadow = (Mem >> scale) + (1 << offset_log)
135static cl::opt<int> ClMappingScale("asan-mapping-scale",
136 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
137static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
138 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
Kostya Serebryany117de482013-02-11 14:36:01 +0000139static cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
140 cl::desc("Use short immediate constant as the mapping offset for 64bit"),
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000141 cl::Hidden, cl::init(true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000142
143// Optimization flags. Not user visible, used mostly for testing
144// and benchmarking the tool.
145static cl::opt<bool> ClOpt("asan-opt",
146 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
147static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
148 cl::desc("Instrument the same temp just once"), cl::Hidden,
149 cl::init(true));
150static cl::opt<bool> ClOptGlobals("asan-opt-globals",
151 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
152
Alexey Samsonovee548272012-11-29 18:14:24 +0000153static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
154 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
155 cl::Hidden, cl::init(false));
156
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000157// Debug flags.
158static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
159 cl::init(0));
160static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
161 cl::Hidden, cl::init(0));
162static cl::opt<std::string> ClDebugFunc("asan-debug-func",
163 cl::Hidden, cl::desc("Debug func"));
164static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
165 cl::Hidden, cl::init(-1));
166static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
167 cl::Hidden, cl::init(-1));
168
169namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000170/// A set of dynamically initialized globals extracted from metadata.
171class SetOfDynamicallyInitializedGlobals {
172 public:
173 void Init(Module& M) {
174 // Clang generates metadata identifying all dynamically initialized globals.
175 NamedMDNode *DynamicGlobals =
176 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
177 if (!DynamicGlobals)
178 return;
179 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
180 MDNode *MDN = DynamicGlobals->getOperand(i);
181 assert(MDN->getNumOperands() == 1);
182 Value *VG = MDN->getOperand(0);
183 // The optimizer may optimize away a global entirely, in which case we
184 // cannot instrument access to it.
185 if (!VG)
186 continue;
187 DynInitGlobals.insert(cast<GlobalVariable>(VG));
188 }
189 }
190 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
191 private:
192 SmallSet<GlobalValue*, 32> DynInitGlobals;
193};
194
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000195/// This struct defines the shadow mapping using the rule:
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000196/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000197struct ShadowMapping {
198 int Scale;
199 uint64_t Offset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000200 bool OrShadowOffset;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000201};
202
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000203static ShadowMapping getShadowMapping(const Module &M, int LongSize,
204 bool ZeroBaseShadow) {
205 llvm::Triple TargetTriple(M.getTargetTriple());
206 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000207 bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000208 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64;
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000209 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000210
211 ShadowMapping Mapping;
212
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000213 // OR-ing shadow offset if more efficient (at least on x86),
214 // but on ppc64 we have to use add since the shadow offset is not neccesary
215 // 1/8-th of the address space.
Kostya Serebryany117de482013-02-11 14:36:01 +0000216 Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000217
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000218 Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000219 (LongSize == 32 ? kDefaultShadowOffset32 :
220 IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000221 if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000222 assert(LongSize == 64);
Kostya Serebryany117de482013-02-11 14:36:01 +0000223 Mapping.Offset = kDefaultShort64bitShadowOffset;
Kostya Serebryany39f02942013-02-13 05:14:12 +0000224 }
225 if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000226 // Zero offset log is the special case.
227 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
228 }
229
230 Mapping.Scale = kDefaultShadowScale;
231 if (ClMappingScale) {
232 Mapping.Scale = ClMappingScale;
233 }
234
235 return Mapping;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000236}
237
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000238static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000239 // Redzone used for stack and globals is at least 32 bytes.
240 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000241 return std::max(32U, 1U << MappingScale);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000242}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000243
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000244/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000245struct AddressSanitizer : public FunctionPass {
Alexey Samsonovee548272012-11-29 18:14:24 +0000246 AddressSanitizer(bool CheckInitOrder = false,
247 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000248 bool CheckLifetime = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000249 StringRef BlacklistFile = StringRef(),
250 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000251 : FunctionPass(ID),
252 CheckInitOrder(CheckInitOrder || ClInitializers),
253 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000254 CheckLifetime(CheckLifetime || ClCheckLifetime),
255 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000256 : BlacklistFile),
257 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000258 virtual const char *getPassName() const {
259 return "AddressSanitizerFunctionPass";
260 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000261 void instrumentMop(Instruction *I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000262 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
263 Value *Addr, uint32_t TypeSize, bool IsWrite,
264 Value *SizeArgument);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000265 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
266 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000267 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000268 bool IsWrite, size_t AccessSizeIndex,
269 Value *SizeArgument);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000270 bool instrumentMemIntrinsic(MemIntrinsic *MI);
271 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000272 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000273 Instruction *InsertBefore, bool IsWrite);
274 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000275 bool runOnFunction(Function &F);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000276 void createInitializerPoisonCalls(Module &M,
277 Value *FirstAddr, Value *LastAddr);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000278 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000279 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000280 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000281 static char ID; // Pass identification, replacement for typeid
282
283 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000284 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000285
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000286 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000287 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000288 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000289
Alexey Samsonovee548272012-11-29 18:14:24 +0000290 bool CheckInitOrder;
291 bool CheckUseAfterReturn;
292 bool CheckLifetime;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000293 SmallString<64> BlacklistFile;
294 bool ZeroBaseShadow;
295
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000296 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000297 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000298 int LongSize;
299 Type *IntptrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000300 ShadowMapping Mapping;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000301 Function *AsanCtorFunction;
302 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000303 Function *AsanHandleNoReturnFunc;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000304 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000305 // This array is indexed by AccessIsWrite and log2(AccessSize).
306 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000307 // This array is indexed by AccessIsWrite.
308 Function *AsanErrorCallbackSized[2];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000309 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000310 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000311
312 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000313};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000314
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000315class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000316 public:
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000317 AddressSanitizerModule(bool CheckInitOrder = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000318 StringRef BlacklistFile = StringRef(),
319 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000320 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000321 CheckInitOrder(CheckInitOrder || ClInitializers),
322 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000323 : BlacklistFile),
324 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000325 bool runOnModule(Module &M);
326 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000327 virtual const char *getPassName() const {
328 return "AddressSanitizerModule";
329 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000330
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000331 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000332 void initializeCallbacks(Module &M);
333
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000334 bool ShouldInstrumentGlobal(GlobalVariable *G);
335 void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
336 Value *LastAddr);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000337 size_t RedzoneSize() const {
338 return RedzoneSizeForScale(Mapping.Scale);
339 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000340
Alexey Samsonovee548272012-11-29 18:14:24 +0000341 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000342 SmallString<64> BlacklistFile;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000343 bool ZeroBaseShadow;
344
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000345 OwningPtr<BlackList> BL;
346 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
347 Type *IntptrTy;
348 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000349 DataLayout *TD;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000350 ShadowMapping Mapping;
Alexey Samsonov46848582012-12-25 12:28:20 +0000351 Function *AsanPoisonGlobals;
352 Function *AsanUnpoisonGlobals;
353 Function *AsanRegisterGlobals;
354 Function *AsanUnregisterGlobals;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000355};
356
Alexey Samsonov59cca132012-12-25 12:04:36 +0000357// Stack poisoning does not play well with exception handling.
358// When an exception is thrown, we essentially bypass the code
359// that unpoisones the stack. This is why the run-time library has
360// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
361// stack in the interceptor. This however does not work inside the
362// actual function which catches the exception. Most likely because the
363// compiler hoists the load of the shadow value somewhere too high.
364// This causes asan to report a non-existing bug on 453.povray.
365// It sounds like an LLVM bug.
366struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
367 Function &F;
368 AddressSanitizer &ASan;
369 DIBuilder DIB;
370 LLVMContext *C;
371 Type *IntptrTy;
372 Type *IntptrPtrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000373 ShadowMapping Mapping;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000374
375 SmallVector<AllocaInst*, 16> AllocaVec;
376 SmallVector<Instruction*, 8> RetVec;
377 uint64_t TotalStackSize;
378 unsigned StackAlignment;
379
380 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
381 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
382
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000383 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
384 struct AllocaPoisonCall {
385 IntrinsicInst *InsBefore;
386 uint64_t Size;
387 bool DoPoison;
388 };
389 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
390
391 // Maps Value to an AllocaInst from which the Value is originated.
392 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
393 AllocaForValueMapTy AllocaForValue;
394
Alexey Samsonov59cca132012-12-25 12:04:36 +0000395 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
396 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
397 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000398 Mapping(ASan.Mapping),
399 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov59cca132012-12-25 12:04:36 +0000400
401 bool runOnFunction() {
402 if (!ClStack) return false;
403 // Collect alloca, ret, lifetime instructions etc.
404 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
405 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
406 BasicBlock *BB = *DI;
407 visit(*BB);
408 }
409 if (AllocaVec.empty()) return false;
410
411 initializeCallbacks(*F.getParent());
412
413 poisonStack();
414
415 if (ClDebugStack) {
416 DEBUG(dbgs() << F);
417 }
418 return true;
419 }
420
421 // Finds all static Alloca instructions and puts
422 // poisoned red zones around all of them.
423 // Then unpoison everything back before the function returns.
424 void poisonStack();
425
426 // ----------------------- Visitors.
427 /// \brief Collect all Ret instructions.
428 void visitReturnInst(ReturnInst &RI) {
429 RetVec.push_back(&RI);
430 }
431
432 /// \brief Collect Alloca instructions we want (and can) handle.
433 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000434 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000435
436 StackAlignment = std::max(StackAlignment, AI.getAlignment());
437 AllocaVec.push_back(&AI);
438 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
439 TotalStackSize += AlignedSize;
440 }
441
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000442 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
443 /// errors.
444 void visitIntrinsicInst(IntrinsicInst &II) {
445 if (!ASan.CheckLifetime) return;
446 Intrinsic::ID ID = II.getIntrinsicID();
447 if (ID != Intrinsic::lifetime_start &&
448 ID != Intrinsic::lifetime_end)
449 return;
450 // Found lifetime intrinsic, add ASan instrumentation if necessary.
451 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
452 // If size argument is undefined, don't do anything.
453 if (Size->isMinusOne()) return;
454 // Check that size doesn't saturate uint64_t and can
455 // be stored in IntptrTy.
456 const uint64_t SizeValue = Size->getValue().getLimitedValue();
457 if (SizeValue == ~0ULL ||
458 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
459 return;
460 // Find alloca instruction that corresponds to llvm.lifetime argument.
461 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
462 if (!AI) return;
463 bool DoPoison = (ID == Intrinsic::lifetime_end);
464 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
465 AllocaPoisonCallVec.push_back(APC);
466 }
467
Alexey Samsonov59cca132012-12-25 12:04:36 +0000468 // ---------------------- Helpers.
469 void initializeCallbacks(Module &M);
470
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000471 // Check if we want (and can) handle this alloca.
472 bool isInterestingAlloca(AllocaInst &AI) {
473 return (!AI.isArrayAllocation() &&
474 AI.isStaticAlloca() &&
475 AI.getAllocatedType()->isSized());
476 }
477
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000478 size_t RedzoneSize() const {
479 return RedzoneSizeForScale(Mapping.Scale);
480 }
Alexey Samsonov59cca132012-12-25 12:04:36 +0000481 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
482 Type *Ty = AI->getAllocatedType();
483 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
484 return SizeInBytes;
485 }
486 uint64_t getAlignedSize(uint64_t SizeInBytes) {
487 size_t RZ = RedzoneSize();
488 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
489 }
490 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
491 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
492 return getAlignedSize(SizeInBytes);
493 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000494 /// Finds alloca where the value comes from.
495 AllocaInst *findAllocaForValue(Value *V);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000496 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
497 Value *ShadowBase, bool DoPoison);
498 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000499};
500
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000501} // namespace
502
503char AddressSanitizer::ID = 0;
504INITIALIZE_PASS(AddressSanitizer, "asan",
505 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
506 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000507FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000508 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000509 StringRef BlacklistFile, bool ZeroBaseShadow) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000510 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000511 CheckLifetime, BlacklistFile, ZeroBaseShadow);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000512}
513
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000514char AddressSanitizerModule::ID = 0;
515INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
516 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
517 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000518ModulePass *llvm::createAddressSanitizerModulePass(
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000519 bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
520 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
521 ZeroBaseShadow);
Alexander Potapenko25878042012-01-23 11:22:43 +0000522}
523
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000524static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
525 size_t Res = CountTrailingZeros_32(TypeSize / 8);
526 assert(Res < kNumberOfAccessSizes);
527 return Res;
528}
529
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000530// Create a constant for Str so that we can pass it to the run-time lib.
531static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000532 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000533 return new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000534 GlobalValue::PrivateLinkage, StrConst,
535 kAsanGenPrefix);
536}
537
538static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
539 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000540}
541
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000542Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
543 // Shadow >> scale
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000544 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
545 if (Mapping.Offset == 0)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000546 return Shadow;
547 // (Shadow >> scale) | offset
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000548 if (Mapping.OrShadowOffset)
549 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
550 else
551 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000552}
553
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000554void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000555 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000556 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000557 IRBuilder<> IRB(InsertBefore);
558 if (Size->getType() != IntptrTy)
559 Size = IRB.CreateIntCast(Size, IntptrTy, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000560 // Check the first byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000561 instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000562 // Check the last byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000563 IRB.SetInsertPoint(InsertBefore);
564 Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
565 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
566 Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
567 instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000568}
569
570// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000571bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000572 Value *Dst = MI->getDest();
573 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000574 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000575 Value *Length = MI->getLength();
576
577 Constant *ConstLength = dyn_cast<Constant>(Length);
578 Instruction *InsertBefore = MI;
579 if (ConstLength) {
580 if (ConstLength->isNullValue()) return false;
581 } else {
582 // The size is not a constant so it could be zero -- check at run-time.
583 IRBuilder<> IRB(InsertBefore);
584
585 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000586 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000587 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000588 }
589
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000590 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000591 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000592 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000593 return true;
594}
595
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000596// If I is an interesting memory access, return the PointerOperand
597// and set IsWrite. Otherwise return NULL.
598static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000599 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000600 if (!ClInstrumentReads) return NULL;
601 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000602 return LI->getPointerOperand();
603 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000604 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
605 if (!ClInstrumentWrites) return NULL;
606 *IsWrite = true;
607 return SI->getPointerOperand();
608 }
609 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
610 if (!ClInstrumentAtomics) return NULL;
611 *IsWrite = true;
612 return RMW->getPointerOperand();
613 }
614 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
615 if (!ClInstrumentAtomics) return NULL;
616 *IsWrite = true;
617 return XCHG->getPointerOperand();
618 }
619 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000620}
621
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000622void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000623 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000624 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
625 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000626 if (ClOpt && ClOptGlobals) {
627 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
628 // If initialization order checking is disabled, a simple access to a
629 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000630 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000631 return;
632 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000633 // have to instrument it. However, if a global does not have initailizer
634 // at all, we assume it has dynamic initializer (in other TU).
635 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000636 return;
637 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000638 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000639
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000640 Type *OrigPtrTy = Addr->getType();
641 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
642
643 assert(OrigTy->isSized());
Kostya Serebryany605ff662013-02-18 13:47:02 +0000644 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000645
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000646 assert((TypeSize % 8) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000647
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000648 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
649 if (TypeSize == 8 || TypeSize == 16 ||
650 TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
651 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
652 // Instrument unusual size (but still multiple of 8).
653 // We can not do it with a single check, so we do 1-byte check for the first
654 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
655 // to report the actual access size.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000656 IRBuilder<> IRB(I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000657 Value *LastByte = IRB.CreateIntToPtr(
658 IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
659 ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
660 OrigPtrTy);
661 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
662 instrumentAddress(I, I, Addr, 8, IsWrite, Size);
663 instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000664}
665
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000666// Validate the result of Module::getOrInsertFunction called for an interface
667// function of AddressSanitizer. If the instrumented module defines a function
668// with the same name, their prototypes must match, otherwise
669// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000670static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000671 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
672 FuncOrBitcast->dump();
673 report_fatal_error("trying to redefine an AddressSanitizer "
674 "interface function");
675}
676
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000677Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000678 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000679 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000680 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000681 CallInst *Call = SizeArgument
682 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
683 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
684
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000685 // We don't do Call->setDoesNotReturn() because the BB already has
686 // UnreachableInst at the end.
687 // This EmptyAsm is required to avoid callback merge.
688 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000689 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000690}
691
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000692Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000693 Value *ShadowValue,
694 uint32_t TypeSize) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000695 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000696 // Addr & (Granularity - 1)
697 Value *LastAccessedByte = IRB.CreateAnd(
698 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
699 // (Addr & (Granularity - 1)) + size - 1
700 if (TypeSize / 8 > 1)
701 LastAccessedByte = IRB.CreateAdd(
702 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
703 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
704 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000705 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000706 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
707 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
708}
709
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000710void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000711 Instruction *InsertBefore,
712 Value *Addr, uint32_t TypeSize,
713 bool IsWrite, Value *SizeArgument) {
714 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000715 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
716
717 Type *ShadowTy = IntegerType::get(
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000718 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000719 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
720 Value *ShadowPtr = memToShadow(AddrLong, IRB);
721 Value *CmpVal = Constant::getNullValue(ShadowTy);
722 Value *ShadowValue = IRB.CreateLoad(
723 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
724
725 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000726 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000727 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000728 TerminatorInst *CrashTerm = 0;
729
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000730 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000731 TerminatorInst *CheckTerm =
732 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000733 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000734 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000735 IRB.SetInsertPoint(CheckTerm);
736 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000737 BasicBlock *CrashBlock =
738 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000739 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000740 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
741 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000742 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000743 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000744 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000745
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000746 Instruction *Crash = generateCrashCode(
747 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000748 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000749}
750
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000751void AddressSanitizerModule::createInitializerPoisonCalls(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000752 Module &M, Value *FirstAddr, Value *LastAddr) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000753 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
754 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
755 // If that function is not present, this TU contains no globals, or they have
756 // all been optimized away
757 if (!GlobalInit)
758 return;
759
760 // Set up the arguments to our poison/unpoison functions.
761 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
762
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000763 // Add a call to poison all external globals before the given function starts.
764 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
765
766 // Add calls to unpoison all globals before each return instruction.
767 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
768 I != E; ++I) {
769 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
770 CallInst::Create(AsanUnpoisonGlobals, "", RI);
771 }
772 }
773}
774
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000775bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000776 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000777 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000778
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000779 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000780 if (!Ty->isSized()) return false;
781 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000782 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000783 // Touch only those globals that will not be defined in other modules.
784 // Don't handle ODR type linkages since other modules may be built w/o asan.
785 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
786 G->getLinkage() != GlobalVariable::PrivateLinkage &&
787 G->getLinkage() != GlobalVariable::InternalLinkage)
788 return false;
789 // Two problems with thread-locals:
790 // - The address of the main thread's copy can't be computed at link-time.
791 // - Need to poison all copies, not just the main thread's one.
792 if (G->isThreadLocal())
793 return false;
794 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000795 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000796
797 // Ignore all the globals with the names starting with "\01L_OBJC_".
798 // Many of those are put into the .cstring section. The linker compresses
799 // that section by removing the spare \0s after the string terminator, so
800 // our redzones get broken.
801 if ((G->getName().find("\01L_OBJC_") == 0) ||
802 (G->getName().find("\01l_OBJC_") == 0)) {
803 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
804 return false;
805 }
806
807 if (G->hasSection()) {
808 StringRef Section(G->getSection());
809 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
810 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
811 // them.
812 if ((Section.find("__OBJC,") == 0) ||
813 (Section.find("__DATA, __objc_") == 0)) {
814 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
815 return false;
816 }
817 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
818 // Constant CFString instances are compiled in the following way:
819 // -- the string buffer is emitted into
820 // __TEXT,__cstring,cstring_literals
821 // -- the constant NSConstantString structure referencing that buffer
822 // is placed into __DATA,__cfstring
823 // Therefore there's no point in placing redzones into __DATA,__cfstring.
824 // Moreover, it causes the linker to crash on OS X 10.7
825 if (Section.find("__DATA,__cfstring") == 0) {
826 DEBUG(dbgs() << "Ignoring CFString: " << *G);
827 return false;
828 }
829 }
830
831 return true;
832}
833
Alexey Samsonov46848582012-12-25 12:28:20 +0000834void AddressSanitizerModule::initializeCallbacks(Module &M) {
835 IRBuilder<> IRB(*C);
836 // Declare our poisoning and unpoisoning functions.
837 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
838 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
839 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
840 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
841 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
842 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
843 // Declare functions that register/unregister globals.
844 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
845 kAsanRegisterGlobalsName, IRB.getVoidTy(),
846 IntptrTy, IntptrTy, NULL));
847 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
848 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
849 kAsanUnregisterGlobalsName,
850 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
851 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
852}
853
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000854// This function replaces all global variables with new variables that have
855// trailing redzones. It also creates a function that poisons
856// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000857bool AddressSanitizerModule::runOnModule(Module &M) {
858 if (!ClGlobals) return false;
859 TD = getAnalysisIfAvailable<DataLayout>();
860 if (!TD)
861 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000862 BL.reset(new BlackList(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000863 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000864 C = &(M.getContext());
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000865 int LongSize = TD->getPointerSizeInBits();
866 IntptrTy = Type::getIntNTy(*C, LongSize);
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000867 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov46848582012-12-25 12:28:20 +0000868 initializeCallbacks(M);
869 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000870
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000871 SmallVector<GlobalVariable *, 16> GlobalsToChange;
872
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000873 for (Module::GlobalListType::iterator G = M.global_begin(),
874 E = M.global_end(); G != E; ++G) {
875 if (ShouldInstrumentGlobal(G))
876 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000877 }
878
879 size_t n = GlobalsToChange.size();
880 if (n == 0) return false;
881
882 // A global is described by a structure
883 // size_t beg;
884 // size_t size;
885 // size_t size_with_redzone;
886 // const char *name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000887 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000888 // We initialize an array of such structures and pass it to a run-time call.
889 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000890 IntptrTy, IntptrTy,
891 IntptrTy, NULL);
892 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000893
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000894
895 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
896 assert(CtorFunc);
897 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000898
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000899 // The addresses of the first and last dynamically initialized globals in
900 // this TU. Used in initialization order checking.
901 Value *FirstDynamic = 0, *LastDynamic = 0;
902
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000903 for (size_t i = 0; i < n; i++) {
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000904 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000905 GlobalVariable *G = GlobalsToChange[i];
906 PointerType *PtrTy = cast<PointerType>(G->getType());
907 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000908 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000909 uint64_t MinRZ = RedzoneSize();
Kostya Serebryany63f08462013-01-24 10:35:40 +0000910 // MinRZ <= RZ <= kMaxGlobalRedzone
911 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000912 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany63f08462013-01-24 10:35:40 +0000913 std::min(kMaxGlobalRedzone,
914 (SizeInBytes / MinRZ / 4) * MinRZ));
915 uint64_t RightRedzoneSize = RZ;
916 // Round up to MinRZ
917 if (SizeInBytes % MinRZ)
918 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
919 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000920 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000921 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000922 bool GlobalHasDynamicInitializer =
923 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000924 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000925 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000926
927 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
928 Constant *NewInitializer = ConstantStruct::get(
929 NewTy, G->getInitializer(),
930 Constant::getNullValue(RightRedZoneTy), NULL);
931
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000932 SmallString<2048> DescriptionOfGlobal = G->getName();
933 DescriptionOfGlobal += " (";
934 DescriptionOfGlobal += M.getModuleIdentifier();
935 DescriptionOfGlobal += ")";
936 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000937
938 // Create a new global variable with enough space for a redzone.
939 GlobalVariable *NewGlobal = new GlobalVariable(
940 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000941 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000942 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany63f08462013-01-24 10:35:40 +0000943 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000944
945 Value *Indices2[2];
946 Indices2[0] = IRB.getInt32(0);
947 Indices2[1] = IRB.getInt32(0);
948
949 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000950 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000951 NewGlobal->takeName(G);
952 G->eraseFromParent();
953
954 Initializers[i] = ConstantStruct::get(
955 GlobalStructTy,
956 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
957 ConstantInt::get(IntptrTy, SizeInBytes),
958 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
959 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000960 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000961 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000962
963 // Populate the first and last globals declared in this TU.
Alexey Samsonovee548272012-11-29 18:14:24 +0000964 if (CheckInitOrder && GlobalHasDynamicInitializer) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000965 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
966 if (FirstDynamic == 0)
967 FirstDynamic = LastDynamic;
968 }
969
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000970 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000971 }
972
973 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
974 GlobalVariable *AllGlobals = new GlobalVariable(
975 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
976 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
977
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000978 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovee548272012-11-29 18:14:24 +0000979 if (CheckInitOrder && FirstDynamic && LastDynamic)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000980 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000981 IRB.CreateCall2(AsanRegisterGlobals,
982 IRB.CreatePointerCast(AllGlobals, IntptrTy),
983 ConstantInt::get(IntptrTy, n));
984
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000985 // We also need to unregister globals at the end, e.g. when a shared library
986 // gets closed.
987 Function *AsanDtorFunction = Function::Create(
988 FunctionType::get(Type::getVoidTy(*C), false),
989 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
990 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
991 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000992 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
993 IRB.CreatePointerCast(AllGlobals, IntptrTy),
994 ConstantInt::get(IntptrTy, n));
995 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
996
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000997 DEBUG(dbgs() << M);
998 return true;
999}
1000
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001001void AddressSanitizer::initializeCallbacks(Module &M) {
1002 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001003 // Create __asan_report* callbacks.
1004 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1005 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1006 AccessSizeIndex++) {
1007 // IsWrite and TypeSize are encoded in the function name.
1008 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1009 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +00001010 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +00001011 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1012 checkInterfaceFunction(M.getOrInsertFunction(
1013 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001014 }
1015 }
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +00001016 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1017 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1018 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1019 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001020
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001021 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1022 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +00001023 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1024 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1025 StringRef(""), StringRef(""),
1026 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001027}
1028
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001029void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001030 // Tell the values of mapping offset and scale to the run-time.
1031 GlobalValue *asan_mapping_offset =
1032 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1033 ConstantInt::get(IntptrTy, Mapping.Offset),
1034 kAsanMappingOffsetName);
1035 // Read the global, otherwise it may be optimized away.
1036 IRB.CreateLoad(asan_mapping_offset, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001037
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001038 GlobalValue *asan_mapping_scale =
1039 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1040 ConstantInt::get(IntptrTy, Mapping.Scale),
1041 kAsanMappingScaleName);
1042 // Read the global, otherwise it may be optimized away.
1043 IRB.CreateLoad(asan_mapping_scale, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001044}
1045
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001046// virtual
1047bool AddressSanitizer::doInitialization(Module &M) {
1048 // Initialize the private fields. No one has accessed them before.
1049 TD = getAnalysisIfAvailable<DataLayout>();
1050
1051 if (!TD)
1052 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +00001053 BL.reset(new BlackList(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001054 DynamicallyInitializedGlobals.Init(M);
1055
1056 C = &(M.getContext());
1057 LongSize = TD->getPointerSizeInBits();
1058 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001059
1060 AsanCtorFunction = Function::Create(
1061 FunctionType::get(Type::getVoidTy(*C), false),
1062 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1063 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1064 // call __asan_init in the module ctor.
1065 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1066 AsanInitFunction = checkInterfaceFunction(
1067 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1068 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1069 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001070
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001071 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001072 emitShadowMapping(M, IRB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001073
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001074 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001075 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001076}
1077
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001078bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1079 // For each NSObject descendant having a +load method, this method is invoked
1080 // by the ObjC runtime before any of the static constructors is called.
1081 // Therefore we need to instrument such methods with a call to __asan_init
1082 // at the beginning in order to initialize our runtime before any access to
1083 // the shadow memory.
1084 // We cannot just ignore these methods, because they may call other
1085 // instrumented functions.
1086 if (F.getName().find(" load]") != std::string::npos) {
1087 IRBuilder<> IRB(F.begin()->begin());
1088 IRB.CreateCall(AsanInitFunction);
1089 return true;
1090 }
1091 return false;
1092}
1093
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001094bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001095 if (BL->isIn(F)) return false;
1096 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001097 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001098 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001099
1100 // If needed, insert __asan_init before checking for AddressSafety attr.
1101 maybeInsertAsanInitAtFunctionEntry(F);
1102
Bill Wendling831737d2012-12-30 10:32:01 +00001103 if (!F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1104 Attribute::AddressSafety))
Bill Wendling67658342012-10-09 07:45:08 +00001105 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001106
1107 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1108 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001109
1110 // We want to instrument every address only once per basic block (unless there
1111 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001112 SmallSet<Value*, 16> TempsToInstrument;
1113 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001114 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001115 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001116
1117 // Fill the set of memory operations to instrument.
1118 for (Function::iterator FI = F.begin(), FE = F.end();
1119 FI != FE; ++FI) {
1120 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001121 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001122 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1123 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001124 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001125 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001126 if (ClOpt && ClOptSameTemp) {
1127 if (!TempsToInstrument.insert(Addr))
1128 continue; // We've seen this temp in the current BB.
1129 }
1130 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1131 // ok, take it.
1132 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001133 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001134 // A call inside BB.
1135 TempsToInstrument.clear();
Kostya Serebryanya17babb2012-11-30 11:08:59 +00001136 if (CI->doesNotReturn()) {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001137 NoReturnCalls.push_back(CI);
1138 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001139 }
1140 continue;
1141 }
1142 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001143 NumInsnsPerBB++;
1144 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1145 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001146 }
1147 }
1148
1149 // Instrument.
1150 int NumInstrumented = 0;
1151 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1152 Instruction *Inst = ToInstrument[i];
1153 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1154 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001155 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001156 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001157 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001158 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001159 }
1160 NumInstrumented++;
1161 }
1162
Alexey Samsonov59cca132012-12-25 12:04:36 +00001163 FunctionStackPoisoner FSP(F, *this);
1164 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001165
1166 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1167 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1168 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1169 Instruction *CI = NoReturnCalls[i];
1170 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001171 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001172 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001173 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001174
1175 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001176}
1177
1178static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1179 if (ShadowRedzoneSize == 1) return PoisonByte;
1180 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1181 if (ShadowRedzoneSize == 4)
1182 return (PoisonByte << 24) + (PoisonByte << 16) +
1183 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001184 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001185}
1186
1187static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1188 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001189 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001190 size_t ShadowGranularity,
1191 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001192 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001193 i+= ShadowGranularity, Shadow++) {
1194 if (i + ShadowGranularity <= Size) {
1195 *Shadow = 0; // fully addressable
1196 } else if (i >= Size) {
1197 *Shadow = Magic; // unaddressable
1198 } else {
1199 *Shadow = Size - i; // first Size-i bytes are addressable
1200 }
1201 }
1202}
1203
Alexey Samsonov59cca132012-12-25 12:04:36 +00001204// Workaround for bug 11395: we don't want to instrument stack in functions
1205// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1206// FIXME: remove once the bug 11395 is fixed.
1207bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1208 if (LongSize != 32) return false;
1209 CallInst *CI = dyn_cast<CallInst>(I);
1210 if (!CI || !CI->isInlineAsm()) return false;
1211 if (CI->getNumArgOperands() <= 5) return false;
1212 // We have inline assembly with quite a few arguments.
1213 return true;
1214}
1215
1216void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1217 IRBuilder<> IRB(*C);
1218 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
1219 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
1220 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
1221 kAsanStackFreeName, IRB.getVoidTy(),
1222 IntptrTy, IntptrTy, IntptrTy, NULL));
1223 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1224 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1225 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1226 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1227}
1228
1229void FunctionStackPoisoner::poisonRedZones(
1230 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
1231 bool DoPoison) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001232 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001233 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1234 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1235 Type *RZPtrTy = PointerType::get(RZTy, 0);
1236
1237 Value *PoisonLeft = ConstantInt::get(RZTy,
1238 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1239 Value *PoisonMid = ConstantInt::get(RZTy,
1240 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1241 Value *PoisonRight = ConstantInt::get(RZTy,
1242 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1243
1244 // poison the first red zone.
1245 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1246
1247 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001248 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001249 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1250 AllocaInst *AI = AllocaVec[i];
1251 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1252 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001253 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001254 Value *Ptr = NULL;
1255
1256 Pos += AlignedSize;
1257
1258 assert(ShadowBase->getType() == IntptrTy);
1259 if (SizeInBytes < AlignedSize) {
1260 // Poison the partial redzone at right
1261 Ptr = IRB.CreateAdd(
1262 ShadowBase, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001263 (Pos >> Mapping.Scale) - ShadowRZSize));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001264 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001265 uint32_t Poison = 0;
1266 if (DoPoison) {
1267 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001268 RedzoneSize(),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001269 1ULL << Mapping.Scale,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001270 kAsanStackPartialRedzoneMagic);
1271 }
1272 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1273 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1274 }
1275
1276 // Poison the full redzone at right.
1277 Ptr = IRB.CreateAdd(ShadowBase,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001278 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001279 bool LastAlloca = (i == AllocaVec.size() - 1);
1280 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001281 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1282
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001283 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001284 }
1285}
1286
Alexey Samsonov59cca132012-12-25 12:04:36 +00001287void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001288 uint64_t LocalStackSize = TotalStackSize +
1289 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001290
Alexey Samsonov59cca132012-12-25 12:04:36 +00001291 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001292 && LocalStackSize <= kMaxStackMallocSize;
1293
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001294 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001295 Instruction *InsBefore = AllocaVec[0];
1296 IRBuilder<> IRB(InsBefore);
1297
1298
1299 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1300 AllocaInst *MyAlloca =
1301 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001302 if (ClRealignStack && StackAlignment < RedzoneSize())
1303 StackAlignment = RedzoneSize();
1304 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001305 assert(MyAlloca->isStaticAlloca());
1306 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1307 Value *LocalStackBase = OrigStackBase;
1308
1309 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001310 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1311 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1312 }
1313
1314 // This string will be parsed by the run-time (DescribeStackAddress).
1315 SmallString<2048> StackDescriptionStorage;
1316 raw_svector_ostream StackDescription(StackDescriptionStorage);
1317 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1318
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001319 // Insert poison calls for lifetime intrinsics for alloca.
1320 bool HavePoisonedAllocas = false;
1321 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1322 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1323 IntrinsicInst *II = APC.InsBefore;
1324 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1325 assert(AI);
1326 IRBuilder<> IRB(II);
1327 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1328 HavePoisonedAllocas |= APC.DoPoison;
1329 }
1330
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001331 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001332 // Replace Alloca instructions with base+offset.
1333 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1334 AllocaInst *AI = AllocaVec[i];
1335 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1336 StringRef Name = AI->getName();
1337 StackDescription << Pos << " " << SizeInBytes << " "
1338 << Name.size() << " " << Name << " ";
1339 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001340 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001341 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001342 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001343 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001344 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001345 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001346 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001347 }
1348 assert(Pos == LocalStackSize);
1349
1350 // Write the Magic value and the frame description constant to the redzone.
1351 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1352 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1353 BasePlus0);
1354 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
Alexey Samsonov59cca132012-12-25 12:04:36 +00001355 ConstantInt::get(IntptrTy,
1356 ASan.LongSize/8));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001357 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001358 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001359 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001360 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1361 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001362 IRB.CreateStore(Description, BasePlus1);
1363
1364 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001365 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1366 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001367
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001368 // Unpoison the stack before all ret instructions.
1369 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1370 Instruction *Ret = RetVec[i];
1371 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001372 // Mark the current frame as retired.
1373 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1374 BasePlus0);
1375 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001376 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001377 if (DoStackMalloc) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001378 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001379 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1380 ConstantInt::get(IntptrTy, LocalStackSize),
1381 OrigStackBase);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001382 } else if (HavePoisonedAllocas) {
1383 // If we poisoned some allocas in llvm.lifetime analysis,
1384 // unpoison whole stack frame now.
1385 assert(LocalStackBase == OrigStackBase);
1386 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001387 }
1388 }
1389
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001390 // We are done. Remove the old unused alloca instructions.
1391 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1392 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001393}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001394
Alexey Samsonov59cca132012-12-25 12:04:36 +00001395void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1396 IRBuilder<> IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001397 // For now just insert the call to ASan runtime.
1398 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1399 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1400 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1401 : AsanUnpoisonStackMemoryFunc,
1402 AddrArg, SizeArg);
1403}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001404
1405// Handling llvm.lifetime intrinsics for a given %alloca:
1406// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1407// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1408// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1409// could be poisoned by previous llvm.lifetime.end instruction, as the
1410// variable may go in and out of scope several times, e.g. in loops).
1411// (3) if we poisoned at least one %alloca in a function,
1412// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001413
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001414AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1415 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1416 // We're intested only in allocas we can handle.
1417 return isInterestingAlloca(*AI) ? AI : 0;
1418 // See if we've already calculated (or started to calculate) alloca for a
1419 // given value.
1420 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1421 if (I != AllocaForValue.end())
1422 return I->second;
1423 // Store 0 while we're calculating alloca for value V to avoid
1424 // infinite recursion if the value references itself.
1425 AllocaForValue[V] = 0;
1426 AllocaInst *Res = 0;
1427 if (CastInst *CI = dyn_cast<CastInst>(V))
1428 Res = findAllocaForValue(CI->getOperand(0));
1429 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1430 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1431 Value *IncValue = PN->getIncomingValue(i);
1432 // Allow self-referencing phi-nodes.
1433 if (IncValue == PN) continue;
1434 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1435 // AI for incoming values should exist and should all be equal.
1436 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1437 return 0;
1438 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001439 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001440 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001441 if (Res != 0)
1442 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001443 return Res;
1444}