blob: 2ee0f9d4a236489ccd148e0fe4a5709b0c004fb0 [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
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +000062static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany800e03f2011-11-16 01:35:23 +000063static const size_t kMaxStackMallocSize = 1 << 16; // 64K
64static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
65static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
66
Craig Topper4172a8a2013-07-16 01:17:10 +000067static const char *const kAsanModuleCtorName = "asan.module_ctor";
68static const char *const kAsanModuleDtorName = "asan.module_dtor";
69static const int kAsanCtorAndCtorPriority = 1;
70static const char *const kAsanReportErrorTemplate = "__asan_report_";
71static const char *const kAsanReportLoadN = "__asan_report_load_n";
72static const char *const kAsanReportStoreN = "__asan_report_store_n";
73static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonov48d7d1d2013-08-05 13:19:49 +000074static const char *const kAsanUnregisterGlobalsName =
75 "__asan_unregister_globals";
Craig Topper4172a8a2013-07-16 01:17:10 +000076static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
77static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
78static const char *const kAsanInitName = "__asan_init_v3";
79static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
80static const char *const kAsanMappingOffsetName = "__asan_mapping_offset";
81static const char *const kAsanMappingScaleName = "__asan_mapping_scale";
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +000082static const int kMaxAsanStackMallocSizeClass = 10;
83static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
84static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topper4172a8a2013-07-16 01:17:10 +000085static const char *const kAsanGenPrefix = "__asan_gen_";
86static const char *const kAsanPoisonStackMemoryName =
87 "__asan_poison_stack_memory";
88static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonovf985f442012-12-04 01:34:23 +000089 "__asan_unpoison_stack_memory";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000090
Kostya Serebryany671c3ba2013-09-17 12:14:50 +000091// These constants must match the definitions in the run-time library.
Kostya Serebryany800e03f2011-11-16 01:35:23 +000092static const int kAsanStackLeftRedzoneMagic = 0xf1;
93static const int kAsanStackMidRedzoneMagic = 0xf2;
94static const int kAsanStackRightRedzoneMagic = 0xf3;
95static const int kAsanStackPartialRedzoneMagic = 0xf4;
David Blaikie0b956502013-09-18 00:11:27 +000096#ifndef NDEBUG
Kostya Serebryany671c3ba2013-09-17 12:14:50 +000097static const int kAsanStackAfterReturnMagic = 0xf5;
David Blaikie0b956502013-09-18 00:11:27 +000098#endif
Kostya Serebryany800e03f2011-11-16 01:35:23 +000099
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000100// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
101static const size_t kNumberOfAccessSizes = 5;
102
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000103// Command-line flags.
104
105// This flag may need to be replaced with -f[no-]asan-reads.
106static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
107 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
108static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
109 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000110static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
111 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
112 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000113static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
114 cl::desc("use instrumentation with slow path for all accesses"),
115 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000116// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000117// in any given BB. Normally, this should be set to unlimited (INT_MAX),
118// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
119// set it to 10000.
120static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
121 cl::init(10000),
122 cl::desc("maximal number of instructions to instrument in any given BB"),
123 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000124// This flag may need to be replaced with -f[no]asan-stack.
125static cl::opt<bool> ClStack("asan-stack",
126 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
127// This flag may need to be replaced with -f[no]asan-use-after-return.
128static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
129 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
130// This flag may need to be replaced with -f[no]asan-globals.
131static cl::opt<bool> ClGlobals("asan-globals",
132 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000133static cl::opt<bool> ClInitializers("asan-initialization-order",
134 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000135static cl::opt<bool> ClMemIntrin("asan-memintrin",
136 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Kostya Serebryany6c554122012-12-04 06:14:01 +0000137static cl::opt<bool> ClRealignStack("asan-realign-stack",
138 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000139static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
140 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000141 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000142
Kostya Serebryany20985712013-06-26 09:18:17 +0000143// This is an experimental feature that will allow to choose between
144// instrumented and non-instrumented code at link-time.
145// If this option is on, just before instrumenting a function we create its
146// clone; if the function is not changed by asan the clone is deleted.
147// If we end up with a clone, we put the instrumented function into a section
148// called "ASAN" and the uninstrumented function into a section called "NOASAN".
149//
150// This is still a prototype, we need to figure out a way to keep two copies of
151// a function so that the linker can easily choose one of them.
152static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
153 cl::desc("Keep uninstrumented copies of functions"),
154 cl::Hidden, cl::init(false));
155
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000156// These flags allow to change the shadow mapping.
157// The shadow mapping looks like
158// Shadow = (Mem >> scale) + (1 << offset_log)
159static cl::opt<int> ClMappingScale("asan-mapping-scale",
160 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
161static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
162 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
Kostya Serebryany117de482013-02-11 14:36:01 +0000163static cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
164 cl::desc("Use short immediate constant as the mapping offset for 64bit"),
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000165 cl::Hidden, cl::init(true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000166
167// Optimization flags. Not user visible, used mostly for testing
168// and benchmarking the tool.
169static cl::opt<bool> ClOpt("asan-opt",
170 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
171static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
172 cl::desc("Instrument the same temp just once"), cl::Hidden,
173 cl::init(true));
174static cl::opt<bool> ClOptGlobals("asan-opt-globals",
175 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
176
Alexey Samsonovee548272012-11-29 18:14:24 +0000177static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
178 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
179 cl::Hidden, cl::init(false));
180
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000181// Debug flags.
182static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
183 cl::init(0));
184static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
185 cl::Hidden, cl::init(0));
186static cl::opt<std::string> ClDebugFunc("asan-debug-func",
187 cl::Hidden, cl::desc("Debug func"));
188static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
189 cl::Hidden, cl::init(-1));
190static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
191 cl::Hidden, cl::init(-1));
192
193namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000194/// A set of dynamically initialized globals extracted from metadata.
195class SetOfDynamicallyInitializedGlobals {
196 public:
197 void Init(Module& M) {
198 // Clang generates metadata identifying all dynamically initialized globals.
199 NamedMDNode *DynamicGlobals =
200 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
201 if (!DynamicGlobals)
202 return;
203 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
204 MDNode *MDN = DynamicGlobals->getOperand(i);
205 assert(MDN->getNumOperands() == 1);
206 Value *VG = MDN->getOperand(0);
207 // The optimizer may optimize away a global entirely, in which case we
208 // cannot instrument access to it.
209 if (!VG)
210 continue;
211 DynInitGlobals.insert(cast<GlobalVariable>(VG));
212 }
213 }
214 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
215 private:
216 SmallSet<GlobalValue*, 32> DynInitGlobals;
217};
218
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000219/// This struct defines the shadow mapping using the rule:
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000220/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000221struct ShadowMapping {
222 int Scale;
223 uint64_t Offset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000224 bool OrShadowOffset;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000225};
226
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000227static ShadowMapping getShadowMapping(const Module &M, int LongSize,
228 bool ZeroBaseShadow) {
229 llvm::Triple TargetTriple(M.getTargetTriple());
230 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000231 bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
Bill Schmidtf38cc382013-07-26 01:35:43 +0000232 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
233 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000234 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +0000235 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
236 TargetTriple.getArch() == llvm::Triple::mipsel;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000237
238 ShadowMapping Mapping;
239
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000240 // OR-ing shadow offset if more efficient (at least on x86),
241 // but on ppc64 we have to use add since the shadow offset is not neccesary
242 // 1/8-th of the address space.
Kostya Serebryany117de482013-02-11 14:36:01 +0000243 Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000244
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000245 Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +0000246 (LongSize == 32 ?
247 (IsMIPS32 ? kMIPS32_ShadowOffset32 : kDefaultShadowOffset32) :
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000248 IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000249 if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000250 assert(LongSize == 64);
Kostya Serebryany117de482013-02-11 14:36:01 +0000251 Mapping.Offset = kDefaultShort64bitShadowOffset;
Kostya Serebryany39f02942013-02-13 05:14:12 +0000252 }
253 if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000254 // Zero offset log is the special case.
255 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
256 }
257
258 Mapping.Scale = kDefaultShadowScale;
259 if (ClMappingScale) {
260 Mapping.Scale = ClMappingScale;
261 }
262
263 return Mapping;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000264}
265
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000266static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000267 // Redzone used for stack and globals is at least 32 bytes.
268 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000269 return std::max(32U, 1U << MappingScale);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000270}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000271
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000272/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000273struct AddressSanitizer : public FunctionPass {
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000274 AddressSanitizer(bool CheckInitOrder = true,
Alexey Samsonovee548272012-11-29 18:14:24 +0000275 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000276 bool CheckLifetime = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000277 StringRef BlacklistFile = StringRef(),
278 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000279 : FunctionPass(ID),
280 CheckInitOrder(CheckInitOrder || ClInitializers),
281 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000282 CheckLifetime(CheckLifetime || ClCheckLifetime),
283 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000284 : BlacklistFile),
285 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000286 virtual const char *getPassName() const {
287 return "AddressSanitizerFunctionPass";
288 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000289 void instrumentMop(Instruction *I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000290 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
291 Value *Addr, uint32_t TypeSize, bool IsWrite,
292 Value *SizeArgument);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000293 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
294 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000295 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000296 bool IsWrite, size_t AccessSizeIndex,
297 Value *SizeArgument);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000298 bool instrumentMemIntrinsic(MemIntrinsic *MI);
299 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000300 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000301 Instruction *InsertBefore, bool IsWrite);
302 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000303 bool runOnFunction(Function &F);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000304 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000305 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000306 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000307 static char ID; // Pass identification, replacement for typeid
308
309 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000310 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000311
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000312 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000313 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000314 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000315
Alexey Samsonovee548272012-11-29 18:14:24 +0000316 bool CheckInitOrder;
317 bool CheckUseAfterReturn;
318 bool CheckLifetime;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000319 SmallString<64> BlacklistFile;
320 bool ZeroBaseShadow;
321
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000322 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000323 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000324 int LongSize;
325 Type *IntptrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000326 ShadowMapping Mapping;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000327 Function *AsanCtorFunction;
328 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000329 Function *AsanHandleNoReturnFunc;
Peter Collingbourne405515d2013-07-09 22:02:49 +0000330 OwningPtr<SpecialCaseList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000331 // This array is indexed by AccessIsWrite and log2(AccessSize).
332 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000333 // This array is indexed by AccessIsWrite.
334 Function *AsanErrorCallbackSized[2];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000335 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000336 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000337
338 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000339};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000340
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000341class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000342 public:
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000343 AddressSanitizerModule(bool CheckInitOrder = true,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000344 StringRef BlacklistFile = StringRef(),
345 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000346 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000347 CheckInitOrder(CheckInitOrder || ClInitializers),
348 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000349 : BlacklistFile),
350 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000351 bool runOnModule(Module &M);
352 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000353 virtual const char *getPassName() const {
354 return "AddressSanitizerModule";
355 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000356
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000357 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000358 void initializeCallbacks(Module &M);
359
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000360 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000361 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000362 size_t RedzoneSize() const {
363 return RedzoneSizeForScale(Mapping.Scale);
364 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000365
Alexey Samsonovee548272012-11-29 18:14:24 +0000366 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000367 SmallString<64> BlacklistFile;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000368 bool ZeroBaseShadow;
369
Peter Collingbourne405515d2013-07-09 22:02:49 +0000370 OwningPtr<SpecialCaseList> BL;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000371 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
372 Type *IntptrTy;
373 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000374 DataLayout *TD;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000375 ShadowMapping Mapping;
Alexey Samsonov46848582012-12-25 12:28:20 +0000376 Function *AsanPoisonGlobals;
377 Function *AsanUnpoisonGlobals;
378 Function *AsanRegisterGlobals;
379 Function *AsanUnregisterGlobals;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000380};
381
Alexey Samsonov59cca132012-12-25 12:04:36 +0000382// Stack poisoning does not play well with exception handling.
383// When an exception is thrown, we essentially bypass the code
384// that unpoisones the stack. This is why the run-time library has
385// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
386// stack in the interceptor. This however does not work inside the
387// actual function which catches the exception. Most likely because the
388// compiler hoists the load of the shadow value somewhere too high.
389// This causes asan to report a non-existing bug on 453.povray.
390// It sounds like an LLVM bug.
391struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
392 Function &F;
393 AddressSanitizer &ASan;
394 DIBuilder DIB;
395 LLVMContext *C;
396 Type *IntptrTy;
397 Type *IntptrPtrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000398 ShadowMapping Mapping;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000399
400 SmallVector<AllocaInst*, 16> AllocaVec;
401 SmallVector<Instruction*, 8> RetVec;
402 uint64_t TotalStackSize;
403 unsigned StackAlignment;
404
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +0000405 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
406 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov59cca132012-12-25 12:04:36 +0000407 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
408
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000409 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
410 struct AllocaPoisonCall {
411 IntrinsicInst *InsBefore;
412 uint64_t Size;
413 bool DoPoison;
414 };
415 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
416
417 // Maps Value to an AllocaInst from which the Value is originated.
418 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
419 AllocaForValueMapTy AllocaForValue;
420
Alexey Samsonov59cca132012-12-25 12:04:36 +0000421 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
422 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
423 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000424 Mapping(ASan.Mapping),
425 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov59cca132012-12-25 12:04:36 +0000426
427 bool runOnFunction() {
428 if (!ClStack) return false;
429 // Collect alloca, ret, lifetime instructions etc.
430 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
431 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
432 BasicBlock *BB = *DI;
433 visit(*BB);
434 }
435 if (AllocaVec.empty()) return false;
436
437 initializeCallbacks(*F.getParent());
438
439 poisonStack();
440
441 if (ClDebugStack) {
442 DEBUG(dbgs() << F);
443 }
444 return true;
445 }
446
447 // Finds all static Alloca instructions and puts
448 // poisoned red zones around all of them.
449 // Then unpoison everything back before the function returns.
450 void poisonStack();
451
452 // ----------------------- Visitors.
453 /// \brief Collect all Ret instructions.
454 void visitReturnInst(ReturnInst &RI) {
455 RetVec.push_back(&RI);
456 }
457
458 /// \brief Collect Alloca instructions we want (and can) handle.
459 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000460 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000461
462 StackAlignment = std::max(StackAlignment, AI.getAlignment());
463 AllocaVec.push_back(&AI);
Kostya Serebryanyd4429212013-06-26 09:49:52 +0000464 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000465 TotalStackSize += AlignedSize;
466 }
467
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000468 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
469 /// errors.
470 void visitIntrinsicInst(IntrinsicInst &II) {
471 if (!ASan.CheckLifetime) return;
472 Intrinsic::ID ID = II.getIntrinsicID();
473 if (ID != Intrinsic::lifetime_start &&
474 ID != Intrinsic::lifetime_end)
475 return;
476 // Found lifetime intrinsic, add ASan instrumentation if necessary.
477 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
478 // If size argument is undefined, don't do anything.
479 if (Size->isMinusOne()) return;
480 // Check that size doesn't saturate uint64_t and can
481 // be stored in IntptrTy.
482 const uint64_t SizeValue = Size->getValue().getLimitedValue();
483 if (SizeValue == ~0ULL ||
484 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
485 return;
486 // Find alloca instruction that corresponds to llvm.lifetime argument.
487 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
488 if (!AI) return;
489 bool DoPoison = (ID == Intrinsic::lifetime_end);
490 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
491 AllocaPoisonCallVec.push_back(APC);
492 }
493
Alexey Samsonov59cca132012-12-25 12:04:36 +0000494 // ---------------------- Helpers.
495 void initializeCallbacks(Module &M);
496
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000497 // Check if we want (and can) handle this alloca.
Jakub Staszak4c710642013-08-09 20:53:48 +0000498 bool isInterestingAlloca(AllocaInst &AI) const {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000499 return (!AI.isArrayAllocation() &&
500 AI.isStaticAlloca() &&
Kostya Serebryanyd4429212013-06-26 09:49:52 +0000501 AI.getAlignment() <= RedzoneSize() &&
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000502 AI.getAllocatedType()->isSized());
503 }
504
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000505 size_t RedzoneSize() const {
506 return RedzoneSizeForScale(Mapping.Scale);
507 }
Jakub Staszak4c710642013-08-09 20:53:48 +0000508 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Alexey Samsonov59cca132012-12-25 12:04:36 +0000509 Type *Ty = AI->getAllocatedType();
510 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
511 return SizeInBytes;
512 }
Jakub Staszak4c710642013-08-09 20:53:48 +0000513 uint64_t getAlignedSize(uint64_t SizeInBytes) const {
Alexey Samsonov59cca132012-12-25 12:04:36 +0000514 size_t RZ = RedzoneSize();
515 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
516 }
Jakub Staszak4c710642013-08-09 20:53:48 +0000517 uint64_t getAlignedAllocaSize(AllocaInst *AI) const {
Alexey Samsonov59cca132012-12-25 12:04:36 +0000518 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
519 return getAlignedSize(SizeInBytes);
520 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000521 /// Finds alloca where the value comes from.
522 AllocaInst *findAllocaForValue(Value *V);
Jakub Staszak4c710642013-08-09 20:53:48 +0000523 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB,
Alexey Samsonov59cca132012-12-25 12:04:36 +0000524 Value *ShadowBase, bool DoPoison);
Jakub Staszak4c710642013-08-09 20:53:48 +0000525 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryany671c3ba2013-09-17 12:14:50 +0000526
527 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
528 int Size);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000529};
530
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000531} // namespace
532
533char AddressSanitizer::ID = 0;
534INITIALIZE_PASS(AddressSanitizer, "asan",
535 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
536 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000537FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000538 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000539 StringRef BlacklistFile, bool ZeroBaseShadow) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000540 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000541 CheckLifetime, BlacklistFile, ZeroBaseShadow);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000542}
543
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000544char AddressSanitizerModule::ID = 0;
545INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
546 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
547 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000548ModulePass *llvm::createAddressSanitizerModulePass(
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000549 bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
550 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
551 ZeroBaseShadow);
Alexander Potapenko25878042012-01-23 11:22:43 +0000552}
553
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000554static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerc6af2432013-05-24 22:23:49 +0000555 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000556 assert(Res < kNumberOfAccessSizes);
557 return Res;
558}
559
Bill Wendling55a1a592013-08-06 22:52:42 +0000560// \brief Create a constant for Str so that we can pass it to the run-time lib.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000561static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000562 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany51116272013-03-18 09:38:39 +0000563 GlobalVariable *GV = new GlobalVariable(M, StrConst->getType(), true,
Bill Wendling55a1a592013-08-06 22:52:42 +0000564 GlobalValue::InternalLinkage, StrConst,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000565 kAsanGenPrefix);
Kostya Serebryany51116272013-03-18 09:38:39 +0000566 GV->setUnnamedAddr(true); // Ok to merge these.
567 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
568 return GV;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000569}
570
571static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
572 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000573}
574
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000575Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
576 // Shadow >> scale
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000577 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
578 if (Mapping.Offset == 0)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000579 return Shadow;
580 // (Shadow >> scale) | offset
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000581 if (Mapping.OrShadowOffset)
582 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
583 else
584 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000585}
586
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000587void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000588 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000589 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000590 IRBuilder<> IRB(InsertBefore);
591 if (Size->getType() != IntptrTy)
592 Size = IRB.CreateIntCast(Size, IntptrTy, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000593 // Check the first byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000594 instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000595 // Check the last byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000596 IRB.SetInsertPoint(InsertBefore);
597 Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
598 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
599 Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
600 instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000601}
602
603// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000604bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000605 Value *Dst = MI->getDest();
606 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000607 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000608 Value *Length = MI->getLength();
609
610 Constant *ConstLength = dyn_cast<Constant>(Length);
611 Instruction *InsertBefore = MI;
612 if (ConstLength) {
613 if (ConstLength->isNullValue()) return false;
614 } else {
615 // The size is not a constant so it could be zero -- check at run-time.
616 IRBuilder<> IRB(InsertBefore);
617
618 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000619 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000620 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000621 }
622
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000623 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000624 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000625 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000626 return true;
627}
628
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000629// If I is an interesting memory access, return the PointerOperand
630// and set IsWrite. Otherwise return NULL.
631static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000632 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000633 if (!ClInstrumentReads) return NULL;
634 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000635 return LI->getPointerOperand();
636 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000637 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
638 if (!ClInstrumentWrites) return NULL;
639 *IsWrite = true;
640 return SI->getPointerOperand();
641 }
642 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
643 if (!ClInstrumentAtomics) return NULL;
644 *IsWrite = true;
645 return RMW->getPointerOperand();
646 }
647 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
648 if (!ClInstrumentAtomics) return NULL;
649 *IsWrite = true;
650 return XCHG->getPointerOperand();
651 }
652 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000653}
654
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000655void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000656 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000657 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
658 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000659 if (ClOpt && ClOptGlobals) {
660 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
661 // If initialization order checking is disabled, a simple access to a
662 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000663 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000664 return;
665 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000666 // have to instrument it. However, if a global does not have initailizer
667 // at all, we assume it has dynamic initializer (in other TU).
668 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000669 return;
670 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000671 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000672
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000673 Type *OrigPtrTy = Addr->getType();
674 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
675
676 assert(OrigTy->isSized());
Kostya Serebryany605ff662013-02-18 13:47:02 +0000677 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000678
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000679 assert((TypeSize % 8) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000680
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000681 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
682 if (TypeSize == 8 || TypeSize == 16 ||
683 TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
684 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
685 // Instrument unusual size (but still multiple of 8).
686 // We can not do it with a single check, so we do 1-byte check for the first
687 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
688 // to report the actual access size.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000689 IRBuilder<> IRB(I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000690 Value *LastByte = IRB.CreateIntToPtr(
691 IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
692 ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
693 OrigPtrTy);
694 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
695 instrumentAddress(I, I, Addr, 8, IsWrite, Size);
696 instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000697}
698
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000699// Validate the result of Module::getOrInsertFunction called for an interface
700// function of AddressSanitizer. If the instrumented module defines a function
701// with the same name, their prototypes must match, otherwise
702// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000703static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000704 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
705 FuncOrBitcast->dump();
706 report_fatal_error("trying to redefine an AddressSanitizer "
707 "interface function");
708}
709
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000710Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000711 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000712 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000713 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000714 CallInst *Call = SizeArgument
715 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
716 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
717
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000718 // We don't do Call->setDoesNotReturn() because the BB already has
719 // UnreachableInst at the end.
720 // This EmptyAsm is required to avoid callback merge.
721 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000722 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000723}
724
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000725Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000726 Value *ShadowValue,
727 uint32_t TypeSize) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000728 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000729 // Addr & (Granularity - 1)
730 Value *LastAccessedByte = IRB.CreateAnd(
731 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
732 // (Addr & (Granularity - 1)) + size - 1
733 if (TypeSize / 8 > 1)
734 LastAccessedByte = IRB.CreateAdd(
735 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
736 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
737 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000738 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000739 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
740 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
741}
742
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000743void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000744 Instruction *InsertBefore,
745 Value *Addr, uint32_t TypeSize,
746 bool IsWrite, Value *SizeArgument) {
747 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000748 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
749
750 Type *ShadowTy = IntegerType::get(
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000751 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000752 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
753 Value *ShadowPtr = memToShadow(AddrLong, IRB);
754 Value *CmpVal = Constant::getNullValue(ShadowTy);
755 Value *ShadowValue = IRB.CreateLoad(
756 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
757
758 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000759 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000760 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000761 TerminatorInst *CrashTerm = 0;
762
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000763 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000764 TerminatorInst *CheckTerm =
765 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000766 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000767 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000768 IRB.SetInsertPoint(CheckTerm);
769 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000770 BasicBlock *CrashBlock =
771 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000772 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000773 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
774 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000775 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000776 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000777 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000778
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000779 Instruction *Crash = generateCrashCode(
780 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000781 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000782}
783
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000784void AddressSanitizerModule::createInitializerPoisonCalls(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000785 Module &M, GlobalValue *ModuleName) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000786 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
787 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
788 // If that function is not present, this TU contains no globals, or they have
789 // all been optimized away
790 if (!GlobalInit)
791 return;
792
793 // Set up the arguments to our poison/unpoison functions.
794 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
795
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000796 // Add a call to poison all external globals before the given function starts.
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000797 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
798 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000799
800 // Add calls to unpoison all globals before each return instruction.
801 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
802 I != E; ++I) {
803 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
804 CallInst::Create(AsanUnpoisonGlobals, "", RI);
805 }
806 }
807}
808
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000809bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000810 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000811 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000812
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000813 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000814 if (!Ty->isSized()) return false;
815 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000816 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000817 // Touch only those globals that will not be defined in other modules.
818 // Don't handle ODR type linkages since other modules may be built w/o asan.
819 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
820 G->getLinkage() != GlobalVariable::PrivateLinkage &&
821 G->getLinkage() != GlobalVariable::InternalLinkage)
822 return false;
823 // Two problems with thread-locals:
824 // - The address of the main thread's copy can't be computed at link-time.
825 // - Need to poison all copies, not just the main thread's one.
826 if (G->isThreadLocal())
827 return false;
828 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000829 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000830
831 // Ignore all the globals with the names starting with "\01L_OBJC_".
832 // Many of those are put into the .cstring section. The linker compresses
833 // that section by removing the spare \0s after the string terminator, so
834 // our redzones get broken.
835 if ((G->getName().find("\01L_OBJC_") == 0) ||
836 (G->getName().find("\01l_OBJC_") == 0)) {
837 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
838 return false;
839 }
840
841 if (G->hasSection()) {
842 StringRef Section(G->getSection());
843 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
844 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
845 // them.
846 if ((Section.find("__OBJC,") == 0) ||
847 (Section.find("__DATA, __objc_") == 0)) {
848 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
849 return false;
850 }
851 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
852 // Constant CFString instances are compiled in the following way:
853 // -- the string buffer is emitted into
854 // __TEXT,__cstring,cstring_literals
855 // -- the constant NSConstantString structure referencing that buffer
856 // is placed into __DATA,__cfstring
857 // Therefore there's no point in placing redzones into __DATA,__cfstring.
858 // Moreover, it causes the linker to crash on OS X 10.7
859 if (Section.find("__DATA,__cfstring") == 0) {
860 DEBUG(dbgs() << "Ignoring CFString: " << *G);
861 return false;
862 }
863 }
864
865 return true;
866}
867
Alexey Samsonov46848582012-12-25 12:28:20 +0000868void AddressSanitizerModule::initializeCallbacks(Module &M) {
869 IRBuilder<> IRB(*C);
870 // Declare our poisoning and unpoisoning functions.
871 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000872 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
Alexey Samsonov46848582012-12-25 12:28:20 +0000873 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
874 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
875 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
876 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
877 // Declare functions that register/unregister globals.
878 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
879 kAsanRegisterGlobalsName, IRB.getVoidTy(),
880 IntptrTy, IntptrTy, NULL));
881 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
882 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
883 kAsanUnregisterGlobalsName,
884 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
885 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
886}
887
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000888// This function replaces all global variables with new variables that have
889// trailing redzones. It also creates a function that poisons
890// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000891bool AddressSanitizerModule::runOnModule(Module &M) {
892 if (!ClGlobals) return false;
893 TD = getAnalysisIfAvailable<DataLayout>();
894 if (!TD)
895 return false;
Alexey Samsonove39e1312013-08-12 11:46:09 +0000896 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000897 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000898 C = &(M.getContext());
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000899 int LongSize = TD->getPointerSizeInBits();
900 IntptrTy = Type::getIntNTy(*C, LongSize);
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000901 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov46848582012-12-25 12:28:20 +0000902 initializeCallbacks(M);
903 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000904
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000905 SmallVector<GlobalVariable *, 16> GlobalsToChange;
906
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000907 for (Module::GlobalListType::iterator G = M.global_begin(),
908 E = M.global_end(); G != E; ++G) {
909 if (ShouldInstrumentGlobal(G))
910 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000911 }
912
913 size_t n = GlobalsToChange.size();
914 if (n == 0) return false;
915
916 // A global is described by a structure
917 // size_t beg;
918 // size_t size;
919 // size_t size_with_redzone;
920 // const char *name;
Kostya Serebryany086a4722013-03-18 08:05:29 +0000921 // const char *module_name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000922 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000923 // We initialize an array of such structures and pass it to a run-time call.
924 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000925 IntptrTy, IntptrTy,
Kostya Serebryany086a4722013-03-18 08:05:29 +0000926 IntptrTy, IntptrTy, NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000927 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000928
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000929
930 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
931 assert(CtorFunc);
932 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000933
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000934 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000935
Kostya Serebryany086a4722013-03-18 08:05:29 +0000936 GlobalVariable *ModuleName = createPrivateGlobalForString(
937 M, M.getModuleIdentifier());
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000938 // We shouldn't merge same module names, as this string serves as unique
939 // module ID in runtime.
940 ModuleName->setUnnamedAddr(false);
Kostya Serebryany086a4722013-03-18 08:05:29 +0000941
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000942 for (size_t i = 0; i < n; i++) {
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000943 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000944 GlobalVariable *G = GlobalsToChange[i];
945 PointerType *PtrTy = cast<PointerType>(G->getType());
946 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000947 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000948 uint64_t MinRZ = RedzoneSize();
Kostya Serebryany63f08462013-01-24 10:35:40 +0000949 // MinRZ <= RZ <= kMaxGlobalRedzone
950 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000951 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany63f08462013-01-24 10:35:40 +0000952 std::min(kMaxGlobalRedzone,
953 (SizeInBytes / MinRZ / 4) * MinRZ));
954 uint64_t RightRedzoneSize = RZ;
955 // Round up to MinRZ
956 if (SizeInBytes % MinRZ)
957 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
958 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000959 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000960 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000961 bool GlobalHasDynamicInitializer =
962 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000963 // Don't check initialization order if this global is blacklisted.
Peter Collingbourne46e11c42013-07-09 22:03:17 +0000964 GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000965
966 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
967 Constant *NewInitializer = ConstantStruct::get(
968 NewTy, G->getInitializer(),
969 Constant::getNullValue(RightRedZoneTy), NULL);
970
Kostya Serebryany086a4722013-03-18 08:05:29 +0000971 GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000972
973 // Create a new global variable with enough space for a redzone.
Bill Wendling55a1a592013-08-06 22:52:42 +0000974 GlobalValue::LinkageTypes Linkage = G->getLinkage();
975 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
976 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000977 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling55a1a592013-08-06 22:52:42 +0000978 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000979 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000980 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany63f08462013-01-24 10:35:40 +0000981 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000982
983 Value *Indices2[2];
984 Indices2[0] = IRB.getInt32(0);
985 Indices2[1] = IRB.getInt32(0);
986
987 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000988 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000989 NewGlobal->takeName(G);
990 G->eraseFromParent();
991
992 Initializers[i] = ConstantStruct::get(
993 GlobalStructTy,
994 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
995 ConstantInt::get(IntptrTy, SizeInBytes),
996 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
997 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany086a4722013-03-18 08:05:29 +0000998 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000999 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001000 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001001
1002 // Populate the first and last globals declared in this TU.
Alexey Samsonovca825ea2013-03-26 13:05:41 +00001003 if (CheckInitOrder && GlobalHasDynamicInitializer)
1004 HasDynamicallyInitializedGlobals = true;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001005
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001006 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001007 }
1008
1009 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1010 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling55a1a592013-08-06 22:52:42 +00001011 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001012 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1013
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001014 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovca825ea2013-03-26 13:05:41 +00001015 if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1016 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001017 IRB.CreateCall2(AsanRegisterGlobals,
1018 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1019 ConstantInt::get(IntptrTy, n));
1020
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001021 // We also need to unregister globals at the end, e.g. when a shared library
1022 // gets closed.
1023 Function *AsanDtorFunction = Function::Create(
1024 FunctionType::get(Type::getVoidTy(*C), false),
1025 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1026 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1027 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001028 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1029 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1030 ConstantInt::get(IntptrTy, n));
1031 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1032
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001033 DEBUG(dbgs() << M);
1034 return true;
1035}
1036
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001037void AddressSanitizer::initializeCallbacks(Module &M) {
1038 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001039 // Create __asan_report* callbacks.
1040 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1041 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1042 AccessSizeIndex++) {
1043 // IsWrite and TypeSize are encoded in the function name.
1044 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1045 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +00001046 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +00001047 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1048 checkInterfaceFunction(M.getOrInsertFunction(
1049 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001050 }
1051 }
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +00001052 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1053 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1054 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1055 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001056
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001057 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1058 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +00001059 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1060 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1061 StringRef(""), StringRef(""),
1062 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001063}
1064
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001065void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001066 // Tell the values of mapping offset and scale to the run-time.
1067 GlobalValue *asan_mapping_offset =
1068 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1069 ConstantInt::get(IntptrTy, Mapping.Offset),
1070 kAsanMappingOffsetName);
1071 // Read the global, otherwise it may be optimized away.
1072 IRB.CreateLoad(asan_mapping_offset, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001073
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001074 GlobalValue *asan_mapping_scale =
1075 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1076 ConstantInt::get(IntptrTy, Mapping.Scale),
1077 kAsanMappingScaleName);
1078 // Read the global, otherwise it may be optimized away.
1079 IRB.CreateLoad(asan_mapping_scale, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001080}
1081
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001082// virtual
1083bool AddressSanitizer::doInitialization(Module &M) {
1084 // Initialize the private fields. No one has accessed them before.
1085 TD = getAnalysisIfAvailable<DataLayout>();
1086
1087 if (!TD)
1088 return false;
Alexey Samsonove39e1312013-08-12 11:46:09 +00001089 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001090 DynamicallyInitializedGlobals.Init(M);
1091
1092 C = &(M.getContext());
1093 LongSize = TD->getPointerSizeInBits();
1094 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001095
1096 AsanCtorFunction = Function::Create(
1097 FunctionType::get(Type::getVoidTy(*C), false),
1098 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1099 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1100 // call __asan_init in the module ctor.
1101 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1102 AsanInitFunction = checkInterfaceFunction(
1103 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1104 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1105 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001106
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001107 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001108 emitShadowMapping(M, IRB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001109
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001110 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001111 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001112}
1113
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001114bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1115 // For each NSObject descendant having a +load method, this method is invoked
1116 // by the ObjC runtime before any of the static constructors is called.
1117 // Therefore we need to instrument such methods with a call to __asan_init
1118 // at the beginning in order to initialize our runtime before any access to
1119 // the shadow memory.
1120 // We cannot just ignore these methods, because they may call other
1121 // instrumented functions.
1122 if (F.getName().find(" load]") != std::string::npos) {
1123 IRBuilder<> IRB(F.begin()->begin());
1124 IRB.CreateCall(AsanInitFunction);
1125 return true;
1126 }
1127 return false;
1128}
1129
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001130bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001131 if (BL->isIn(F)) return false;
1132 if (&F == AsanCtorFunction) return false;
Kostya Serebryany3797adb2013-03-18 07:33:49 +00001133 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001134 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001135 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001136
Kostya Serebryany8eec41f2013-02-26 06:58:09 +00001137 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001138 maybeInsertAsanInitAtFunctionEntry(F);
1139
Kostya Serebryany20985712013-06-26 09:18:17 +00001140 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendling67658342012-10-09 07:45:08 +00001141 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001142
1143 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1144 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001145
1146 // We want to instrument every address only once per basic block (unless there
1147 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001148 SmallSet<Value*, 16> TempsToInstrument;
1149 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001150 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany20985712013-06-26 09:18:17 +00001151 int NumAllocas = 0;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001152 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001153
1154 // Fill the set of memory operations to instrument.
1155 for (Function::iterator FI = F.begin(), FE = F.end();
1156 FI != FE; ++FI) {
1157 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001158 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001159 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1160 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001161 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001162 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001163 if (ClOpt && ClOptSameTemp) {
1164 if (!TempsToInstrument.insert(Addr))
1165 continue; // We've seen this temp in the current BB.
1166 }
1167 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1168 // ok, take it.
1169 } else {
Kostya Serebryany20985712013-06-26 09:18:17 +00001170 if (isa<AllocaInst>(BI))
1171 NumAllocas++;
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001172 CallSite CS(BI);
1173 if (CS) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001174 // A call inside BB.
1175 TempsToInstrument.clear();
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001176 if (CS.doesNotReturn())
1177 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001178 }
1179 continue;
1180 }
1181 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001182 NumInsnsPerBB++;
1183 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1184 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001185 }
1186 }
1187
Kostya Serebryany20985712013-06-26 09:18:17 +00001188 Function *UninstrumentedDuplicate = 0;
1189 bool LikelyToInstrument =
1190 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1191 if (ClKeepUninstrumented && LikelyToInstrument) {
1192 ValueToValueMapTy VMap;
1193 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1194 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1195 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1196 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1197 }
1198
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001199 // Instrument.
1200 int NumInstrumented = 0;
1201 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1202 Instruction *Inst = ToInstrument[i];
1203 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1204 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001205 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001206 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001207 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001208 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001209 }
1210 NumInstrumented++;
1211 }
1212
Alexey Samsonov59cca132012-12-25 12:04:36 +00001213 FunctionStackPoisoner FSP(F, *this);
1214 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001215
1216 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1217 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1218 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1219 Instruction *CI = NoReturnCalls[i];
1220 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001221 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001222 }
1223
Kostya Serebryany20985712013-06-26 09:18:17 +00001224 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1225 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1226
1227 if (ClKeepUninstrumented) {
1228 if (!res) {
1229 // No instrumentation is done, no need for the duplicate.
1230 if (UninstrumentedDuplicate)
1231 UninstrumentedDuplicate->eraseFromParent();
1232 } else {
1233 // The function was instrumented. We must have the duplicate.
1234 assert(UninstrumentedDuplicate);
1235 UninstrumentedDuplicate->setSection("NOASAN");
1236 assert(!F.hasSection());
1237 F.setSection("ASAN");
1238 }
1239 }
1240
1241 return res;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001242}
1243
1244static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1245 if (ShadowRedzoneSize == 1) return PoisonByte;
1246 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1247 if (ShadowRedzoneSize == 4)
1248 return (PoisonByte << 24) + (PoisonByte << 16) +
1249 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001250 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001251}
1252
1253static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1254 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001255 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001256 size_t ShadowGranularity,
1257 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001258 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001259 i+= ShadowGranularity, Shadow++) {
1260 if (i + ShadowGranularity <= Size) {
1261 *Shadow = 0; // fully addressable
1262 } else if (i >= Size) {
1263 *Shadow = Magic; // unaddressable
1264 } else {
1265 *Shadow = Size - i; // first Size-i bytes are addressable
1266 }
1267 }
1268}
1269
Alexey Samsonov59cca132012-12-25 12:04:36 +00001270// Workaround for bug 11395: we don't want to instrument stack in functions
1271// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1272// FIXME: remove once the bug 11395 is fixed.
1273bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1274 if (LongSize != 32) return false;
1275 CallInst *CI = dyn_cast<CallInst>(I);
1276 if (!CI || !CI->isInlineAsm()) return false;
1277 if (CI->getNumArgOperands() <= 5) return false;
1278 // We have inline assembly with quite a few arguments.
1279 return true;
1280}
1281
1282void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1283 IRBuilder<> IRB(*C);
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001284 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1285 std::string Suffix = itostr(i);
1286 AsanStackMallocFunc[i] = checkInterfaceFunction(
1287 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1288 IntptrTy, IntptrTy, NULL));
1289 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1290 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1291 IntptrTy, IntptrTy, NULL));
1292 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001293 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1294 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1295 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1296 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1297}
1298
1299void FunctionStackPoisoner::poisonRedZones(
Jakub Staszak4c710642013-08-09 20:53:48 +00001300 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB, Value *ShadowBase,
Alexey Samsonov59cca132012-12-25 12:04:36 +00001301 bool DoPoison) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001302 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001303 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1304 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1305 Type *RZPtrTy = PointerType::get(RZTy, 0);
1306
1307 Value *PoisonLeft = ConstantInt::get(RZTy,
1308 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1309 Value *PoisonMid = ConstantInt::get(RZTy,
1310 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1311 Value *PoisonRight = ConstantInt::get(RZTy,
1312 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1313
1314 // poison the first red zone.
1315 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1316
1317 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001318 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001319 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1320 AllocaInst *AI = AllocaVec[i];
1321 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1322 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001323 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001324 Value *Ptr = NULL;
1325
1326 Pos += AlignedSize;
1327
1328 assert(ShadowBase->getType() == IntptrTy);
1329 if (SizeInBytes < AlignedSize) {
1330 // Poison the partial redzone at right
1331 Ptr = IRB.CreateAdd(
1332 ShadowBase, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001333 (Pos >> Mapping.Scale) - ShadowRZSize));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001334 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001335 uint32_t Poison = 0;
1336 if (DoPoison) {
1337 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001338 RedzoneSize(),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001339 1ULL << Mapping.Scale,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001340 kAsanStackPartialRedzoneMagic);
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +00001341 Poison =
1342 ASan.TD->isLittleEndian()
1343 ? support::endian::byte_swap<uint32_t, support::little>(Poison)
1344 : support::endian::byte_swap<uint32_t, support::big>(Poison);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001345 }
1346 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1347 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1348 }
1349
1350 // Poison the full redzone at right.
1351 Ptr = IRB.CreateAdd(ShadowBase,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001352 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001353 bool LastAlloca = (i == AllocaVec.size() - 1);
1354 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001355 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1356
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001357 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001358 }
1359}
1360
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001361// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1362// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1363static int StackMallocSizeClass(uint64_t LocalStackSize) {
1364 assert(LocalStackSize <= kMaxStackMallocSize);
1365 uint64_t MaxSize = kMinStackMallocSize;
1366 for (int i = 0; ; i++, MaxSize *= 2)
1367 if (LocalStackSize <= MaxSize)
1368 return i;
1369 llvm_unreachable("impossible LocalStackSize");
1370}
1371
Kostya Serebryany671c3ba2013-09-17 12:14:50 +00001372// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1373// We can not use MemSet intrinsic because it may end up calling the actual
1374// memset. Size is a multiple of 8.
1375// Currently this generates 8-byte stores on x86_64; it may be better to
1376// generate wider stores.
1377void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1378 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1379 assert(!(Size % 8));
1380 assert(kAsanStackAfterReturnMagic == 0xf5);
1381 for (int i = 0; i < Size; i += 8) {
1382 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1383 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1384 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1385 }
1386}
1387
Alexey Samsonov59cca132012-12-25 12:04:36 +00001388void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001389 uint64_t LocalStackSize = TotalStackSize +
1390 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001391
Alexey Samsonov59cca132012-12-25 12:04:36 +00001392 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001393 && LocalStackSize <= kMaxStackMallocSize;
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001394 int StackMallocIdx = -1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001395
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001396 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001397 Instruction *InsBefore = AllocaVec[0];
1398 IRBuilder<> IRB(InsBefore);
1399
1400
1401 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1402 AllocaInst *MyAlloca =
1403 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001404 if (ClRealignStack && StackAlignment < RedzoneSize())
1405 StackAlignment = RedzoneSize();
1406 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001407 assert(MyAlloca->isStaticAlloca());
1408 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1409 Value *LocalStackBase = OrigStackBase;
1410
1411 if (DoStackMalloc) {
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001412 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1413 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1414 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc[StackMallocIdx],
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001415 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1416 }
1417
Kostya Serebryany30160562013-03-22 10:37:20 +00001418 // This string will be parsed by the run-time (DescribeAddressIfStack).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001419 SmallString<2048> StackDescriptionStorage;
1420 raw_svector_ostream StackDescription(StackDescriptionStorage);
Kostya Serebryany30160562013-03-22 10:37:20 +00001421 StackDescription << AllocaVec.size() << " ";
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001422
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001423 // Insert poison calls for lifetime intrinsics for alloca.
1424 bool HavePoisonedAllocas = false;
1425 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1426 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1427 IntrinsicInst *II = APC.InsBefore;
1428 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1429 assert(AI);
1430 IRBuilder<> IRB(II);
1431 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1432 HavePoisonedAllocas |= APC.DoPoison;
1433 }
1434
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001435 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001436 // Replace Alloca instructions with base+offset.
1437 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1438 AllocaInst *AI = AllocaVec[i];
1439 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1440 StringRef Name = AI->getName();
1441 StackDescription << Pos << " " << SizeInBytes << " "
1442 << Name.size() << " " << Name << " ";
1443 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001444 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001445 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001446 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001447 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001448 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001449 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001450 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001451 }
1452 assert(Pos == LocalStackSize);
1453
Kostya Serebryany30160562013-03-22 10:37:20 +00001454 // The left-most redzone has enough space for at least 4 pointers.
1455 // Write the Magic value to redzone[0].
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001456 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1457 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1458 BasePlus0);
Kostya Serebryany30160562013-03-22 10:37:20 +00001459 // Write the frame description constant to redzone[1].
1460 Value *BasePlus1 = IRB.CreateIntToPtr(
1461 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1462 IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001463 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001464 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001465 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1466 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001467 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryany30160562013-03-22 10:37:20 +00001468 // Write the PC to redzone[2].
1469 Value *BasePlus2 = IRB.CreateIntToPtr(
1470 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1471 2 * ASan.LongSize/8)),
1472 IntptrPtrTy);
1473 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001474
1475 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001476 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1477 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001478
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001479 // Unpoison the stack before all ret instructions.
1480 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1481 Instruction *Ret = RetVec[i];
1482 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001483 // Mark the current frame as retired.
1484 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1485 BasePlus0);
1486 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001487 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001488 if (DoStackMalloc) {
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001489 assert(StackMallocIdx >= 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001490 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany671c3ba2013-09-17 12:14:50 +00001491 if (StackMallocIdx <= 4) {
1492 // For small sizes inline the whole thing:
1493 // if LocalStackBase != OrigStackBase:
1494 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1495 // **SavedFlagPtr(LocalStackBase) = 0
1496 // FIXME: if LocalStackBase != OrigStackBase don't call poisonRedZones.
1497 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1498 TerminatorInst *PoisonTerm =
1499 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1500 IRBuilder<> IRBPoison(PoisonTerm);
1501 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1502 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1503 ClassSize >> Mapping.Scale);
1504 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1505 LocalStackBase,
1506 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1507 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1508 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1509 IRBPoison.CreateStore(
1510 Constant::getNullValue(IRBPoison.getInt8Ty()),
1511 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1512 } else {
1513 // For larger frames call __asan_stack_free_*.
1514 IRBRet.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1515 ConstantInt::get(IntptrTy, LocalStackSize),
1516 OrigStackBase);
1517 }
Alexey Samsonovf985f442012-12-04 01:34:23 +00001518 } else if (HavePoisonedAllocas) {
1519 // If we poisoned some allocas in llvm.lifetime analysis,
1520 // unpoison whole stack frame now.
1521 assert(LocalStackBase == OrigStackBase);
1522 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001523 }
1524 }
1525
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001526 // We are done. Remove the old unused alloca instructions.
1527 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1528 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001529}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001530
Alexey Samsonov59cca132012-12-25 12:04:36 +00001531void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak4c710642013-08-09 20:53:48 +00001532 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001533 // For now just insert the call to ASan runtime.
1534 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1535 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1536 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1537 : AsanUnpoisonStackMemoryFunc,
1538 AddrArg, SizeArg);
1539}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001540
1541// Handling llvm.lifetime intrinsics for a given %alloca:
1542// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1543// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1544// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1545// could be poisoned by previous llvm.lifetime.end instruction, as the
1546// variable may go in and out of scope several times, e.g. in loops).
1547// (3) if we poisoned at least one %alloca in a function,
1548// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001549
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001550AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1551 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1552 // We're intested only in allocas we can handle.
1553 return isInterestingAlloca(*AI) ? AI : 0;
1554 // See if we've already calculated (or started to calculate) alloca for a
1555 // given value.
1556 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1557 if (I != AllocaForValue.end())
1558 return I->second;
1559 // Store 0 while we're calculating alloca for value V to avoid
1560 // infinite recursion if the value references itself.
1561 AllocaForValue[V] = 0;
1562 AllocaInst *Res = 0;
1563 if (CastInst *CI = dyn_cast<CastInst>(V))
1564 Res = findAllocaForValue(CI->getOperand(0));
1565 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1566 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1567 Value *IncValue = PN->getIncomingValue(i);
1568 // Allow self-referencing phi-nodes.
1569 if (IncValue == PN) continue;
1570 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1571 // AI for incoming values should exist and should all be equal.
1572 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1573 return 0;
1574 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001575 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001576 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001577 if (Res != 0)
1578 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001579 return Res;
1580}