blob: a5126d68cd886dcc37d06226beabf4788b673f08 [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"
Kostya Serebryany20985712013-06-26 09:18:17 +000046#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov1afbb512012-12-12 14:31:53 +000047#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000048#include "llvm/Transforms/Utils/ModuleUtils.h"
Peter Collingbourne405515d2013-07-09 22:02:49 +000049#include "llvm/Transforms/Utils/SpecialCaseList.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
Craig Topper4172a8a2013-07-16 01:17:10 +000066static const char *const kAsanModuleCtorName = "asan.module_ctor";
67static const char *const kAsanModuleDtorName = "asan.module_dtor";
68static const int kAsanCtorAndCtorPriority = 1;
69static const char *const kAsanReportErrorTemplate = "__asan_report_";
70static const char *const kAsanReportLoadN = "__asan_report_load_n";
71static const char *const kAsanReportStoreN = "__asan_report_store_n";
72static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
73static const char *const kAsanUnregisterGlobalsName = "__asan_unregister_globals";
74static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
75static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
76static const char *const kAsanInitName = "__asan_init_v3";
77static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
78static const char *const kAsanMappingOffsetName = "__asan_mapping_offset";
79static const char *const kAsanMappingScaleName = "__asan_mapping_scale";
80static const char *const kAsanStackMallocName = "__asan_stack_malloc";
81static const char *const kAsanStackFreeName = "__asan_stack_free";
82static const char *const kAsanGenPrefix = "__asan_gen_";
83static const char *const kAsanPoisonStackMemoryName =
84 "__asan_poison_stack_memory";
85static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonovf985f442012-12-04 01:34:23 +000086 "__asan_unpoison_stack_memory";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000087
88static const int kAsanStackLeftRedzoneMagic = 0xf1;
89static const int kAsanStackMidRedzoneMagic = 0xf2;
90static const int kAsanStackRightRedzoneMagic = 0xf3;
91static const int kAsanStackPartialRedzoneMagic = 0xf4;
92
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000093// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
94static const size_t kNumberOfAccessSizes = 5;
95
Kostya Serebryany800e03f2011-11-16 01:35:23 +000096// Command-line flags.
97
98// This flag may need to be replaced with -f[no-]asan-reads.
99static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
100 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
101static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
102 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000103static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
104 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
105 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000106static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
107 cl::desc("use instrumentation with slow path for all accesses"),
108 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000109// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000110// in any given BB. Normally, this should be set to unlimited (INT_MAX),
111// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
112// set it to 10000.
113static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
114 cl::init(10000),
115 cl::desc("maximal number of instructions to instrument in any given BB"),
116 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000117// This flag may need to be replaced with -f[no]asan-stack.
118static cl::opt<bool> ClStack("asan-stack",
119 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
120// This flag may need to be replaced with -f[no]asan-use-after-return.
121static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
122 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
123// This flag may need to be replaced with -f[no]asan-globals.
124static cl::opt<bool> ClGlobals("asan-globals",
125 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000126static cl::opt<bool> ClInitializers("asan-initialization-order",
127 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000128static cl::opt<bool> ClMemIntrin("asan-memintrin",
129 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Kostya Serebryany6c554122012-12-04 06:14:01 +0000130static cl::opt<bool> ClRealignStack("asan-realign-stack",
131 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000132static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
133 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000134 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000135
Kostya Serebryany20985712013-06-26 09:18:17 +0000136// This is an experimental feature that will allow to choose between
137// instrumented and non-instrumented code at link-time.
138// If this option is on, just before instrumenting a function we create its
139// clone; if the function is not changed by asan the clone is deleted.
140// If we end up with a clone, we put the instrumented function into a section
141// called "ASAN" and the uninstrumented function into a section called "NOASAN".
142//
143// This is still a prototype, we need to figure out a way to keep two copies of
144// a function so that the linker can easily choose one of them.
145static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
146 cl::desc("Keep uninstrumented copies of functions"),
147 cl::Hidden, cl::init(false));
148
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000149// These flags allow to change the shadow mapping.
150// The shadow mapping looks like
151// Shadow = (Mem >> scale) + (1 << offset_log)
152static cl::opt<int> ClMappingScale("asan-mapping-scale",
153 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
154static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
155 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
Kostya Serebryany117de482013-02-11 14:36:01 +0000156static cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
157 cl::desc("Use short immediate constant as the mapping offset for 64bit"),
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000158 cl::Hidden, cl::init(true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000159
160// Optimization flags. Not user visible, used mostly for testing
161// and benchmarking the tool.
162static cl::opt<bool> ClOpt("asan-opt",
163 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
164static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
165 cl::desc("Instrument the same temp just once"), cl::Hidden,
166 cl::init(true));
167static cl::opt<bool> ClOptGlobals("asan-opt-globals",
168 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
169
Alexey Samsonovee548272012-11-29 18:14:24 +0000170static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
171 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
172 cl::Hidden, cl::init(false));
173
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000174// Debug flags.
175static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
176 cl::init(0));
177static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
178 cl::Hidden, cl::init(0));
179static cl::opt<std::string> ClDebugFunc("asan-debug-func",
180 cl::Hidden, cl::desc("Debug func"));
181static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
182 cl::Hidden, cl::init(-1));
183static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
184 cl::Hidden, cl::init(-1));
185
186namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000187/// A set of dynamically initialized globals extracted from metadata.
188class SetOfDynamicallyInitializedGlobals {
189 public:
190 void Init(Module& M) {
191 // Clang generates metadata identifying all dynamically initialized globals.
192 NamedMDNode *DynamicGlobals =
193 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
194 if (!DynamicGlobals)
195 return;
196 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
197 MDNode *MDN = DynamicGlobals->getOperand(i);
198 assert(MDN->getNumOperands() == 1);
199 Value *VG = MDN->getOperand(0);
200 // The optimizer may optimize away a global entirely, in which case we
201 // cannot instrument access to it.
202 if (!VG)
203 continue;
204 DynInitGlobals.insert(cast<GlobalVariable>(VG));
205 }
206 }
207 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
208 private:
209 SmallSet<GlobalValue*, 32> DynInitGlobals;
210};
211
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000212/// This struct defines the shadow mapping using the rule:
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000213/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000214struct ShadowMapping {
215 int Scale;
216 uint64_t Offset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000217 bool OrShadowOffset;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000218};
219
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000220static ShadowMapping getShadowMapping(const Module &M, int LongSize,
221 bool ZeroBaseShadow) {
222 llvm::Triple TargetTriple(M.getTargetTriple());
223 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000224 bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
Bill Schmidtf38cc382013-07-26 01:35:43 +0000225 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
226 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000227 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +0000228 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
229 TargetTriple.getArch() == llvm::Triple::mipsel;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000230
231 ShadowMapping Mapping;
232
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000233 // OR-ing shadow offset if more efficient (at least on x86),
234 // but on ppc64 we have to use add since the shadow offset is not neccesary
235 // 1/8-th of the address space.
Kostya Serebryany117de482013-02-11 14:36:01 +0000236 Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000237
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000238 Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +0000239 (LongSize == 32 ?
240 (IsMIPS32 ? kMIPS32_ShadowOffset32 : kDefaultShadowOffset32) :
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000241 IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000242 if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000243 assert(LongSize == 64);
Kostya Serebryany117de482013-02-11 14:36:01 +0000244 Mapping.Offset = kDefaultShort64bitShadowOffset;
Kostya Serebryany39f02942013-02-13 05:14:12 +0000245 }
246 if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000247 // Zero offset log is the special case.
248 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
249 }
250
251 Mapping.Scale = kDefaultShadowScale;
252 if (ClMappingScale) {
253 Mapping.Scale = ClMappingScale;
254 }
255
256 return Mapping;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000257}
258
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000259static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000260 // Redzone used for stack and globals is at least 32 bytes.
261 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000262 return std::max(32U, 1U << MappingScale);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000263}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000264
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000265/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000266struct AddressSanitizer : public FunctionPass {
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000267 AddressSanitizer(bool CheckInitOrder = true,
Alexey Samsonovee548272012-11-29 18:14:24 +0000268 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000269 bool CheckLifetime = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000270 StringRef BlacklistFile = StringRef(),
271 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000272 : FunctionPass(ID),
273 CheckInitOrder(CheckInitOrder || ClInitializers),
274 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000275 CheckLifetime(CheckLifetime || ClCheckLifetime),
276 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000277 : BlacklistFile),
278 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000279 virtual const char *getPassName() const {
280 return "AddressSanitizerFunctionPass";
281 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000282 void instrumentMop(Instruction *I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000283 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
284 Value *Addr, uint32_t TypeSize, bool IsWrite,
285 Value *SizeArgument);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000286 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
287 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000288 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000289 bool IsWrite, size_t AccessSizeIndex,
290 Value *SizeArgument);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000291 bool instrumentMemIntrinsic(MemIntrinsic *MI);
292 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000293 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000294 Instruction *InsertBefore, bool IsWrite);
295 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000296 bool runOnFunction(Function &F);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000297 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000298 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000299 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000300 static char ID; // Pass identification, replacement for typeid
301
302 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000303 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000304
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000305 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000306 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000307 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000308
Alexey Samsonovee548272012-11-29 18:14:24 +0000309 bool CheckInitOrder;
310 bool CheckUseAfterReturn;
311 bool CheckLifetime;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000312 SmallString<64> BlacklistFile;
313 bool ZeroBaseShadow;
314
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000315 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000316 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000317 int LongSize;
318 Type *IntptrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000319 ShadowMapping Mapping;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000320 Function *AsanCtorFunction;
321 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000322 Function *AsanHandleNoReturnFunc;
Peter Collingbourne405515d2013-07-09 22:02:49 +0000323 OwningPtr<SpecialCaseList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000324 // This array is indexed by AccessIsWrite and log2(AccessSize).
325 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000326 // This array is indexed by AccessIsWrite.
327 Function *AsanErrorCallbackSized[2];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000328 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000329 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000330
331 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000332};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000333
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000334class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000335 public:
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000336 AddressSanitizerModule(bool CheckInitOrder = true,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000337 StringRef BlacklistFile = StringRef(),
338 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000339 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000340 CheckInitOrder(CheckInitOrder || ClInitializers),
341 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000342 : BlacklistFile),
343 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000344 bool runOnModule(Module &M);
345 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000346 virtual const char *getPassName() const {
347 return "AddressSanitizerModule";
348 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000349
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000350 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000351 void initializeCallbacks(Module &M);
352
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000353 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000354 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000355 size_t RedzoneSize() const {
356 return RedzoneSizeForScale(Mapping.Scale);
357 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000358
Alexey Samsonovee548272012-11-29 18:14:24 +0000359 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000360 SmallString<64> BlacklistFile;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000361 bool ZeroBaseShadow;
362
Peter Collingbourne405515d2013-07-09 22:02:49 +0000363 OwningPtr<SpecialCaseList> BL;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000364 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
365 Type *IntptrTy;
366 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000367 DataLayout *TD;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000368 ShadowMapping Mapping;
Alexey Samsonov46848582012-12-25 12:28:20 +0000369 Function *AsanPoisonGlobals;
370 Function *AsanUnpoisonGlobals;
371 Function *AsanRegisterGlobals;
372 Function *AsanUnregisterGlobals;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000373};
374
Alexey Samsonov59cca132012-12-25 12:04:36 +0000375// Stack poisoning does not play well with exception handling.
376// When an exception is thrown, we essentially bypass the code
377// that unpoisones the stack. This is why the run-time library has
378// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
379// stack in the interceptor. This however does not work inside the
380// actual function which catches the exception. Most likely because the
381// compiler hoists the load of the shadow value somewhere too high.
382// This causes asan to report a non-existing bug on 453.povray.
383// It sounds like an LLVM bug.
384struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
385 Function &F;
386 AddressSanitizer &ASan;
387 DIBuilder DIB;
388 LLVMContext *C;
389 Type *IntptrTy;
390 Type *IntptrPtrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000391 ShadowMapping Mapping;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000392
393 SmallVector<AllocaInst*, 16> AllocaVec;
394 SmallVector<Instruction*, 8> RetVec;
395 uint64_t TotalStackSize;
396 unsigned StackAlignment;
397
398 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
399 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
400
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000401 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
402 struct AllocaPoisonCall {
403 IntrinsicInst *InsBefore;
404 uint64_t Size;
405 bool DoPoison;
406 };
407 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
408
409 // Maps Value to an AllocaInst from which the Value is originated.
410 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
411 AllocaForValueMapTy AllocaForValue;
412
Alexey Samsonov59cca132012-12-25 12:04:36 +0000413 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
414 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
415 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000416 Mapping(ASan.Mapping),
417 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov59cca132012-12-25 12:04:36 +0000418
419 bool runOnFunction() {
420 if (!ClStack) return false;
421 // Collect alloca, ret, lifetime instructions etc.
422 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
423 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
424 BasicBlock *BB = *DI;
425 visit(*BB);
426 }
427 if (AllocaVec.empty()) return false;
428
429 initializeCallbacks(*F.getParent());
430
431 poisonStack();
432
433 if (ClDebugStack) {
434 DEBUG(dbgs() << F);
435 }
436 return true;
437 }
438
439 // Finds all static Alloca instructions and puts
440 // poisoned red zones around all of them.
441 // Then unpoison everything back before the function returns.
442 void poisonStack();
443
444 // ----------------------- Visitors.
445 /// \brief Collect all Ret instructions.
446 void visitReturnInst(ReturnInst &RI) {
447 RetVec.push_back(&RI);
448 }
449
450 /// \brief Collect Alloca instructions we want (and can) handle.
451 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000452 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000453
454 StackAlignment = std::max(StackAlignment, AI.getAlignment());
455 AllocaVec.push_back(&AI);
Kostya Serebryanyd4429212013-06-26 09:49:52 +0000456 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000457 TotalStackSize += AlignedSize;
458 }
459
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000460 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
461 /// errors.
462 void visitIntrinsicInst(IntrinsicInst &II) {
463 if (!ASan.CheckLifetime) return;
464 Intrinsic::ID ID = II.getIntrinsicID();
465 if (ID != Intrinsic::lifetime_start &&
466 ID != Intrinsic::lifetime_end)
467 return;
468 // Found lifetime intrinsic, add ASan instrumentation if necessary.
469 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
470 // If size argument is undefined, don't do anything.
471 if (Size->isMinusOne()) return;
472 // Check that size doesn't saturate uint64_t and can
473 // be stored in IntptrTy.
474 const uint64_t SizeValue = Size->getValue().getLimitedValue();
475 if (SizeValue == ~0ULL ||
476 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
477 return;
478 // Find alloca instruction that corresponds to llvm.lifetime argument.
479 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
480 if (!AI) return;
481 bool DoPoison = (ID == Intrinsic::lifetime_end);
482 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
483 AllocaPoisonCallVec.push_back(APC);
484 }
485
Alexey Samsonov59cca132012-12-25 12:04:36 +0000486 // ---------------------- Helpers.
487 void initializeCallbacks(Module &M);
488
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000489 // Check if we want (and can) handle this alloca.
490 bool isInterestingAlloca(AllocaInst &AI) {
491 return (!AI.isArrayAllocation() &&
492 AI.isStaticAlloca() &&
Kostya Serebryanyd4429212013-06-26 09:49:52 +0000493 AI.getAlignment() <= RedzoneSize() &&
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000494 AI.getAllocatedType()->isSized());
495 }
496
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000497 size_t RedzoneSize() const {
498 return RedzoneSizeForScale(Mapping.Scale);
499 }
Alexey Samsonov59cca132012-12-25 12:04:36 +0000500 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
501 Type *Ty = AI->getAllocatedType();
502 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
503 return SizeInBytes;
504 }
505 uint64_t getAlignedSize(uint64_t SizeInBytes) {
506 size_t RZ = RedzoneSize();
507 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
508 }
509 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
510 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
511 return getAlignedSize(SizeInBytes);
512 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000513 /// Finds alloca where the value comes from.
514 AllocaInst *findAllocaForValue(Value *V);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000515 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
516 Value *ShadowBase, bool DoPoison);
517 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000518};
519
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000520} // namespace
521
522char AddressSanitizer::ID = 0;
523INITIALIZE_PASS(AddressSanitizer, "asan",
524 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
525 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000526FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000527 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000528 StringRef BlacklistFile, bool ZeroBaseShadow) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000529 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000530 CheckLifetime, BlacklistFile, ZeroBaseShadow);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000531}
532
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000533char AddressSanitizerModule::ID = 0;
534INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
535 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
536 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000537ModulePass *llvm::createAddressSanitizerModulePass(
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000538 bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
539 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
540 ZeroBaseShadow);
Alexander Potapenko25878042012-01-23 11:22:43 +0000541}
542
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000543static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerc6af2432013-05-24 22:23:49 +0000544 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000545 assert(Res < kNumberOfAccessSizes);
546 return Res;
547}
548
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000549// Create a constant for Str so that we can pass it to the run-time lib.
550static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000551 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany51116272013-03-18 09:38:39 +0000552 GlobalVariable *GV = new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000553 GlobalValue::PrivateLinkage, StrConst,
554 kAsanGenPrefix);
Kostya Serebryany51116272013-03-18 09:38:39 +0000555 GV->setUnnamedAddr(true); // Ok to merge these.
556 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
557 return GV;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000558}
559
560static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
561 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000562}
563
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000564Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
565 // Shadow >> scale
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000566 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
567 if (Mapping.Offset == 0)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000568 return Shadow;
569 // (Shadow >> scale) | offset
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000570 if (Mapping.OrShadowOffset)
571 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
572 else
573 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000574}
575
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000576void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000577 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000578 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000579 IRBuilder<> IRB(InsertBefore);
580 if (Size->getType() != IntptrTy)
581 Size = IRB.CreateIntCast(Size, IntptrTy, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000582 // Check the first byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000583 instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000584 // Check the last byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000585 IRB.SetInsertPoint(InsertBefore);
586 Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
587 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
588 Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
589 instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000590}
591
592// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000593bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000594 Value *Dst = MI->getDest();
595 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000596 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000597 Value *Length = MI->getLength();
598
599 Constant *ConstLength = dyn_cast<Constant>(Length);
600 Instruction *InsertBefore = MI;
601 if (ConstLength) {
602 if (ConstLength->isNullValue()) return false;
603 } else {
604 // The size is not a constant so it could be zero -- check at run-time.
605 IRBuilder<> IRB(InsertBefore);
606
607 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000608 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000609 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000610 }
611
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000612 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000613 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000614 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000615 return true;
616}
617
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000618// If I is an interesting memory access, return the PointerOperand
619// and set IsWrite. Otherwise return NULL.
620static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000621 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000622 if (!ClInstrumentReads) return NULL;
623 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000624 return LI->getPointerOperand();
625 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000626 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
627 if (!ClInstrumentWrites) return NULL;
628 *IsWrite = true;
629 return SI->getPointerOperand();
630 }
631 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
632 if (!ClInstrumentAtomics) return NULL;
633 *IsWrite = true;
634 return RMW->getPointerOperand();
635 }
636 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
637 if (!ClInstrumentAtomics) return NULL;
638 *IsWrite = true;
639 return XCHG->getPointerOperand();
640 }
641 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000642}
643
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000644void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000645 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000646 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
647 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000648 if (ClOpt && ClOptGlobals) {
649 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
650 // If initialization order checking is disabled, a simple access to a
651 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000652 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000653 return;
654 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000655 // have to instrument it. However, if a global does not have initailizer
656 // at all, we assume it has dynamic initializer (in other TU).
657 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000658 return;
659 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000660 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000661
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000662 Type *OrigPtrTy = Addr->getType();
663 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
664
665 assert(OrigTy->isSized());
Kostya Serebryany605ff662013-02-18 13:47:02 +0000666 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000667
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000668 assert((TypeSize % 8) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000669
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000670 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
671 if (TypeSize == 8 || TypeSize == 16 ||
672 TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
673 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
674 // Instrument unusual size (but still multiple of 8).
675 // We can not do it with a single check, so we do 1-byte check for the first
676 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
677 // to report the actual access size.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000678 IRBuilder<> IRB(I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000679 Value *LastByte = IRB.CreateIntToPtr(
680 IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
681 ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
682 OrigPtrTy);
683 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
684 instrumentAddress(I, I, Addr, 8, IsWrite, Size);
685 instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000686}
687
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000688// Validate the result of Module::getOrInsertFunction called for an interface
689// function of AddressSanitizer. If the instrumented module defines a function
690// with the same name, their prototypes must match, otherwise
691// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000692static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000693 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
694 FuncOrBitcast->dump();
695 report_fatal_error("trying to redefine an AddressSanitizer "
696 "interface function");
697}
698
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000699Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000700 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000701 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000702 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000703 CallInst *Call = SizeArgument
704 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
705 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
706
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000707 // We don't do Call->setDoesNotReturn() because the BB already has
708 // UnreachableInst at the end.
709 // This EmptyAsm is required to avoid callback merge.
710 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000711 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000712}
713
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000714Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000715 Value *ShadowValue,
716 uint32_t TypeSize) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000717 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000718 // Addr & (Granularity - 1)
719 Value *LastAccessedByte = IRB.CreateAnd(
720 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
721 // (Addr & (Granularity - 1)) + size - 1
722 if (TypeSize / 8 > 1)
723 LastAccessedByte = IRB.CreateAdd(
724 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
725 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
726 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000727 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000728 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
729 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
730}
731
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000732void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000733 Instruction *InsertBefore,
734 Value *Addr, uint32_t TypeSize,
735 bool IsWrite, Value *SizeArgument) {
736 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000737 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
738
739 Type *ShadowTy = IntegerType::get(
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000740 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000741 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
742 Value *ShadowPtr = memToShadow(AddrLong, IRB);
743 Value *CmpVal = Constant::getNullValue(ShadowTy);
744 Value *ShadowValue = IRB.CreateLoad(
745 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
746
747 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000748 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000749 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000750 TerminatorInst *CrashTerm = 0;
751
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000752 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000753 TerminatorInst *CheckTerm =
754 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000755 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000756 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000757 IRB.SetInsertPoint(CheckTerm);
758 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000759 BasicBlock *CrashBlock =
760 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000761 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000762 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
763 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000764 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000765 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000766 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000767
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000768 Instruction *Crash = generateCrashCode(
769 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000770 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000771}
772
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000773void AddressSanitizerModule::createInitializerPoisonCalls(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000774 Module &M, GlobalValue *ModuleName) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000775 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
776 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
777 // If that function is not present, this TU contains no globals, or they have
778 // all been optimized away
779 if (!GlobalInit)
780 return;
781
782 // Set up the arguments to our poison/unpoison functions.
783 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
784
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000785 // Add a call to poison all external globals before the given function starts.
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000786 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
787 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000788
789 // Add calls to unpoison all globals before each return instruction.
790 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
791 I != E; ++I) {
792 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
793 CallInst::Create(AsanUnpoisonGlobals, "", RI);
794 }
795 }
796}
797
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000798bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000799 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000800 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000801
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000802 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000803 if (!Ty->isSized()) return false;
804 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000805 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000806 // Touch only those globals that will not be defined in other modules.
807 // Don't handle ODR type linkages since other modules may be built w/o asan.
808 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
809 G->getLinkage() != GlobalVariable::PrivateLinkage &&
810 G->getLinkage() != GlobalVariable::InternalLinkage)
811 return false;
812 // Two problems with thread-locals:
813 // - The address of the main thread's copy can't be computed at link-time.
814 // - Need to poison all copies, not just the main thread's one.
815 if (G->isThreadLocal())
816 return false;
817 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000818 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000819
820 // Ignore all the globals with the names starting with "\01L_OBJC_".
821 // Many of those are put into the .cstring section. The linker compresses
822 // that section by removing the spare \0s after the string terminator, so
823 // our redzones get broken.
824 if ((G->getName().find("\01L_OBJC_") == 0) ||
825 (G->getName().find("\01l_OBJC_") == 0)) {
826 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
827 return false;
828 }
829
830 if (G->hasSection()) {
831 StringRef Section(G->getSection());
832 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
833 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
834 // them.
835 if ((Section.find("__OBJC,") == 0) ||
836 (Section.find("__DATA, __objc_") == 0)) {
837 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
838 return false;
839 }
840 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
841 // Constant CFString instances are compiled in the following way:
842 // -- the string buffer is emitted into
843 // __TEXT,__cstring,cstring_literals
844 // -- the constant NSConstantString structure referencing that buffer
845 // is placed into __DATA,__cfstring
846 // Therefore there's no point in placing redzones into __DATA,__cfstring.
847 // Moreover, it causes the linker to crash on OS X 10.7
848 if (Section.find("__DATA,__cfstring") == 0) {
849 DEBUG(dbgs() << "Ignoring CFString: " << *G);
850 return false;
851 }
852 }
853
854 return true;
855}
856
Alexey Samsonov46848582012-12-25 12:28:20 +0000857void AddressSanitizerModule::initializeCallbacks(Module &M) {
858 IRBuilder<> IRB(*C);
859 // Declare our poisoning and unpoisoning functions.
860 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000861 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
Alexey Samsonov46848582012-12-25 12:28:20 +0000862 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
863 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
864 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
865 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
866 // Declare functions that register/unregister globals.
867 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
868 kAsanRegisterGlobalsName, IRB.getVoidTy(),
869 IntptrTy, IntptrTy, NULL));
870 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
871 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
872 kAsanUnregisterGlobalsName,
873 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
874 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
875}
876
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000877// This function replaces all global variables with new variables that have
878// trailing redzones. It also creates a function that poisons
879// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000880bool AddressSanitizerModule::runOnModule(Module &M) {
881 if (!ClGlobals) return false;
882 TD = getAnalysisIfAvailable<DataLayout>();
883 if (!TD)
884 return false;
Peter Collingbourne405515d2013-07-09 22:02:49 +0000885 BL.reset(new SpecialCaseList(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000886 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000887 C = &(M.getContext());
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000888 int LongSize = TD->getPointerSizeInBits();
889 IntptrTy = Type::getIntNTy(*C, LongSize);
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000890 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov46848582012-12-25 12:28:20 +0000891 initializeCallbacks(M);
892 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000893
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000894 SmallVector<GlobalVariable *, 16> GlobalsToChange;
895
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000896 for (Module::GlobalListType::iterator G = M.global_begin(),
897 E = M.global_end(); G != E; ++G) {
898 if (ShouldInstrumentGlobal(G))
899 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000900 }
901
902 size_t n = GlobalsToChange.size();
903 if (n == 0) return false;
904
905 // A global is described by a structure
906 // size_t beg;
907 // size_t size;
908 // size_t size_with_redzone;
909 // const char *name;
Kostya Serebryany086a4722013-03-18 08:05:29 +0000910 // const char *module_name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000911 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000912 // We initialize an array of such structures and pass it to a run-time call.
913 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000914 IntptrTy, IntptrTy,
Kostya Serebryany086a4722013-03-18 08:05:29 +0000915 IntptrTy, IntptrTy, NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000916 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000917
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000918
919 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
920 assert(CtorFunc);
921 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000922
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000923 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000924
Kostya Serebryany086a4722013-03-18 08:05:29 +0000925 GlobalVariable *ModuleName = createPrivateGlobalForString(
926 M, M.getModuleIdentifier());
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000927 // We shouldn't merge same module names, as this string serves as unique
928 // module ID in runtime.
929 ModuleName->setUnnamedAddr(false);
Kostya Serebryany086a4722013-03-18 08:05:29 +0000930
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000931 for (size_t i = 0; i < n; i++) {
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000932 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000933 GlobalVariable *G = GlobalsToChange[i];
934 PointerType *PtrTy = cast<PointerType>(G->getType());
935 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000936 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000937 uint64_t MinRZ = RedzoneSize();
Kostya Serebryany63f08462013-01-24 10:35:40 +0000938 // MinRZ <= RZ <= kMaxGlobalRedzone
939 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000940 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany63f08462013-01-24 10:35:40 +0000941 std::min(kMaxGlobalRedzone,
942 (SizeInBytes / MinRZ / 4) * MinRZ));
943 uint64_t RightRedzoneSize = RZ;
944 // Round up to MinRZ
945 if (SizeInBytes % MinRZ)
946 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
947 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000948 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000949 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000950 bool GlobalHasDynamicInitializer =
951 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000952 // Don't check initialization order if this global is blacklisted.
Peter Collingbourne46e11c42013-07-09 22:03:17 +0000953 GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000954
955 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
956 Constant *NewInitializer = ConstantStruct::get(
957 NewTy, G->getInitializer(),
958 Constant::getNullValue(RightRedZoneTy), NULL);
959
Kostya Serebryany086a4722013-03-18 08:05:29 +0000960 GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000961
962 // Create a new global variable with enough space for a redzone.
963 GlobalVariable *NewGlobal = new GlobalVariable(
964 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000965 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000966 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany63f08462013-01-24 10:35:40 +0000967 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000968
969 Value *Indices2[2];
970 Indices2[0] = IRB.getInt32(0);
971 Indices2[1] = IRB.getInt32(0);
972
973 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000974 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000975 NewGlobal->takeName(G);
976 G->eraseFromParent();
977
978 Initializers[i] = ConstantStruct::get(
979 GlobalStructTy,
980 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
981 ConstantInt::get(IntptrTy, SizeInBytes),
982 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
983 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany086a4722013-03-18 08:05:29 +0000984 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000985 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000986 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000987
988 // Populate the first and last globals declared in this TU.
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000989 if (CheckInitOrder && GlobalHasDynamicInitializer)
990 HasDynamicallyInitializedGlobals = true;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000991
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000992 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000993 }
994
995 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
996 GlobalVariable *AllGlobals = new GlobalVariable(
997 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
998 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
999
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001000 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovca825ea2013-03-26 13:05:41 +00001001 if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1002 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001003 IRB.CreateCall2(AsanRegisterGlobals,
1004 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1005 ConstantInt::get(IntptrTy, n));
1006
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001007 // We also need to unregister globals at the end, e.g. when a shared library
1008 // gets closed.
1009 Function *AsanDtorFunction = Function::Create(
1010 FunctionType::get(Type::getVoidTy(*C), false),
1011 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1012 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1013 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001014 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1015 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1016 ConstantInt::get(IntptrTy, n));
1017 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1018
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001019 DEBUG(dbgs() << M);
1020 return true;
1021}
1022
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001023void AddressSanitizer::initializeCallbacks(Module &M) {
1024 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001025 // Create __asan_report* callbacks.
1026 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1027 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1028 AccessSizeIndex++) {
1029 // IsWrite and TypeSize are encoded in the function name.
1030 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1031 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +00001032 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +00001033 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1034 checkInterfaceFunction(M.getOrInsertFunction(
1035 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001036 }
1037 }
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +00001038 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1039 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1040 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1041 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001042
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001043 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1044 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +00001045 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1046 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1047 StringRef(""), StringRef(""),
1048 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001049}
1050
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001051void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001052 // Tell the values of mapping offset and scale to the run-time.
1053 GlobalValue *asan_mapping_offset =
1054 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1055 ConstantInt::get(IntptrTy, Mapping.Offset),
1056 kAsanMappingOffsetName);
1057 // Read the global, otherwise it may be optimized away.
1058 IRB.CreateLoad(asan_mapping_offset, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001059
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001060 GlobalValue *asan_mapping_scale =
1061 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1062 ConstantInt::get(IntptrTy, Mapping.Scale),
1063 kAsanMappingScaleName);
1064 // Read the global, otherwise it may be optimized away.
1065 IRB.CreateLoad(asan_mapping_scale, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001066}
1067
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001068// virtual
1069bool AddressSanitizer::doInitialization(Module &M) {
1070 // Initialize the private fields. No one has accessed them before.
1071 TD = getAnalysisIfAvailable<DataLayout>();
1072
1073 if (!TD)
1074 return false;
Peter Collingbourne405515d2013-07-09 22:02:49 +00001075 BL.reset(new SpecialCaseList(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001076 DynamicallyInitializedGlobals.Init(M);
1077
1078 C = &(M.getContext());
1079 LongSize = TD->getPointerSizeInBits();
1080 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001081
1082 AsanCtorFunction = Function::Create(
1083 FunctionType::get(Type::getVoidTy(*C), false),
1084 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1085 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1086 // call __asan_init in the module ctor.
1087 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1088 AsanInitFunction = checkInterfaceFunction(
1089 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1090 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1091 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001092
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001093 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001094 emitShadowMapping(M, IRB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001095
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001096 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001097 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001098}
1099
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001100bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1101 // For each NSObject descendant having a +load method, this method is invoked
1102 // by the ObjC runtime before any of the static constructors is called.
1103 // Therefore we need to instrument such methods with a call to __asan_init
1104 // at the beginning in order to initialize our runtime before any access to
1105 // the shadow memory.
1106 // We cannot just ignore these methods, because they may call other
1107 // instrumented functions.
1108 if (F.getName().find(" load]") != std::string::npos) {
1109 IRBuilder<> IRB(F.begin()->begin());
1110 IRB.CreateCall(AsanInitFunction);
1111 return true;
1112 }
1113 return false;
1114}
1115
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001116bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001117 if (BL->isIn(F)) return false;
1118 if (&F == AsanCtorFunction) return false;
Kostya Serebryany3797adb2013-03-18 07:33:49 +00001119 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001120 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001121 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001122
Kostya Serebryany8eec41f2013-02-26 06:58:09 +00001123 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001124 maybeInsertAsanInitAtFunctionEntry(F);
1125
Kostya Serebryany20985712013-06-26 09:18:17 +00001126 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendling67658342012-10-09 07:45:08 +00001127 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001128
1129 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1130 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001131
1132 // We want to instrument every address only once per basic block (unless there
1133 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001134 SmallSet<Value*, 16> TempsToInstrument;
1135 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001136 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany20985712013-06-26 09:18:17 +00001137 int NumAllocas = 0;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001138 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001139
1140 // Fill the set of memory operations to instrument.
1141 for (Function::iterator FI = F.begin(), FE = F.end();
1142 FI != FE; ++FI) {
1143 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001144 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001145 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1146 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001147 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001148 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001149 if (ClOpt && ClOptSameTemp) {
1150 if (!TempsToInstrument.insert(Addr))
1151 continue; // We've seen this temp in the current BB.
1152 }
1153 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1154 // ok, take it.
1155 } else {
Kostya Serebryany20985712013-06-26 09:18:17 +00001156 if (isa<AllocaInst>(BI))
1157 NumAllocas++;
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001158 CallSite CS(BI);
1159 if (CS) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001160 // A call inside BB.
1161 TempsToInstrument.clear();
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001162 if (CS.doesNotReturn())
1163 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001164 }
1165 continue;
1166 }
1167 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001168 NumInsnsPerBB++;
1169 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1170 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001171 }
1172 }
1173
Kostya Serebryany20985712013-06-26 09:18:17 +00001174 Function *UninstrumentedDuplicate = 0;
1175 bool LikelyToInstrument =
1176 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1177 if (ClKeepUninstrumented && LikelyToInstrument) {
1178 ValueToValueMapTy VMap;
1179 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1180 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1181 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1182 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1183 }
1184
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001185 // Instrument.
1186 int NumInstrumented = 0;
1187 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1188 Instruction *Inst = ToInstrument[i];
1189 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1190 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001191 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001192 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001193 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001194 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001195 }
1196 NumInstrumented++;
1197 }
1198
Alexey Samsonov59cca132012-12-25 12:04:36 +00001199 FunctionStackPoisoner FSP(F, *this);
1200 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001201
1202 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1203 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1204 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1205 Instruction *CI = NoReturnCalls[i];
1206 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001207 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001208 }
1209
Kostya Serebryany20985712013-06-26 09:18:17 +00001210 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1211 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1212
1213 if (ClKeepUninstrumented) {
1214 if (!res) {
1215 // No instrumentation is done, no need for the duplicate.
1216 if (UninstrumentedDuplicate)
1217 UninstrumentedDuplicate->eraseFromParent();
1218 } else {
1219 // The function was instrumented. We must have the duplicate.
1220 assert(UninstrumentedDuplicate);
1221 UninstrumentedDuplicate->setSection("NOASAN");
1222 assert(!F.hasSection());
1223 F.setSection("ASAN");
1224 }
1225 }
1226
1227 return res;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001228}
1229
1230static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1231 if (ShadowRedzoneSize == 1) return PoisonByte;
1232 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1233 if (ShadowRedzoneSize == 4)
1234 return (PoisonByte << 24) + (PoisonByte << 16) +
1235 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001236 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001237}
1238
1239static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1240 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001241 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001242 size_t ShadowGranularity,
1243 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001244 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001245 i+= ShadowGranularity, Shadow++) {
1246 if (i + ShadowGranularity <= Size) {
1247 *Shadow = 0; // fully addressable
1248 } else if (i >= Size) {
1249 *Shadow = Magic; // unaddressable
1250 } else {
1251 *Shadow = Size - i; // first Size-i bytes are addressable
1252 }
1253 }
1254}
1255
Alexey Samsonov59cca132012-12-25 12:04:36 +00001256// Workaround for bug 11395: we don't want to instrument stack in functions
1257// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1258// FIXME: remove once the bug 11395 is fixed.
1259bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1260 if (LongSize != 32) return false;
1261 CallInst *CI = dyn_cast<CallInst>(I);
1262 if (!CI || !CI->isInlineAsm()) return false;
1263 if (CI->getNumArgOperands() <= 5) return false;
1264 // We have inline assembly with quite a few arguments.
1265 return true;
1266}
1267
1268void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1269 IRBuilder<> IRB(*C);
1270 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
1271 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
1272 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
1273 kAsanStackFreeName, IRB.getVoidTy(),
1274 IntptrTy, IntptrTy, IntptrTy, NULL));
1275 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1276 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1277 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1278 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1279}
1280
1281void FunctionStackPoisoner::poisonRedZones(
1282 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
1283 bool DoPoison) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001284 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001285 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1286 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1287 Type *RZPtrTy = PointerType::get(RZTy, 0);
1288
1289 Value *PoisonLeft = ConstantInt::get(RZTy,
1290 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1291 Value *PoisonMid = ConstantInt::get(RZTy,
1292 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1293 Value *PoisonRight = ConstantInt::get(RZTy,
1294 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1295
1296 // poison the first red zone.
1297 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1298
1299 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001300 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001301 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1302 AllocaInst *AI = AllocaVec[i];
1303 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1304 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001305 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001306 Value *Ptr = NULL;
1307
1308 Pos += AlignedSize;
1309
1310 assert(ShadowBase->getType() == IntptrTy);
1311 if (SizeInBytes < AlignedSize) {
1312 // Poison the partial redzone at right
1313 Ptr = IRB.CreateAdd(
1314 ShadowBase, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001315 (Pos >> Mapping.Scale) - ShadowRZSize));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001316 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001317 uint32_t Poison = 0;
1318 if (DoPoison) {
1319 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001320 RedzoneSize(),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001321 1ULL << Mapping.Scale,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001322 kAsanStackPartialRedzoneMagic);
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +00001323 Poison =
1324 ASan.TD->isLittleEndian()
1325 ? support::endian::byte_swap<uint32_t, support::little>(Poison)
1326 : support::endian::byte_swap<uint32_t, support::big>(Poison);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001327 }
1328 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1329 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1330 }
1331
1332 // Poison the full redzone at right.
1333 Ptr = IRB.CreateAdd(ShadowBase,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001334 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001335 bool LastAlloca = (i == AllocaVec.size() - 1);
1336 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001337 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1338
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001339 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001340 }
1341}
1342
Alexey Samsonov59cca132012-12-25 12:04:36 +00001343void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001344 uint64_t LocalStackSize = TotalStackSize +
1345 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001346
Alexey Samsonov59cca132012-12-25 12:04:36 +00001347 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001348 && LocalStackSize <= kMaxStackMallocSize;
1349
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001350 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001351 Instruction *InsBefore = AllocaVec[0];
1352 IRBuilder<> IRB(InsBefore);
1353
1354
1355 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1356 AllocaInst *MyAlloca =
1357 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001358 if (ClRealignStack && StackAlignment < RedzoneSize())
1359 StackAlignment = RedzoneSize();
1360 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001361 assert(MyAlloca->isStaticAlloca());
1362 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1363 Value *LocalStackBase = OrigStackBase;
1364
1365 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001366 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1367 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1368 }
1369
Kostya Serebryany30160562013-03-22 10:37:20 +00001370 // This string will be parsed by the run-time (DescribeAddressIfStack).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001371 SmallString<2048> StackDescriptionStorage;
1372 raw_svector_ostream StackDescription(StackDescriptionStorage);
Kostya Serebryany30160562013-03-22 10:37:20 +00001373 StackDescription << AllocaVec.size() << " ";
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001374
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001375 // Insert poison calls for lifetime intrinsics for alloca.
1376 bool HavePoisonedAllocas = false;
1377 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1378 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1379 IntrinsicInst *II = APC.InsBefore;
1380 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1381 assert(AI);
1382 IRBuilder<> IRB(II);
1383 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1384 HavePoisonedAllocas |= APC.DoPoison;
1385 }
1386
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001387 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001388 // Replace Alloca instructions with base+offset.
1389 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1390 AllocaInst *AI = AllocaVec[i];
1391 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1392 StringRef Name = AI->getName();
1393 StackDescription << Pos << " " << SizeInBytes << " "
1394 << Name.size() << " " << Name << " ";
1395 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001396 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001397 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001398 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001399 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001400 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001401 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001402 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001403 }
1404 assert(Pos == LocalStackSize);
1405
Kostya Serebryany30160562013-03-22 10:37:20 +00001406 // The left-most redzone has enough space for at least 4 pointers.
1407 // Write the Magic value to redzone[0].
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001408 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1409 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1410 BasePlus0);
Kostya Serebryany30160562013-03-22 10:37:20 +00001411 // Write the frame description constant to redzone[1].
1412 Value *BasePlus1 = IRB.CreateIntToPtr(
1413 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1414 IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001415 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001416 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001417 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1418 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001419 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryany30160562013-03-22 10:37:20 +00001420 // Write the PC to redzone[2].
1421 Value *BasePlus2 = IRB.CreateIntToPtr(
1422 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1423 2 * ASan.LongSize/8)),
1424 IntptrPtrTy);
1425 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001426
1427 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001428 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1429 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001430
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001431 // Unpoison the stack before all ret instructions.
1432 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1433 Instruction *Ret = RetVec[i];
1434 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001435 // Mark the current frame as retired.
1436 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1437 BasePlus0);
1438 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001439 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001440 if (DoStackMalloc) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001441 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001442 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1443 ConstantInt::get(IntptrTy, LocalStackSize),
1444 OrigStackBase);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001445 } else if (HavePoisonedAllocas) {
1446 // If we poisoned some allocas in llvm.lifetime analysis,
1447 // unpoison whole stack frame now.
1448 assert(LocalStackBase == OrigStackBase);
1449 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001450 }
1451 }
1452
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001453 // We are done. Remove the old unused alloca instructions.
1454 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1455 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001456}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001457
Alexey Samsonov59cca132012-12-25 12:04:36 +00001458void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1459 IRBuilder<> IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001460 // For now just insert the call to ASan runtime.
1461 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1462 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1463 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1464 : AsanUnpoisonStackMemoryFunc,
1465 AddrArg, SizeArg);
1466}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001467
1468// Handling llvm.lifetime intrinsics for a given %alloca:
1469// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1470// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1471// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1472// could be poisoned by previous llvm.lifetime.end instruction, as the
1473// variable may go in and out of scope several times, e.g. in loops).
1474// (3) if we poisoned at least one %alloca in a function,
1475// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001476
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001477AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1478 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1479 // We're intested only in allocas we can handle.
1480 return isInterestingAlloca(*AI) ? AI : 0;
1481 // See if we've already calculated (or started to calculate) alloca for a
1482 // given value.
1483 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1484 if (I != AllocaForValue.end())
1485 return I->second;
1486 // Store 0 while we're calculating alloca for value V to avoid
1487 // infinite recursion if the value references itself.
1488 AllocaForValue[V] = 0;
1489 AllocaInst *Res = 0;
1490 if (CastInst *CI = dyn_cast<CastInst>(V))
1491 Res = findAllocaForValue(CI->getOperand(0));
1492 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1493 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1494 Value *IncValue = PN->getIncomingValue(i);
1495 // Allow self-referencing phi-nodes.
1496 if (IncValue == PN) continue;
1497 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1498 // AI for incoming values should exist and should all be equal.
1499 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1500 return 0;
1501 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001502 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001503 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001504 if (Res != 0)
1505 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001506 return Res;
1507}