blob: 67a8325b0ccd351f75ae908e2485f5d935e40325 [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 Serebryany1479c9b2013-02-20 12:35:15 +000038#include "llvm/Support/CallSite.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 Serebryany3e1d45b2013-06-03 14:46:56 +000042#include "llvm/Support/Endian.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000043#include "llvm/Support/raw_ostream.h"
44#include "llvm/Support/system_error.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruth90230c82013-01-19 08:03:47 +000046#include "llvm/Transforms/Utils/BlackList.h"
Kostya Serebryany20985712013-06-26 09:18:17 +000047#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000048#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000049#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000050#include <algorithm>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000051#include <string>
Kostya Serebryany800e03f2011-11-16 01:35:23 +000052
53using namespace llvm;
54
55static const uint64_t kDefaultShadowScale = 3;
56static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
57static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryany117de482013-02-11 14:36:01 +000058static const uint64_t kDefaultShort64bitShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany48a615f2013-01-23 12:54:55 +000059static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +000060static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000061
62static const size_t kMaxStackMallocSize = 1 << 16; // 64K
63static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
64static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
65
66static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000067static const char *kAsanModuleDtorName = "asan.module_dtor";
68static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000069static const char *kAsanReportErrorTemplate = "__asan_report_";
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +000070static const char *kAsanReportLoadN = "__asan_report_load_n";
71static const char *kAsanReportStoreN = "__asan_report_store_n";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000072static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000073static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +000074static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
75static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kostya Serebryany30160562013-03-22 10:37:20 +000076static const char *kAsanInitName = "__asan_init_v3";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000077static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000078static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
79static const char *kAsanMappingScaleName = "__asan_mapping_scale";
80static const char *kAsanStackMallocName = "__asan_stack_malloc";
81static const char *kAsanStackFreeName = "__asan_stack_free";
Kostya Serebryany51c7c652012-11-20 14:16:08 +000082static const char *kAsanGenPrefix = "__asan_gen_";
Alexey Samsonovf985f442012-12-04 01:34:23 +000083static const char *kAsanPoisonStackMemoryName = "__asan_poison_stack_memory";
84static const char *kAsanUnpoisonStackMemoryName =
85 "__asan_unpoison_stack_memory";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000086
87static const int kAsanStackLeftRedzoneMagic = 0xf1;
88static const int kAsanStackMidRedzoneMagic = 0xf2;
89static const int kAsanStackRightRedzoneMagic = 0xf3;
90static const int kAsanStackPartialRedzoneMagic = 0xf4;
91
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000092// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
93static const size_t kNumberOfAccessSizes = 5;
94
Kostya Serebryany800e03f2011-11-16 01:35:23 +000095// Command-line flags.
96
97// This flag may need to be replaced with -f[no-]asan-reads.
98static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
99 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
100static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
101 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000102static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
103 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
104 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000105static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
106 cl::desc("use instrumentation with slow path for all accesses"),
107 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000108// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000109// in any given BB. Normally, this should be set to unlimited (INT_MAX),
110// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
111// set it to 10000.
112static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
113 cl::init(10000),
114 cl::desc("maximal number of instructions to instrument in any given BB"),
115 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000116// This flag may need to be replaced with -f[no]asan-stack.
117static cl::opt<bool> ClStack("asan-stack",
118 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
119// This flag may need to be replaced with -f[no]asan-use-after-return.
120static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
121 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
122// This flag may need to be replaced with -f[no]asan-globals.
123static cl::opt<bool> ClGlobals("asan-globals",
124 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000125static cl::opt<bool> ClInitializers("asan-initialization-order",
126 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000127static cl::opt<bool> ClMemIntrin("asan-memintrin",
128 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Kostya Serebryany6c554122012-12-04 06:14:01 +0000129static cl::opt<bool> ClRealignStack("asan-realign-stack",
130 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000131static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
132 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000133 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000134
Kostya Serebryany20985712013-06-26 09:18:17 +0000135// This is an experimental feature that will allow to choose between
136// instrumented and non-instrumented code at link-time.
137// If this option is on, just before instrumenting a function we create its
138// clone; if the function is not changed by asan the clone is deleted.
139// If we end up with a clone, we put the instrumented function into a section
140// called "ASAN" and the uninstrumented function into a section called "NOASAN".
141//
142// This is still a prototype, we need to figure out a way to keep two copies of
143// a function so that the linker can easily choose one of them.
144static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
145 cl::desc("Keep uninstrumented copies of functions"),
146 cl::Hidden, cl::init(false));
147
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000148// These flags allow to change the shadow mapping.
149// The shadow mapping looks like
150// Shadow = (Mem >> scale) + (1 << offset_log)
151static cl::opt<int> ClMappingScale("asan-mapping-scale",
152 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
153static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
154 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
Kostya Serebryany117de482013-02-11 14:36:01 +0000155static cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
156 cl::desc("Use short immediate constant as the mapping offset for 64bit"),
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000157 cl::Hidden, cl::init(true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000158
159// Optimization flags. Not user visible, used mostly for testing
160// and benchmarking the tool.
161static cl::opt<bool> ClOpt("asan-opt",
162 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
163static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
164 cl::desc("Instrument the same temp just once"), cl::Hidden,
165 cl::init(true));
166static cl::opt<bool> ClOptGlobals("asan-opt-globals",
167 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
168
Alexey Samsonovee548272012-11-29 18:14:24 +0000169static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
170 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
171 cl::Hidden, cl::init(false));
172
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000173// Debug flags.
174static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
175 cl::init(0));
176static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
177 cl::Hidden, cl::init(0));
178static cl::opt<std::string> ClDebugFunc("asan-debug-func",
179 cl::Hidden, cl::desc("Debug func"));
180static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
181 cl::Hidden, cl::init(-1));
182static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
183 cl::Hidden, cl::init(-1));
184
185namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000186/// A set of dynamically initialized globals extracted from metadata.
187class SetOfDynamicallyInitializedGlobals {
188 public:
189 void Init(Module& M) {
190 // Clang generates metadata identifying all dynamically initialized globals.
191 NamedMDNode *DynamicGlobals =
192 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
193 if (!DynamicGlobals)
194 return;
195 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
196 MDNode *MDN = DynamicGlobals->getOperand(i);
197 assert(MDN->getNumOperands() == 1);
198 Value *VG = MDN->getOperand(0);
199 // The optimizer may optimize away a global entirely, in which case we
200 // cannot instrument access to it.
201 if (!VG)
202 continue;
203 DynInitGlobals.insert(cast<GlobalVariable>(VG));
204 }
205 }
206 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
207 private:
208 SmallSet<GlobalValue*, 32> DynInitGlobals;
209};
210
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000211/// This struct defines the shadow mapping using the rule:
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000212/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000213struct ShadowMapping {
214 int Scale;
215 uint64_t Offset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000216 bool OrShadowOffset;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000217};
218
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000219static ShadowMapping getShadowMapping(const Module &M, int LongSize,
220 bool ZeroBaseShadow) {
221 llvm::Triple TargetTriple(M.getTargetTriple());
222 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000223 bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000224 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64;
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000225 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +0000226 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
227 TargetTriple.getArch() == llvm::Triple::mipsel;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000228
229 ShadowMapping Mapping;
230
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000231 // OR-ing shadow offset if more efficient (at least on x86),
232 // but on ppc64 we have to use add since the shadow offset is not neccesary
233 // 1/8-th of the address space.
Kostya Serebryany117de482013-02-11 14:36:01 +0000234 Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000235
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000236 Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +0000237 (LongSize == 32 ?
238 (IsMIPS32 ? kMIPS32_ShadowOffset32 : kDefaultShadowOffset32) :
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000239 IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000240 if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000241 assert(LongSize == 64);
Kostya Serebryany117de482013-02-11 14:36:01 +0000242 Mapping.Offset = kDefaultShort64bitShadowOffset;
Kostya Serebryany39f02942013-02-13 05:14:12 +0000243 }
244 if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000245 // Zero offset log is the special case.
246 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
247 }
248
249 Mapping.Scale = kDefaultShadowScale;
250 if (ClMappingScale) {
251 Mapping.Scale = ClMappingScale;
252 }
253
254 return Mapping;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000255}
256
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000257static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000258 // Redzone used for stack and globals is at least 32 bytes.
259 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000260 return std::max(32U, 1U << MappingScale);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000261}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000262
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000263/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000264struct AddressSanitizer : public FunctionPass {
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000265 AddressSanitizer(bool CheckInitOrder = true,
Alexey Samsonovee548272012-11-29 18:14:24 +0000266 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000267 bool CheckLifetime = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000268 StringRef BlacklistFile = StringRef(),
269 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000270 : FunctionPass(ID),
271 CheckInitOrder(CheckInitOrder || ClInitializers),
272 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000273 CheckLifetime(CheckLifetime || ClCheckLifetime),
274 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000275 : BlacklistFile),
276 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000277 virtual const char *getPassName() const {
278 return "AddressSanitizerFunctionPass";
279 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000280 void instrumentMop(Instruction *I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000281 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
282 Value *Addr, uint32_t TypeSize, bool IsWrite,
283 Value *SizeArgument);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000284 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
285 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000286 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000287 bool IsWrite, size_t AccessSizeIndex,
288 Value *SizeArgument);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000289 bool instrumentMemIntrinsic(MemIntrinsic *MI);
290 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000291 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000292 Instruction *InsertBefore, bool IsWrite);
293 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000294 bool runOnFunction(Function &F);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000295 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000296 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000297 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000298 static char ID; // Pass identification, replacement for typeid
299
300 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000301 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000302
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000303 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000304 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000305 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000306
Alexey Samsonovee548272012-11-29 18:14:24 +0000307 bool CheckInitOrder;
308 bool CheckUseAfterReturn;
309 bool CheckLifetime;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000310 SmallString<64> BlacklistFile;
311 bool ZeroBaseShadow;
312
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000313 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000314 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000315 int LongSize;
316 Type *IntptrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000317 ShadowMapping Mapping;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000318 Function *AsanCtorFunction;
319 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000320 Function *AsanHandleNoReturnFunc;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000321 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000322 // This array is indexed by AccessIsWrite and log2(AccessSize).
323 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000324 // This array is indexed by AccessIsWrite.
325 Function *AsanErrorCallbackSized[2];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000326 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000327 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000328
329 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000330};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000331
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000332class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000333 public:
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000334 AddressSanitizerModule(bool CheckInitOrder = true,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000335 StringRef BlacklistFile = StringRef(),
336 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000337 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000338 CheckInitOrder(CheckInitOrder || ClInitializers),
339 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000340 : BlacklistFile),
341 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000342 bool runOnModule(Module &M);
343 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000344 virtual const char *getPassName() const {
345 return "AddressSanitizerModule";
346 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000347
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000348 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000349 void initializeCallbacks(Module &M);
350
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000351 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000352 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000353 size_t RedzoneSize() const {
354 return RedzoneSizeForScale(Mapping.Scale);
355 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000356
Alexey Samsonovee548272012-11-29 18:14:24 +0000357 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000358 SmallString<64> BlacklistFile;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000359 bool ZeroBaseShadow;
360
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000361 OwningPtr<BlackList> BL;
362 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
363 Type *IntptrTy;
364 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000365 DataLayout *TD;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000366 ShadowMapping Mapping;
Alexey Samsonov46848582012-12-25 12:28:20 +0000367 Function *AsanPoisonGlobals;
368 Function *AsanUnpoisonGlobals;
369 Function *AsanRegisterGlobals;
370 Function *AsanUnregisterGlobals;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000371};
372
Alexey Samsonov59cca132012-12-25 12:04:36 +0000373// Stack poisoning does not play well with exception handling.
374// When an exception is thrown, we essentially bypass the code
375// that unpoisones the stack. This is why the run-time library has
376// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
377// stack in the interceptor. This however does not work inside the
378// actual function which catches the exception. Most likely because the
379// compiler hoists the load of the shadow value somewhere too high.
380// This causes asan to report a non-existing bug on 453.povray.
381// It sounds like an LLVM bug.
382struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
383 Function &F;
384 AddressSanitizer &ASan;
385 DIBuilder DIB;
386 LLVMContext *C;
387 Type *IntptrTy;
388 Type *IntptrPtrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000389 ShadowMapping Mapping;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000390
391 SmallVector<AllocaInst*, 16> AllocaVec;
392 SmallVector<Instruction*, 8> RetVec;
393 uint64_t TotalStackSize;
394 unsigned StackAlignment;
395
396 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
397 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
398
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000399 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
400 struct AllocaPoisonCall {
401 IntrinsicInst *InsBefore;
402 uint64_t Size;
403 bool DoPoison;
404 };
405 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
406
407 // Maps Value to an AllocaInst from which the Value is originated.
408 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
409 AllocaForValueMapTy AllocaForValue;
410
Alexey Samsonov59cca132012-12-25 12:04:36 +0000411 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
412 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
413 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000414 Mapping(ASan.Mapping),
415 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov59cca132012-12-25 12:04:36 +0000416
417 bool runOnFunction() {
418 if (!ClStack) return false;
419 // Collect alloca, ret, lifetime instructions etc.
420 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
421 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
422 BasicBlock *BB = *DI;
423 visit(*BB);
424 }
425 if (AllocaVec.empty()) return false;
426
427 initializeCallbacks(*F.getParent());
428
429 poisonStack();
430
431 if (ClDebugStack) {
432 DEBUG(dbgs() << F);
433 }
434 return true;
435 }
436
437 // Finds all static Alloca instructions and puts
438 // poisoned red zones around all of them.
439 // Then unpoison everything back before the function returns.
440 void poisonStack();
441
442 // ----------------------- Visitors.
443 /// \brief Collect all Ret instructions.
444 void visitReturnInst(ReturnInst &RI) {
445 RetVec.push_back(&RI);
446 }
447
448 /// \brief Collect Alloca instructions we want (and can) handle.
449 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000450 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000451
452 StackAlignment = std::max(StackAlignment, AI.getAlignment());
453 AllocaVec.push_back(&AI);
454 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
455 TotalStackSize += AlignedSize;
456 }
457
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000458 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
459 /// errors.
460 void visitIntrinsicInst(IntrinsicInst &II) {
461 if (!ASan.CheckLifetime) return;
462 Intrinsic::ID ID = II.getIntrinsicID();
463 if (ID != Intrinsic::lifetime_start &&
464 ID != Intrinsic::lifetime_end)
465 return;
466 // Found lifetime intrinsic, add ASan instrumentation if necessary.
467 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
468 // If size argument is undefined, don't do anything.
469 if (Size->isMinusOne()) return;
470 // Check that size doesn't saturate uint64_t and can
471 // be stored in IntptrTy.
472 const uint64_t SizeValue = Size->getValue().getLimitedValue();
473 if (SizeValue == ~0ULL ||
474 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
475 return;
476 // Find alloca instruction that corresponds to llvm.lifetime argument.
477 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
478 if (!AI) return;
479 bool DoPoison = (ID == Intrinsic::lifetime_end);
480 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
481 AllocaPoisonCallVec.push_back(APC);
482 }
483
Alexey Samsonov59cca132012-12-25 12:04:36 +0000484 // ---------------------- Helpers.
485 void initializeCallbacks(Module &M);
486
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000487 // Check if we want (and can) handle this alloca.
488 bool isInterestingAlloca(AllocaInst &AI) {
489 return (!AI.isArrayAllocation() &&
490 AI.isStaticAlloca() &&
491 AI.getAllocatedType()->isSized());
492 }
493
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000494 size_t RedzoneSize() const {
495 return RedzoneSizeForScale(Mapping.Scale);
496 }
Alexey Samsonov59cca132012-12-25 12:04:36 +0000497 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
498 Type *Ty = AI->getAllocatedType();
499 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
500 return SizeInBytes;
501 }
502 uint64_t getAlignedSize(uint64_t SizeInBytes) {
503 size_t RZ = RedzoneSize();
504 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
505 }
506 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
507 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
508 return getAlignedSize(SizeInBytes);
509 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000510 /// Finds alloca where the value comes from.
511 AllocaInst *findAllocaForValue(Value *V);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000512 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
513 Value *ShadowBase, bool DoPoison);
514 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000515};
516
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000517} // namespace
518
519char AddressSanitizer::ID = 0;
520INITIALIZE_PASS(AddressSanitizer, "asan",
521 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
522 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000523FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000524 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000525 StringRef BlacklistFile, bool ZeroBaseShadow) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000526 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000527 CheckLifetime, BlacklistFile, ZeroBaseShadow);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000528}
529
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000530char AddressSanitizerModule::ID = 0;
531INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
532 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
533 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000534ModulePass *llvm::createAddressSanitizerModulePass(
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000535 bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
536 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
537 ZeroBaseShadow);
Alexander Potapenko25878042012-01-23 11:22:43 +0000538}
539
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000540static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerc6af2432013-05-24 22:23:49 +0000541 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000542 assert(Res < kNumberOfAccessSizes);
543 return Res;
544}
545
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000546// Create a constant for Str so that we can pass it to the run-time lib.
547static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000548 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany51116272013-03-18 09:38:39 +0000549 GlobalVariable *GV = new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000550 GlobalValue::PrivateLinkage, StrConst,
551 kAsanGenPrefix);
Kostya Serebryany51116272013-03-18 09:38:39 +0000552 GV->setUnnamedAddr(true); // Ok to merge these.
553 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
554 return GV;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000555}
556
557static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
558 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000559}
560
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000561Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
562 // Shadow >> scale
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000563 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
564 if (Mapping.Offset == 0)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000565 return Shadow;
566 // (Shadow >> scale) | offset
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000567 if (Mapping.OrShadowOffset)
568 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
569 else
570 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000571}
572
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000573void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000574 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000575 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000576 IRBuilder<> IRB(InsertBefore);
577 if (Size->getType() != IntptrTy)
578 Size = IRB.CreateIntCast(Size, IntptrTy, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000579 // Check the first byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000580 instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000581 // Check the last byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000582 IRB.SetInsertPoint(InsertBefore);
583 Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
584 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
585 Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
586 instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000587}
588
589// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000590bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000591 Value *Dst = MI->getDest();
592 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000593 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000594 Value *Length = MI->getLength();
595
596 Constant *ConstLength = dyn_cast<Constant>(Length);
597 Instruction *InsertBefore = MI;
598 if (ConstLength) {
599 if (ConstLength->isNullValue()) return false;
600 } else {
601 // The size is not a constant so it could be zero -- check at run-time.
602 IRBuilder<> IRB(InsertBefore);
603
604 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000605 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000606 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000607 }
608
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000609 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000610 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000611 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000612 return true;
613}
614
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000615// If I is an interesting memory access, return the PointerOperand
616// and set IsWrite. Otherwise return NULL.
617static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000618 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000619 if (!ClInstrumentReads) return NULL;
620 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000621 return LI->getPointerOperand();
622 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000623 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
624 if (!ClInstrumentWrites) return NULL;
625 *IsWrite = true;
626 return SI->getPointerOperand();
627 }
628 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
629 if (!ClInstrumentAtomics) return NULL;
630 *IsWrite = true;
631 return RMW->getPointerOperand();
632 }
633 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
634 if (!ClInstrumentAtomics) return NULL;
635 *IsWrite = true;
636 return XCHG->getPointerOperand();
637 }
638 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000639}
640
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000641void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000642 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000643 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
644 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000645 if (ClOpt && ClOptGlobals) {
646 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
647 // If initialization order checking is disabled, a simple access to a
648 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000649 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000650 return;
651 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000652 // have to instrument it. However, if a global does not have initailizer
653 // at all, we assume it has dynamic initializer (in other TU).
654 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000655 return;
656 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000657 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000658
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000659 Type *OrigPtrTy = Addr->getType();
660 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
661
662 assert(OrigTy->isSized());
Kostya Serebryany605ff662013-02-18 13:47:02 +0000663 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000664
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000665 assert((TypeSize % 8) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000666
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000667 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
668 if (TypeSize == 8 || TypeSize == 16 ||
669 TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
670 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
671 // Instrument unusual size (but still multiple of 8).
672 // We can not do it with a single check, so we do 1-byte check for the first
673 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
674 // to report the actual access size.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000675 IRBuilder<> IRB(I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000676 Value *LastByte = IRB.CreateIntToPtr(
677 IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
678 ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
679 OrigPtrTy);
680 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
681 instrumentAddress(I, I, Addr, 8, IsWrite, Size);
682 instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000683}
684
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000685// Validate the result of Module::getOrInsertFunction called for an interface
686// function of AddressSanitizer. If the instrumented module defines a function
687// with the same name, their prototypes must match, otherwise
688// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000689static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000690 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
691 FuncOrBitcast->dump();
692 report_fatal_error("trying to redefine an AddressSanitizer "
693 "interface function");
694}
695
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000696Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000697 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000698 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000699 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000700 CallInst *Call = SizeArgument
701 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
702 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
703
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000704 // We don't do Call->setDoesNotReturn() because the BB already has
705 // UnreachableInst at the end.
706 // This EmptyAsm is required to avoid callback merge.
707 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000708 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000709}
710
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000711Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000712 Value *ShadowValue,
713 uint32_t TypeSize) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000714 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000715 // Addr & (Granularity - 1)
716 Value *LastAccessedByte = IRB.CreateAnd(
717 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
718 // (Addr & (Granularity - 1)) + size - 1
719 if (TypeSize / 8 > 1)
720 LastAccessedByte = IRB.CreateAdd(
721 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
722 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
723 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000724 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000725 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
726 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
727}
728
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000729void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000730 Instruction *InsertBefore,
731 Value *Addr, uint32_t TypeSize,
732 bool IsWrite, Value *SizeArgument) {
733 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000734 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
735
736 Type *ShadowTy = IntegerType::get(
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000737 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000738 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
739 Value *ShadowPtr = memToShadow(AddrLong, IRB);
740 Value *CmpVal = Constant::getNullValue(ShadowTy);
741 Value *ShadowValue = IRB.CreateLoad(
742 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
743
744 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000745 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000746 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000747 TerminatorInst *CrashTerm = 0;
748
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000749 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000750 TerminatorInst *CheckTerm =
751 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000752 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000753 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000754 IRB.SetInsertPoint(CheckTerm);
755 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000756 BasicBlock *CrashBlock =
757 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000758 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000759 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
760 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000761 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000762 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000763 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000764
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000765 Instruction *Crash = generateCrashCode(
766 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000767 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000768}
769
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000770void AddressSanitizerModule::createInitializerPoisonCalls(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000771 Module &M, GlobalValue *ModuleName) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000772 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
773 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
774 // If that function is not present, this TU contains no globals, or they have
775 // all been optimized away
776 if (!GlobalInit)
777 return;
778
779 // Set up the arguments to our poison/unpoison functions.
780 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
781
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000782 // Add a call to poison all external globals before the given function starts.
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000783 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
784 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000785
786 // Add calls to unpoison all globals before each return instruction.
787 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
788 I != E; ++I) {
789 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
790 CallInst::Create(AsanUnpoisonGlobals, "", RI);
791 }
792 }
793}
794
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000795bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000796 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000797 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000798
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000799 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000800 if (!Ty->isSized()) return false;
801 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000802 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000803 // Touch only those globals that will not be defined in other modules.
804 // Don't handle ODR type linkages since other modules may be built w/o asan.
805 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
806 G->getLinkage() != GlobalVariable::PrivateLinkage &&
807 G->getLinkage() != GlobalVariable::InternalLinkage)
808 return false;
809 // Two problems with thread-locals:
810 // - The address of the main thread's copy can't be computed at link-time.
811 // - Need to poison all copies, not just the main thread's one.
812 if (G->isThreadLocal())
813 return false;
814 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000815 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000816
817 // Ignore all the globals with the names starting with "\01L_OBJC_".
818 // Many of those are put into the .cstring section. The linker compresses
819 // that section by removing the spare \0s after the string terminator, so
820 // our redzones get broken.
821 if ((G->getName().find("\01L_OBJC_") == 0) ||
822 (G->getName().find("\01l_OBJC_") == 0)) {
823 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
824 return false;
825 }
826
827 if (G->hasSection()) {
828 StringRef Section(G->getSection());
829 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
830 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
831 // them.
832 if ((Section.find("__OBJC,") == 0) ||
833 (Section.find("__DATA, __objc_") == 0)) {
834 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
835 return false;
836 }
837 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
838 // Constant CFString instances are compiled in the following way:
839 // -- the string buffer is emitted into
840 // __TEXT,__cstring,cstring_literals
841 // -- the constant NSConstantString structure referencing that buffer
842 // is placed into __DATA,__cfstring
843 // Therefore there's no point in placing redzones into __DATA,__cfstring.
844 // Moreover, it causes the linker to crash on OS X 10.7
845 if (Section.find("__DATA,__cfstring") == 0) {
846 DEBUG(dbgs() << "Ignoring CFString: " << *G);
847 return false;
848 }
849 }
850
851 return true;
852}
853
Alexey Samsonov46848582012-12-25 12:28:20 +0000854void AddressSanitizerModule::initializeCallbacks(Module &M) {
855 IRBuilder<> IRB(*C);
856 // Declare our poisoning and unpoisoning functions.
857 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000858 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
Alexey Samsonov46848582012-12-25 12:28:20 +0000859 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
860 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
861 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
862 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
863 // Declare functions that register/unregister globals.
864 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
865 kAsanRegisterGlobalsName, IRB.getVoidTy(),
866 IntptrTy, IntptrTy, NULL));
867 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
868 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
869 kAsanUnregisterGlobalsName,
870 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
871 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
872}
873
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000874// This function replaces all global variables with new variables that have
875// trailing redzones. It also creates a function that poisons
876// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000877bool AddressSanitizerModule::runOnModule(Module &M) {
878 if (!ClGlobals) return false;
879 TD = getAnalysisIfAvailable<DataLayout>();
880 if (!TD)
881 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000882 BL.reset(new BlackList(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000883 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000884 C = &(M.getContext());
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000885 int LongSize = TD->getPointerSizeInBits();
886 IntptrTy = Type::getIntNTy(*C, LongSize);
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000887 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov46848582012-12-25 12:28:20 +0000888 initializeCallbacks(M);
889 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000890
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000891 SmallVector<GlobalVariable *, 16> GlobalsToChange;
892
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000893 for (Module::GlobalListType::iterator G = M.global_begin(),
894 E = M.global_end(); G != E; ++G) {
895 if (ShouldInstrumentGlobal(G))
896 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000897 }
898
899 size_t n = GlobalsToChange.size();
900 if (n == 0) return false;
901
902 // A global is described by a structure
903 // size_t beg;
904 // size_t size;
905 // size_t size_with_redzone;
906 // const char *name;
Kostya Serebryany086a4722013-03-18 08:05:29 +0000907 // const char *module_name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000908 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000909 // We initialize an array of such structures and pass it to a run-time call.
910 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000911 IntptrTy, IntptrTy,
Kostya Serebryany086a4722013-03-18 08:05:29 +0000912 IntptrTy, IntptrTy, NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000913 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000914
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000915
916 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
917 assert(CtorFunc);
918 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000919
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000920 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000921
Kostya Serebryany086a4722013-03-18 08:05:29 +0000922 GlobalVariable *ModuleName = createPrivateGlobalForString(
923 M, M.getModuleIdentifier());
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000924 // We shouldn't merge same module names, as this string serves as unique
925 // module ID in runtime.
926 ModuleName->setUnnamedAddr(false);
Kostya Serebryany086a4722013-03-18 08:05:29 +0000927
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000928 for (size_t i = 0; i < n; i++) {
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000929 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000930 GlobalVariable *G = GlobalsToChange[i];
931 PointerType *PtrTy = cast<PointerType>(G->getType());
932 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000933 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000934 uint64_t MinRZ = RedzoneSize();
Kostya Serebryany63f08462013-01-24 10:35:40 +0000935 // MinRZ <= RZ <= kMaxGlobalRedzone
936 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000937 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany63f08462013-01-24 10:35:40 +0000938 std::min(kMaxGlobalRedzone,
939 (SizeInBytes / MinRZ / 4) * MinRZ));
940 uint64_t RightRedzoneSize = RZ;
941 // Round up to MinRZ
942 if (SizeInBytes % MinRZ)
943 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
944 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000945 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000946 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000947 bool GlobalHasDynamicInitializer =
948 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000949 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000950 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000951
952 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
953 Constant *NewInitializer = ConstantStruct::get(
954 NewTy, G->getInitializer(),
955 Constant::getNullValue(RightRedZoneTy), NULL);
956
Kostya Serebryany086a4722013-03-18 08:05:29 +0000957 GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000958
959 // Create a new global variable with enough space for a redzone.
960 GlobalVariable *NewGlobal = new GlobalVariable(
961 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000962 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000963 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany63f08462013-01-24 10:35:40 +0000964 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000965
966 Value *Indices2[2];
967 Indices2[0] = IRB.getInt32(0);
968 Indices2[1] = IRB.getInt32(0);
969
970 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000971 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000972 NewGlobal->takeName(G);
973 G->eraseFromParent();
974
975 Initializers[i] = ConstantStruct::get(
976 GlobalStructTy,
977 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
978 ConstantInt::get(IntptrTy, SizeInBytes),
979 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
980 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany086a4722013-03-18 08:05:29 +0000981 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000982 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000983 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000984
985 // Populate the first and last globals declared in this TU.
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000986 if (CheckInitOrder && GlobalHasDynamicInitializer)
987 HasDynamicallyInitializedGlobals = true;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000988
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000989 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000990 }
991
992 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
993 GlobalVariable *AllGlobals = new GlobalVariable(
994 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
995 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
996
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000997 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000998 if (CheckInitOrder && HasDynamicallyInitializedGlobals)
999 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001000 IRB.CreateCall2(AsanRegisterGlobals,
1001 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1002 ConstantInt::get(IntptrTy, n));
1003
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001004 // We also need to unregister globals at the end, e.g. when a shared library
1005 // gets closed.
1006 Function *AsanDtorFunction = Function::Create(
1007 FunctionType::get(Type::getVoidTy(*C), false),
1008 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1009 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1010 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001011 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1012 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1013 ConstantInt::get(IntptrTy, n));
1014 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1015
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001016 DEBUG(dbgs() << M);
1017 return true;
1018}
1019
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001020void AddressSanitizer::initializeCallbacks(Module &M) {
1021 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001022 // Create __asan_report* callbacks.
1023 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1024 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1025 AccessSizeIndex++) {
1026 // IsWrite and TypeSize are encoded in the function name.
1027 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1028 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +00001029 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +00001030 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1031 checkInterfaceFunction(M.getOrInsertFunction(
1032 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001033 }
1034 }
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +00001035 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1036 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1037 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1038 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001039
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001040 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1041 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +00001042 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1043 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1044 StringRef(""), StringRef(""),
1045 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001046}
1047
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001048void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001049 // Tell the values of mapping offset and scale to the run-time.
1050 GlobalValue *asan_mapping_offset =
1051 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1052 ConstantInt::get(IntptrTy, Mapping.Offset),
1053 kAsanMappingOffsetName);
1054 // Read the global, otherwise it may be optimized away.
1055 IRB.CreateLoad(asan_mapping_offset, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001056
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001057 GlobalValue *asan_mapping_scale =
1058 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1059 ConstantInt::get(IntptrTy, Mapping.Scale),
1060 kAsanMappingScaleName);
1061 // Read the global, otherwise it may be optimized away.
1062 IRB.CreateLoad(asan_mapping_scale, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001063}
1064
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001065// virtual
1066bool AddressSanitizer::doInitialization(Module &M) {
1067 // Initialize the private fields. No one has accessed them before.
1068 TD = getAnalysisIfAvailable<DataLayout>();
1069
1070 if (!TD)
1071 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +00001072 BL.reset(new BlackList(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001073 DynamicallyInitializedGlobals.Init(M);
1074
1075 C = &(M.getContext());
1076 LongSize = TD->getPointerSizeInBits();
1077 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001078
1079 AsanCtorFunction = Function::Create(
1080 FunctionType::get(Type::getVoidTy(*C), false),
1081 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1082 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1083 // call __asan_init in the module ctor.
1084 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1085 AsanInitFunction = checkInterfaceFunction(
1086 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1087 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1088 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001089
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001090 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001091 emitShadowMapping(M, IRB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001092
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001093 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001094 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001095}
1096
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001097bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1098 // For each NSObject descendant having a +load method, this method is invoked
1099 // by the ObjC runtime before any of the static constructors is called.
1100 // Therefore we need to instrument such methods with a call to __asan_init
1101 // at the beginning in order to initialize our runtime before any access to
1102 // the shadow memory.
1103 // We cannot just ignore these methods, because they may call other
1104 // instrumented functions.
1105 if (F.getName().find(" load]") != std::string::npos) {
1106 IRBuilder<> IRB(F.begin()->begin());
1107 IRB.CreateCall(AsanInitFunction);
1108 return true;
1109 }
1110 return false;
1111}
1112
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001113bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001114 if (BL->isIn(F)) return false;
1115 if (&F == AsanCtorFunction) return false;
Kostya Serebryany3797adb2013-03-18 07:33:49 +00001116 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001117 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001118 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001119
Kostya Serebryany8eec41f2013-02-26 06:58:09 +00001120 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001121 maybeInsertAsanInitAtFunctionEntry(F);
1122
Kostya Serebryany20985712013-06-26 09:18:17 +00001123 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendling67658342012-10-09 07:45:08 +00001124 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001125
1126 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1127 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001128
1129 // We want to instrument every address only once per basic block (unless there
1130 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001131 SmallSet<Value*, 16> TempsToInstrument;
1132 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001133 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany20985712013-06-26 09:18:17 +00001134 int NumAllocas = 0;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001135 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001136
1137 // Fill the set of memory operations to instrument.
1138 for (Function::iterator FI = F.begin(), FE = F.end();
1139 FI != FE; ++FI) {
1140 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001141 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001142 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1143 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001144 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001145 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001146 if (ClOpt && ClOptSameTemp) {
1147 if (!TempsToInstrument.insert(Addr))
1148 continue; // We've seen this temp in the current BB.
1149 }
1150 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1151 // ok, take it.
1152 } else {
Kostya Serebryany20985712013-06-26 09:18:17 +00001153 if (isa<AllocaInst>(BI))
1154 NumAllocas++;
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001155 CallSite CS(BI);
1156 if (CS) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001157 // A call inside BB.
1158 TempsToInstrument.clear();
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001159 if (CS.doesNotReturn())
1160 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001161 }
1162 continue;
1163 }
1164 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001165 NumInsnsPerBB++;
1166 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1167 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001168 }
1169 }
1170
Kostya Serebryany20985712013-06-26 09:18:17 +00001171 Function *UninstrumentedDuplicate = 0;
1172 bool LikelyToInstrument =
1173 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1174 if (ClKeepUninstrumented && LikelyToInstrument) {
1175 ValueToValueMapTy VMap;
1176 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1177 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1178 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1179 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1180 }
1181
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001182 // Instrument.
1183 int NumInstrumented = 0;
1184 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1185 Instruction *Inst = ToInstrument[i];
1186 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1187 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001188 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001189 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001190 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001191 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001192 }
1193 NumInstrumented++;
1194 }
1195
Alexey Samsonov59cca132012-12-25 12:04:36 +00001196 FunctionStackPoisoner FSP(F, *this);
1197 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001198
1199 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1200 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1201 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1202 Instruction *CI = NoReturnCalls[i];
1203 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001204 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001205 }
1206
Kostya Serebryany20985712013-06-26 09:18:17 +00001207 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1208 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1209
1210 if (ClKeepUninstrumented) {
1211 if (!res) {
1212 // No instrumentation is done, no need for the duplicate.
1213 if (UninstrumentedDuplicate)
1214 UninstrumentedDuplicate->eraseFromParent();
1215 } else {
1216 // The function was instrumented. We must have the duplicate.
1217 assert(UninstrumentedDuplicate);
1218 UninstrumentedDuplicate->setSection("NOASAN");
1219 assert(!F.hasSection());
1220 F.setSection("ASAN");
1221 }
1222 }
1223
1224 return res;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001225}
1226
1227static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1228 if (ShadowRedzoneSize == 1) return PoisonByte;
1229 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1230 if (ShadowRedzoneSize == 4)
1231 return (PoisonByte << 24) + (PoisonByte << 16) +
1232 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001233 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001234}
1235
1236static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1237 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001238 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001239 size_t ShadowGranularity,
1240 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001241 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001242 i+= ShadowGranularity, Shadow++) {
1243 if (i + ShadowGranularity <= Size) {
1244 *Shadow = 0; // fully addressable
1245 } else if (i >= Size) {
1246 *Shadow = Magic; // unaddressable
1247 } else {
1248 *Shadow = Size - i; // first Size-i bytes are addressable
1249 }
1250 }
1251}
1252
Alexey Samsonov59cca132012-12-25 12:04:36 +00001253// Workaround for bug 11395: we don't want to instrument stack in functions
1254// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1255// FIXME: remove once the bug 11395 is fixed.
1256bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1257 if (LongSize != 32) return false;
1258 CallInst *CI = dyn_cast<CallInst>(I);
1259 if (!CI || !CI->isInlineAsm()) return false;
1260 if (CI->getNumArgOperands() <= 5) return false;
1261 // We have inline assembly with quite a few arguments.
1262 return true;
1263}
1264
1265void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1266 IRBuilder<> IRB(*C);
1267 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
1268 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
1269 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
1270 kAsanStackFreeName, IRB.getVoidTy(),
1271 IntptrTy, IntptrTy, IntptrTy, NULL));
1272 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1273 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1274 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1275 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1276}
1277
1278void FunctionStackPoisoner::poisonRedZones(
1279 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
1280 bool DoPoison) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001281 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001282 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1283 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1284 Type *RZPtrTy = PointerType::get(RZTy, 0);
1285
1286 Value *PoisonLeft = ConstantInt::get(RZTy,
1287 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1288 Value *PoisonMid = ConstantInt::get(RZTy,
1289 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1290 Value *PoisonRight = ConstantInt::get(RZTy,
1291 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1292
1293 // poison the first red zone.
1294 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1295
1296 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001297 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001298 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1299 AllocaInst *AI = AllocaVec[i];
1300 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1301 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001302 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001303 Value *Ptr = NULL;
1304
1305 Pos += AlignedSize;
1306
1307 assert(ShadowBase->getType() == IntptrTy);
1308 if (SizeInBytes < AlignedSize) {
1309 // Poison the partial redzone at right
1310 Ptr = IRB.CreateAdd(
1311 ShadowBase, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001312 (Pos >> Mapping.Scale) - ShadowRZSize));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001313 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001314 uint32_t Poison = 0;
1315 if (DoPoison) {
1316 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001317 RedzoneSize(),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001318 1ULL << Mapping.Scale,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001319 kAsanStackPartialRedzoneMagic);
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +00001320 Poison =
1321 ASan.TD->isLittleEndian()
1322 ? support::endian::byte_swap<uint32_t, support::little>(Poison)
1323 : support::endian::byte_swap<uint32_t, support::big>(Poison);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001324 }
1325 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1326 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1327 }
1328
1329 // Poison the full redzone at right.
1330 Ptr = IRB.CreateAdd(ShadowBase,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001331 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001332 bool LastAlloca = (i == AllocaVec.size() - 1);
1333 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001334 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1335
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001336 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001337 }
1338}
1339
Alexey Samsonov59cca132012-12-25 12:04:36 +00001340void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001341 uint64_t LocalStackSize = TotalStackSize +
1342 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001343
Alexey Samsonov59cca132012-12-25 12:04:36 +00001344 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001345 && LocalStackSize <= kMaxStackMallocSize;
1346
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001347 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001348 Instruction *InsBefore = AllocaVec[0];
1349 IRBuilder<> IRB(InsBefore);
1350
1351
1352 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1353 AllocaInst *MyAlloca =
1354 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001355 if (ClRealignStack && StackAlignment < RedzoneSize())
1356 StackAlignment = RedzoneSize();
1357 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001358 assert(MyAlloca->isStaticAlloca());
1359 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1360 Value *LocalStackBase = OrigStackBase;
1361
1362 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001363 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1364 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1365 }
1366
Kostya Serebryany30160562013-03-22 10:37:20 +00001367 // This string will be parsed by the run-time (DescribeAddressIfStack).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001368 SmallString<2048> StackDescriptionStorage;
1369 raw_svector_ostream StackDescription(StackDescriptionStorage);
Kostya Serebryany30160562013-03-22 10:37:20 +00001370 StackDescription << AllocaVec.size() << " ";
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001371
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001372 // Insert poison calls for lifetime intrinsics for alloca.
1373 bool HavePoisonedAllocas = false;
1374 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1375 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1376 IntrinsicInst *II = APC.InsBefore;
1377 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1378 assert(AI);
1379 IRBuilder<> IRB(II);
1380 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1381 HavePoisonedAllocas |= APC.DoPoison;
1382 }
1383
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001384 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001385 // Replace Alloca instructions with base+offset.
1386 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1387 AllocaInst *AI = AllocaVec[i];
1388 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1389 StringRef Name = AI->getName();
1390 StackDescription << Pos << " " << SizeInBytes << " "
1391 << Name.size() << " " << Name << " ";
1392 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001393 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001394 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001395 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001396 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001397 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001398 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001399 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001400 }
1401 assert(Pos == LocalStackSize);
1402
Kostya Serebryany30160562013-03-22 10:37:20 +00001403 // The left-most redzone has enough space for at least 4 pointers.
1404 // Write the Magic value to redzone[0].
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001405 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1406 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1407 BasePlus0);
Kostya Serebryany30160562013-03-22 10:37:20 +00001408 // Write the frame description constant to redzone[1].
1409 Value *BasePlus1 = IRB.CreateIntToPtr(
1410 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1411 IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001412 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001413 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001414 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1415 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001416 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryany30160562013-03-22 10:37:20 +00001417 // Write the PC to redzone[2].
1418 Value *BasePlus2 = IRB.CreateIntToPtr(
1419 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1420 2 * ASan.LongSize/8)),
1421 IntptrPtrTy);
1422 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001423
1424 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001425 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1426 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001427
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001428 // Unpoison the stack before all ret instructions.
1429 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1430 Instruction *Ret = RetVec[i];
1431 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001432 // Mark the current frame as retired.
1433 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1434 BasePlus0);
1435 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001436 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001437 if (DoStackMalloc) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001438 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001439 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1440 ConstantInt::get(IntptrTy, LocalStackSize),
1441 OrigStackBase);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001442 } else if (HavePoisonedAllocas) {
1443 // If we poisoned some allocas in llvm.lifetime analysis,
1444 // unpoison whole stack frame now.
1445 assert(LocalStackBase == OrigStackBase);
1446 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001447 }
1448 }
1449
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001450 // We are done. Remove the old unused alloca instructions.
1451 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1452 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001453}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001454
Alexey Samsonov59cca132012-12-25 12:04:36 +00001455void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1456 IRBuilder<> IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001457 // For now just insert the call to ASan runtime.
1458 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1459 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1460 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1461 : AsanUnpoisonStackMemoryFunc,
1462 AddrArg, SizeArg);
1463}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001464
1465// Handling llvm.lifetime intrinsics for a given %alloca:
1466// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1467// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1468// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1469// could be poisoned by previous llvm.lifetime.end instruction, as the
1470// variable may go in and out of scope several times, e.g. in loops).
1471// (3) if we poisoned at least one %alloca in a function,
1472// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001473
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001474AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1475 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1476 // We're intested only in allocas we can handle.
1477 return isInterestingAlloca(*AI) ? AI : 0;
1478 // See if we've already calculated (or started to calculate) alloca for a
1479 // given value.
1480 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1481 if (I != AllocaForValue.end())
1482 return I->second;
1483 // Store 0 while we're calculating alloca for value V to avoid
1484 // infinite recursion if the value references itself.
1485 AllocaForValue[V] = 0;
1486 AllocaInst *Res = 0;
1487 if (CastInst *CI = dyn_cast<CastInst>(V))
1488 Res = findAllocaForValue(CI->getOperand(0));
1489 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1490 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1491 Value *IncValue = PN->getIncomingValue(i);
1492 // Allow self-referencing phi-nodes.
1493 if (IncValue == PN) continue;
1494 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1495 // AI for incoming values should exist and should all be equal.
1496 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1497 return 0;
1498 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001499 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001500 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001501 if (Res != 0)
1502 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001503 return Res;
1504}