blob: 8f8af20cee182afb88e05dca3193a0c30f6fe7db [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 Serebryanyac04aba2013-09-18 14:07:14 +000091static const char *const kAsanOptionDetectUAR =
92 "__asan_option_detect_stack_use_after_return";
93
Kostya Serebryany671c3ba2013-09-17 12:14:50 +000094// These constants must match the definitions in the run-time library.
Kostya Serebryany800e03f2011-11-16 01:35:23 +000095static const int kAsanStackLeftRedzoneMagic = 0xf1;
96static const int kAsanStackMidRedzoneMagic = 0xf2;
97static const int kAsanStackRightRedzoneMagic = 0xf3;
98static const int kAsanStackPartialRedzoneMagic = 0xf4;
David Blaikie0b956502013-09-18 00:11:27 +000099#ifndef NDEBUG
Kostya Serebryany671c3ba2013-09-17 12:14:50 +0000100static const int kAsanStackAfterReturnMagic = 0xf5;
David Blaikie0b956502013-09-18 00:11:27 +0000101#endif
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000102
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000103// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
104static const size_t kNumberOfAccessSizes = 5;
105
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000106// Command-line flags.
107
108// This flag may need to be replaced with -f[no-]asan-reads.
109static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
110 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
111static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
112 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000113static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
114 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
115 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000116static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
117 cl::desc("use instrumentation with slow path for all accesses"),
118 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000119// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000120// in any given BB. Normally, this should be set to unlimited (INT_MAX),
121// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
122// set it to 10000.
123static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
124 cl::init(10000),
125 cl::desc("maximal number of instructions to instrument in any given BB"),
126 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000127// This flag may need to be replaced with -f[no]asan-stack.
128static cl::opt<bool> ClStack("asan-stack",
129 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
130// This flag may need to be replaced with -f[no]asan-use-after-return.
131static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
132 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
133// This flag may need to be replaced with -f[no]asan-globals.
134static cl::opt<bool> ClGlobals("asan-globals",
135 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000136static cl::opt<bool> ClInitializers("asan-initialization-order",
137 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000138static cl::opt<bool> ClMemIntrin("asan-memintrin",
139 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Kostya Serebryany6c554122012-12-04 06:14:01 +0000140static cl::opt<bool> ClRealignStack("asan-realign-stack",
141 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000142static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
143 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000144 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000145
Kostya Serebryany20985712013-06-26 09:18:17 +0000146// This is an experimental feature that will allow to choose between
147// instrumented and non-instrumented code at link-time.
148// If this option is on, just before instrumenting a function we create its
149// clone; if the function is not changed by asan the clone is deleted.
150// If we end up with a clone, we put the instrumented function into a section
151// called "ASAN" and the uninstrumented function into a section called "NOASAN".
152//
153// This is still a prototype, we need to figure out a way to keep two copies of
154// a function so that the linker can easily choose one of them.
155static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
156 cl::desc("Keep uninstrumented copies of functions"),
157 cl::Hidden, cl::init(false));
158
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000159// These flags allow to change the shadow mapping.
160// The shadow mapping looks like
161// Shadow = (Mem >> scale) + (1 << offset_log)
162static cl::opt<int> ClMappingScale("asan-mapping-scale",
163 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
164static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
165 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
Kostya Serebryany117de482013-02-11 14:36:01 +0000166static cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
167 cl::desc("Use short immediate constant as the mapping offset for 64bit"),
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000168 cl::Hidden, cl::init(true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000169
170// Optimization flags. Not user visible, used mostly for testing
171// and benchmarking the tool.
172static cl::opt<bool> ClOpt("asan-opt",
173 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
174static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
175 cl::desc("Instrument the same temp just once"), cl::Hidden,
176 cl::init(true));
177static cl::opt<bool> ClOptGlobals("asan-opt-globals",
178 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
179
Alexey Samsonovee548272012-11-29 18:14:24 +0000180static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
181 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
182 cl::Hidden, cl::init(false));
183
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000184// Debug flags.
185static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
186 cl::init(0));
187static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
188 cl::Hidden, cl::init(0));
189static cl::opt<std::string> ClDebugFunc("asan-debug-func",
190 cl::Hidden, cl::desc("Debug func"));
191static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
192 cl::Hidden, cl::init(-1));
193static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
194 cl::Hidden, cl::init(-1));
195
196namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000197/// A set of dynamically initialized globals extracted from metadata.
198class SetOfDynamicallyInitializedGlobals {
199 public:
200 void Init(Module& M) {
201 // Clang generates metadata identifying all dynamically initialized globals.
202 NamedMDNode *DynamicGlobals =
203 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
204 if (!DynamicGlobals)
205 return;
206 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
207 MDNode *MDN = DynamicGlobals->getOperand(i);
208 assert(MDN->getNumOperands() == 1);
209 Value *VG = MDN->getOperand(0);
210 // The optimizer may optimize away a global entirely, in which case we
211 // cannot instrument access to it.
212 if (!VG)
213 continue;
214 DynInitGlobals.insert(cast<GlobalVariable>(VG));
215 }
216 }
217 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
218 private:
219 SmallSet<GlobalValue*, 32> DynInitGlobals;
220};
221
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000222/// This struct defines the shadow mapping using the rule:
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000223/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000224struct ShadowMapping {
225 int Scale;
226 uint64_t Offset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000227 bool OrShadowOffset;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000228};
229
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000230static ShadowMapping getShadowMapping(const Module &M, int LongSize,
231 bool ZeroBaseShadow) {
232 llvm::Triple TargetTriple(M.getTargetTriple());
233 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000234 bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
Bill Schmidtf38cc382013-07-26 01:35:43 +0000235 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
236 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000237 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +0000238 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
239 TargetTriple.getArch() == llvm::Triple::mipsel;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000240
241 ShadowMapping Mapping;
242
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000243 // OR-ing shadow offset if more efficient (at least on x86),
244 // but on ppc64 we have to use add since the shadow offset is not neccesary
245 // 1/8-th of the address space.
Kostya Serebryany117de482013-02-11 14:36:01 +0000246 Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000247
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000248 Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +0000249 (LongSize == 32 ?
250 (IsMIPS32 ? kMIPS32_ShadowOffset32 : kDefaultShadowOffset32) :
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000251 IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
Alexander Potapenkoc8a196a2013-02-12 12:41:12 +0000252 if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
Kostya Serebryany0bc55d52013-02-12 11:11:02 +0000253 assert(LongSize == 64);
Kostya Serebryany117de482013-02-11 14:36:01 +0000254 Mapping.Offset = kDefaultShort64bitShadowOffset;
Kostya Serebryany39f02942013-02-13 05:14:12 +0000255 }
256 if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000257 // Zero offset log is the special case.
258 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
259 }
260
261 Mapping.Scale = kDefaultShadowScale;
262 if (ClMappingScale) {
263 Mapping.Scale = ClMappingScale;
264 }
265
266 return Mapping;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000267}
268
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000269static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000270 // Redzone used for stack and globals is at least 32 bytes.
271 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000272 return std::max(32U, 1U << MappingScale);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000273}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000274
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000275/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000276struct AddressSanitizer : public FunctionPass {
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000277 AddressSanitizer(bool CheckInitOrder = true,
Alexey Samsonovee548272012-11-29 18:14:24 +0000278 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000279 bool CheckLifetime = false,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000280 StringRef BlacklistFile = StringRef(),
281 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000282 : FunctionPass(ID),
283 CheckInitOrder(CheckInitOrder || ClInitializers),
284 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000285 CheckLifetime(CheckLifetime || ClCheckLifetime),
286 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000287 : BlacklistFile),
288 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000289 virtual const char *getPassName() const {
290 return "AddressSanitizerFunctionPass";
291 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000292 void instrumentMop(Instruction *I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000293 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
294 Value *Addr, uint32_t TypeSize, bool IsWrite,
295 Value *SizeArgument);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000296 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
297 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000298 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000299 bool IsWrite, size_t AccessSizeIndex,
300 Value *SizeArgument);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000301 bool instrumentMemIntrinsic(MemIntrinsic *MI);
302 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000303 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000304 Instruction *InsertBefore, bool IsWrite);
305 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000306 bool runOnFunction(Function &F);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000307 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000308 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000309 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000310 static char ID; // Pass identification, replacement for typeid
311
312 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000313 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000314
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000315 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000316 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000317 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000318
Alexey Samsonovee548272012-11-29 18:14:24 +0000319 bool CheckInitOrder;
320 bool CheckUseAfterReturn;
321 bool CheckLifetime;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000322 SmallString<64> BlacklistFile;
323 bool ZeroBaseShadow;
324
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000325 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000326 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000327 int LongSize;
328 Type *IntptrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000329 ShadowMapping Mapping;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000330 Function *AsanCtorFunction;
331 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000332 Function *AsanHandleNoReturnFunc;
Peter Collingbourne405515d2013-07-09 22:02:49 +0000333 OwningPtr<SpecialCaseList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000334 // This array is indexed by AccessIsWrite and log2(AccessSize).
335 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000336 // This array is indexed by AccessIsWrite.
337 Function *AsanErrorCallbackSized[2];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000338 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000339 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000340
341 friend struct FunctionStackPoisoner;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000342};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000343
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000344class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000345 public:
Alexey Samsonovb4ba5e62013-03-14 12:38:58 +0000346 AddressSanitizerModule(bool CheckInitOrder = true,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000347 StringRef BlacklistFile = StringRef(),
348 bool ZeroBaseShadow = false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000349 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000350 CheckInitOrder(CheckInitOrder || ClInitializers),
351 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000352 : BlacklistFile),
353 ZeroBaseShadow(ZeroBaseShadow) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000354 bool runOnModule(Module &M);
355 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000356 virtual const char *getPassName() const {
357 return "AddressSanitizerModule";
358 }
Alexey Samsonovf985f442012-12-04 01:34:23 +0000359
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000360 private:
Alexey Samsonov46848582012-12-25 12:28:20 +0000361 void initializeCallbacks(Module &M);
362
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000363 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000364 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000365 size_t RedzoneSize() const {
366 return RedzoneSizeForScale(Mapping.Scale);
367 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000368
Alexey Samsonovee548272012-11-29 18:14:24 +0000369 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000370 SmallString<64> BlacklistFile;
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000371 bool ZeroBaseShadow;
372
Peter Collingbourne405515d2013-07-09 22:02:49 +0000373 OwningPtr<SpecialCaseList> BL;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000374 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
375 Type *IntptrTy;
376 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000377 DataLayout *TD;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000378 ShadowMapping Mapping;
Alexey Samsonov46848582012-12-25 12:28:20 +0000379 Function *AsanPoisonGlobals;
380 Function *AsanUnpoisonGlobals;
381 Function *AsanRegisterGlobals;
382 Function *AsanUnregisterGlobals;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000383};
384
Alexey Samsonov59cca132012-12-25 12:04:36 +0000385// Stack poisoning does not play well with exception handling.
386// When an exception is thrown, we essentially bypass the code
387// that unpoisones the stack. This is why the run-time library has
388// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
389// stack in the interceptor. This however does not work inside the
390// actual function which catches the exception. Most likely because the
391// compiler hoists the load of the shadow value somewhere too high.
392// This causes asan to report a non-existing bug on 453.povray.
393// It sounds like an LLVM bug.
394struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
395 Function &F;
396 AddressSanitizer &ASan;
397 DIBuilder DIB;
398 LLVMContext *C;
399 Type *IntptrTy;
400 Type *IntptrPtrTy;
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000401 ShadowMapping Mapping;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000402
403 SmallVector<AllocaInst*, 16> AllocaVec;
404 SmallVector<Instruction*, 8> RetVec;
405 uint64_t TotalStackSize;
406 unsigned StackAlignment;
407
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +0000408 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
409 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov59cca132012-12-25 12:04:36 +0000410 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
411
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000412 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
413 struct AllocaPoisonCall {
414 IntrinsicInst *InsBefore;
415 uint64_t Size;
416 bool DoPoison;
417 };
418 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
419
420 // Maps Value to an AllocaInst from which the Value is originated.
421 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
422 AllocaForValueMapTy AllocaForValue;
423
Alexey Samsonov59cca132012-12-25 12:04:36 +0000424 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
425 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
426 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000427 Mapping(ASan.Mapping),
428 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov59cca132012-12-25 12:04:36 +0000429
430 bool runOnFunction() {
431 if (!ClStack) return false;
432 // Collect alloca, ret, lifetime instructions etc.
433 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
434 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
435 BasicBlock *BB = *DI;
436 visit(*BB);
437 }
438 if (AllocaVec.empty()) return false;
439
440 initializeCallbacks(*F.getParent());
441
442 poisonStack();
443
444 if (ClDebugStack) {
445 DEBUG(dbgs() << F);
446 }
447 return true;
448 }
449
450 // Finds all static Alloca instructions and puts
451 // poisoned red zones around all of them.
452 // Then unpoison everything back before the function returns.
453 void poisonStack();
454
455 // ----------------------- Visitors.
456 /// \brief Collect all Ret instructions.
457 void visitReturnInst(ReturnInst &RI) {
458 RetVec.push_back(&RI);
459 }
460
461 /// \brief Collect Alloca instructions we want (and can) handle.
462 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000463 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov59cca132012-12-25 12:04:36 +0000464
465 StackAlignment = std::max(StackAlignment, AI.getAlignment());
466 AllocaVec.push_back(&AI);
Kostya Serebryanyd4429212013-06-26 09:49:52 +0000467 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000468 TotalStackSize += AlignedSize;
469 }
470
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000471 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
472 /// errors.
473 void visitIntrinsicInst(IntrinsicInst &II) {
474 if (!ASan.CheckLifetime) return;
475 Intrinsic::ID ID = II.getIntrinsicID();
476 if (ID != Intrinsic::lifetime_start &&
477 ID != Intrinsic::lifetime_end)
478 return;
479 // Found lifetime intrinsic, add ASan instrumentation if necessary.
480 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
481 // If size argument is undefined, don't do anything.
482 if (Size->isMinusOne()) return;
483 // Check that size doesn't saturate uint64_t and can
484 // be stored in IntptrTy.
485 const uint64_t SizeValue = Size->getValue().getLimitedValue();
486 if (SizeValue == ~0ULL ||
487 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
488 return;
489 // Find alloca instruction that corresponds to llvm.lifetime argument.
490 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
491 if (!AI) return;
492 bool DoPoison = (ID == Intrinsic::lifetime_end);
493 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
494 AllocaPoisonCallVec.push_back(APC);
495 }
496
Alexey Samsonov59cca132012-12-25 12:04:36 +0000497 // ---------------------- Helpers.
498 void initializeCallbacks(Module &M);
499
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000500 // Check if we want (and can) handle this alloca.
Jakub Staszak4c710642013-08-09 20:53:48 +0000501 bool isInterestingAlloca(AllocaInst &AI) const {
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000502 return (!AI.isArrayAllocation() &&
503 AI.isStaticAlloca() &&
Kostya Serebryanyd4429212013-06-26 09:49:52 +0000504 AI.getAlignment() <= RedzoneSize() &&
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000505 AI.getAllocatedType()->isSized());
506 }
507
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000508 size_t RedzoneSize() const {
509 return RedzoneSizeForScale(Mapping.Scale);
510 }
Jakub Staszak4c710642013-08-09 20:53:48 +0000511 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Alexey Samsonov59cca132012-12-25 12:04:36 +0000512 Type *Ty = AI->getAllocatedType();
513 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
514 return SizeInBytes;
515 }
Jakub Staszak4c710642013-08-09 20:53:48 +0000516 uint64_t getAlignedSize(uint64_t SizeInBytes) const {
Alexey Samsonov59cca132012-12-25 12:04:36 +0000517 size_t RZ = RedzoneSize();
518 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
519 }
Jakub Staszak4c710642013-08-09 20:53:48 +0000520 uint64_t getAlignedAllocaSize(AllocaInst *AI) const {
Alexey Samsonov59cca132012-12-25 12:04:36 +0000521 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
522 return getAlignedSize(SizeInBytes);
523 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +0000524 /// Finds alloca where the value comes from.
525 AllocaInst *findAllocaForValue(Value *V);
Jakub Staszak4c710642013-08-09 20:53:48 +0000526 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB,
Alexey Samsonov59cca132012-12-25 12:04:36 +0000527 Value *ShadowBase, bool DoPoison);
Jakub Staszak4c710642013-08-09 20:53:48 +0000528 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryany671c3ba2013-09-17 12:14:50 +0000529
530 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
531 int Size);
Alexey Samsonov59cca132012-12-25 12:04:36 +0000532};
533
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000534} // namespace
535
536char AddressSanitizer::ID = 0;
537INITIALIZE_PASS(AddressSanitizer, "asan",
538 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
539 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000540FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000541 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000542 StringRef BlacklistFile, bool ZeroBaseShadow) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000543 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000544 CheckLifetime, BlacklistFile, ZeroBaseShadow);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000545}
546
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000547char AddressSanitizerModule::ID = 0;
548INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
549 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
550 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000551ModulePass *llvm::createAddressSanitizerModulePass(
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000552 bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
553 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
554 ZeroBaseShadow);
Alexander Potapenko25878042012-01-23 11:22:43 +0000555}
556
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000557static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerc6af2432013-05-24 22:23:49 +0000558 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000559 assert(Res < kNumberOfAccessSizes);
560 return Res;
561}
562
Bill Wendling55a1a592013-08-06 22:52:42 +0000563// \brief Create a constant for Str so that we can pass it to the run-time lib.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000564static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000565 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany51116272013-03-18 09:38:39 +0000566 GlobalVariable *GV = new GlobalVariable(M, StrConst->getType(), true,
Bill Wendling55a1a592013-08-06 22:52:42 +0000567 GlobalValue::InternalLinkage, StrConst,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000568 kAsanGenPrefix);
Kostya Serebryany51116272013-03-18 09:38:39 +0000569 GV->setUnnamedAddr(true); // Ok to merge these.
570 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
571 return GV;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000572}
573
574static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
575 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000576}
577
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000578Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
579 // Shadow >> scale
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000580 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
581 if (Mapping.Offset == 0)
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000582 return Shadow;
583 // (Shadow >> scale) | offset
Kostya Serebryany48a615f2013-01-23 12:54:55 +0000584 if (Mapping.OrShadowOffset)
585 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
586 else
587 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000588}
589
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000590void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000591 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000592 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000593 IRBuilder<> IRB(InsertBefore);
594 if (Size->getType() != IntptrTy)
595 Size = IRB.CreateIntCast(Size, IntptrTy, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000596 // Check the first byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000597 instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000598 // Check the last byte.
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000599 IRB.SetInsertPoint(InsertBefore);
600 Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
601 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
602 Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
603 instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000604}
605
606// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000607bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000608 Value *Dst = MI->getDest();
609 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000610 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000611 Value *Length = MI->getLength();
612
613 Constant *ConstLength = dyn_cast<Constant>(Length);
614 Instruction *InsertBefore = MI;
615 if (ConstLength) {
616 if (ConstLength->isNullValue()) return false;
617 } else {
618 // The size is not a constant so it could be zero -- check at run-time.
619 IRBuilder<> IRB(InsertBefore);
620
621 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000622 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000623 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000624 }
625
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000626 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000627 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000628 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000629 return true;
630}
631
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000632// If I is an interesting memory access, return the PointerOperand
633// and set IsWrite. Otherwise return NULL.
634static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000635 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000636 if (!ClInstrumentReads) return NULL;
637 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000638 return LI->getPointerOperand();
639 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000640 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
641 if (!ClInstrumentWrites) return NULL;
642 *IsWrite = true;
643 return SI->getPointerOperand();
644 }
645 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
646 if (!ClInstrumentAtomics) return NULL;
647 *IsWrite = true;
648 return RMW->getPointerOperand();
649 }
650 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
651 if (!ClInstrumentAtomics) return NULL;
652 *IsWrite = true;
653 return XCHG->getPointerOperand();
654 }
655 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000656}
657
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000658void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000659 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000660 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
661 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000662 if (ClOpt && ClOptGlobals) {
663 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
664 // If initialization order checking is disabled, a simple access to a
665 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000666 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000667 return;
668 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000669 // have to instrument it. However, if a global does not have initailizer
670 // at all, we assume it has dynamic initializer (in other TU).
671 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000672 return;
673 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000674 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000675
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000676 Type *OrigPtrTy = Addr->getType();
677 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
678
679 assert(OrigTy->isSized());
Kostya Serebryany605ff662013-02-18 13:47:02 +0000680 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000681
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000682 assert((TypeSize % 8) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000683
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000684 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
685 if (TypeSize == 8 || TypeSize == 16 ||
686 TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
687 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
688 // Instrument unusual size (but still multiple of 8).
689 // We can not do it with a single check, so we do 1-byte check for the first
690 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
691 // to report the actual access size.
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000692 IRBuilder<> IRB(I);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000693 Value *LastByte = IRB.CreateIntToPtr(
694 IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
695 ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
696 OrigPtrTy);
697 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
698 instrumentAddress(I, I, Addr, 8, IsWrite, Size);
699 instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000700}
701
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000702// Validate the result of Module::getOrInsertFunction called for an interface
703// function of AddressSanitizer. If the instrumented module defines a function
704// with the same name, their prototypes must match, otherwise
705// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000706static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000707 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
708 FuncOrBitcast->dump();
709 report_fatal_error("trying to redefine an AddressSanitizer "
710 "interface function");
711}
712
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000713Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000714 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000715 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000716 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000717 CallInst *Call = SizeArgument
718 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
719 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
720
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000721 // We don't do Call->setDoesNotReturn() because the BB already has
722 // UnreachableInst at the end.
723 // This EmptyAsm is required to avoid callback merge.
724 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000725 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000726}
727
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000728Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000729 Value *ShadowValue,
730 uint32_t TypeSize) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000731 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000732 // Addr & (Granularity - 1)
733 Value *LastAccessedByte = IRB.CreateAnd(
734 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
735 // (Addr & (Granularity - 1)) + size - 1
736 if (TypeSize / 8 > 1)
737 LastAccessedByte = IRB.CreateAdd(
738 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
739 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
740 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000741 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000742 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
743 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
744}
745
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000746void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000747 Instruction *InsertBefore,
748 Value *Addr, uint32_t TypeSize,
749 bool IsWrite, Value *SizeArgument) {
750 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000751 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
752
753 Type *ShadowTy = IntegerType::get(
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000754 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000755 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
756 Value *ShadowPtr = memToShadow(AddrLong, IRB);
757 Value *CmpVal = Constant::getNullValue(ShadowTy);
758 Value *ShadowValue = IRB.CreateLoad(
759 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
760
761 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000762 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000763 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000764 TerminatorInst *CrashTerm = 0;
765
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000766 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000767 TerminatorInst *CheckTerm =
768 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000769 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000770 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000771 IRB.SetInsertPoint(CheckTerm);
772 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000773 BasicBlock *CrashBlock =
774 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000775 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000776 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
777 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000778 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000779 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000780 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000781
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +0000782 Instruction *Crash = generateCrashCode(
783 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000784 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000785}
786
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000787void AddressSanitizerModule::createInitializerPoisonCalls(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000788 Module &M, GlobalValue *ModuleName) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000789 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
790 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
791 // If that function is not present, this TU contains no globals, or they have
792 // all been optimized away
793 if (!GlobalInit)
794 return;
795
796 // Set up the arguments to our poison/unpoison functions.
797 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
798
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000799 // Add a call to poison all external globals before the given function starts.
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000800 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
801 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000802
803 // Add calls to unpoison all globals before each return instruction.
804 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
805 I != E; ++I) {
806 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
807 CallInst::Create(AsanUnpoisonGlobals, "", RI);
808 }
809 }
810}
811
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000812bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000813 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000814 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000815
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000816 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000817 if (!Ty->isSized()) return false;
818 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000819 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000820 // Touch only those globals that will not be defined in other modules.
821 // Don't handle ODR type linkages since other modules may be built w/o asan.
822 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
823 G->getLinkage() != GlobalVariable::PrivateLinkage &&
824 G->getLinkage() != GlobalVariable::InternalLinkage)
825 return false;
826 // Two problems with thread-locals:
827 // - The address of the main thread's copy can't be computed at link-time.
828 // - Need to poison all copies, not just the main thread's one.
829 if (G->isThreadLocal())
830 return false;
831 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000832 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000833
834 // Ignore all the globals with the names starting with "\01L_OBJC_".
835 // Many of those are put into the .cstring section. The linker compresses
836 // that section by removing the spare \0s after the string terminator, so
837 // our redzones get broken.
838 if ((G->getName().find("\01L_OBJC_") == 0) ||
839 (G->getName().find("\01l_OBJC_") == 0)) {
840 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
841 return false;
842 }
843
844 if (G->hasSection()) {
845 StringRef Section(G->getSection());
846 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
847 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
848 // them.
849 if ((Section.find("__OBJC,") == 0) ||
850 (Section.find("__DATA, __objc_") == 0)) {
851 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
852 return false;
853 }
854 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
855 // Constant CFString instances are compiled in the following way:
856 // -- the string buffer is emitted into
857 // __TEXT,__cstring,cstring_literals
858 // -- the constant NSConstantString structure referencing that buffer
859 // is placed into __DATA,__cfstring
860 // Therefore there's no point in placing redzones into __DATA,__cfstring.
861 // Moreover, it causes the linker to crash on OS X 10.7
862 if (Section.find("__DATA,__cfstring") == 0) {
863 DEBUG(dbgs() << "Ignoring CFString: " << *G);
864 return false;
865 }
866 }
867
868 return true;
869}
870
Alexey Samsonov46848582012-12-25 12:28:20 +0000871void AddressSanitizerModule::initializeCallbacks(Module &M) {
872 IRBuilder<> IRB(*C);
873 // Declare our poisoning and unpoisoning functions.
874 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000875 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
Alexey Samsonov46848582012-12-25 12:28:20 +0000876 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
877 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
878 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
879 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
880 // Declare functions that register/unregister globals.
881 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
882 kAsanRegisterGlobalsName, IRB.getVoidTy(),
883 IntptrTy, IntptrTy, NULL));
884 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
885 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
886 kAsanUnregisterGlobalsName,
887 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
888 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
889}
890
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000891// This function replaces all global variables with new variables that have
892// trailing redzones. It also creates a function that poisons
893// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000894bool AddressSanitizerModule::runOnModule(Module &M) {
895 if (!ClGlobals) return false;
896 TD = getAnalysisIfAvailable<DataLayout>();
897 if (!TD)
898 return false;
Alexey Samsonove39e1312013-08-12 11:46:09 +0000899 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000900 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000901 C = &(M.getContext());
Alexey Samsonov19cd7e92013-01-16 13:23:28 +0000902 int LongSize = TD->getPointerSizeInBits();
903 IntptrTy = Type::getIntNTy(*C, LongSize);
Alexey Samsonov11af9a82013-01-17 11:12:32 +0000904 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov46848582012-12-25 12:28:20 +0000905 initializeCallbacks(M);
906 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000907
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000908 SmallVector<GlobalVariable *, 16> GlobalsToChange;
909
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000910 for (Module::GlobalListType::iterator G = M.global_begin(),
911 E = M.global_end(); G != E; ++G) {
912 if (ShouldInstrumentGlobal(G))
913 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000914 }
915
916 size_t n = GlobalsToChange.size();
917 if (n == 0) return false;
918
919 // A global is described by a structure
920 // size_t beg;
921 // size_t size;
922 // size_t size_with_redzone;
923 // const char *name;
Kostya Serebryany086a4722013-03-18 08:05:29 +0000924 // const char *module_name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000925 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000926 // We initialize an array of such structures and pass it to a run-time call.
927 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000928 IntptrTy, IntptrTy,
Kostya Serebryany086a4722013-03-18 08:05:29 +0000929 IntptrTy, IntptrTy, NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000930 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000931
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000932
933 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
934 assert(CtorFunc);
935 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000936
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000937 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000938
Kostya Serebryany086a4722013-03-18 08:05:29 +0000939 GlobalVariable *ModuleName = createPrivateGlobalForString(
940 M, M.getModuleIdentifier());
Alexey Samsonovca825ea2013-03-26 13:05:41 +0000941 // We shouldn't merge same module names, as this string serves as unique
942 // module ID in runtime.
943 ModuleName->setUnnamedAddr(false);
Kostya Serebryany086a4722013-03-18 08:05:29 +0000944
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000945 for (size_t i = 0; i < n; i++) {
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000946 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000947 GlobalVariable *G = GlobalsToChange[i];
948 PointerType *PtrTy = cast<PointerType>(G->getType());
949 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000950 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000951 uint64_t MinRZ = RedzoneSize();
Kostya Serebryany63f08462013-01-24 10:35:40 +0000952 // MinRZ <= RZ <= kMaxGlobalRedzone
953 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryany29f975f2013-01-24 10:43:50 +0000954 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany63f08462013-01-24 10:35:40 +0000955 std::min(kMaxGlobalRedzone,
956 (SizeInBytes / MinRZ / 4) * MinRZ));
957 uint64_t RightRedzoneSize = RZ;
958 // Round up to MinRZ
959 if (SizeInBytes % MinRZ)
960 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
961 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000962 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000963 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000964 bool GlobalHasDynamicInitializer =
965 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000966 // Don't check initialization order if this global is blacklisted.
Peter Collingbourne46e11c42013-07-09 22:03:17 +0000967 GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000968
969 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
970 Constant *NewInitializer = ConstantStruct::get(
971 NewTy, G->getInitializer(),
972 Constant::getNullValue(RightRedZoneTy), NULL);
973
Kostya Serebryany086a4722013-03-18 08:05:29 +0000974 GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000975
976 // Create a new global variable with enough space for a redzone.
Bill Wendling55a1a592013-08-06 22:52:42 +0000977 GlobalValue::LinkageTypes Linkage = G->getLinkage();
978 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
979 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000980 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling55a1a592013-08-06 22:52:42 +0000981 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000982 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000983 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany63f08462013-01-24 10:35:40 +0000984 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000985
986 Value *Indices2[2];
987 Indices2[0] = IRB.getInt32(0);
988 Indices2[1] = IRB.getInt32(0);
989
990 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000991 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000992 NewGlobal->takeName(G);
993 G->eraseFromParent();
994
995 Initializers[i] = ConstantStruct::get(
996 GlobalStructTy,
997 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
998 ConstantInt::get(IntptrTy, SizeInBytes),
999 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1000 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany086a4722013-03-18 08:05:29 +00001001 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001002 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001003 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001004
1005 // Populate the first and last globals declared in this TU.
Alexey Samsonovca825ea2013-03-26 13:05:41 +00001006 if (CheckInitOrder && GlobalHasDynamicInitializer)
1007 HasDynamicallyInitializedGlobals = true;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001008
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001009 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001010 }
1011
1012 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1013 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling55a1a592013-08-06 22:52:42 +00001014 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001015 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1016
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +00001017 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovca825ea2013-03-26 13:05:41 +00001018 if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1019 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001020 IRB.CreateCall2(AsanRegisterGlobals,
1021 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1022 ConstantInt::get(IntptrTy, n));
1023
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001024 // We also need to unregister globals at the end, e.g. when a shared library
1025 // gets closed.
1026 Function *AsanDtorFunction = Function::Create(
1027 FunctionType::get(Type::getVoidTy(*C), false),
1028 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1029 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1030 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001031 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1032 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1033 ConstantInt::get(IntptrTy, n));
1034 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1035
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001036 DEBUG(dbgs() << M);
1037 return true;
1038}
1039
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001040void AddressSanitizer::initializeCallbacks(Module &M) {
1041 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001042 // Create __asan_report* callbacks.
1043 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1044 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1045 AccessSizeIndex++) {
1046 // IsWrite and TypeSize are encoded in the function name.
1047 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1048 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +00001049 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +00001050 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1051 checkInterfaceFunction(M.getOrInsertFunction(
1052 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001053 }
1054 }
Kostya Serebryany6ecccdb2013-02-19 11:29:21 +00001055 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1056 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1057 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1058 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001059
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001060 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1061 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf7b08222012-07-20 09:54:50 +00001062 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1063 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1064 StringRef(""), StringRef(""),
1065 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001066}
1067
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001068void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001069 // Tell the values of mapping offset and scale to the run-time.
1070 GlobalValue *asan_mapping_offset =
1071 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1072 ConstantInt::get(IntptrTy, Mapping.Offset),
1073 kAsanMappingOffsetName);
1074 // Read the global, otherwise it may be optimized away.
1075 IRB.CreateLoad(asan_mapping_offset, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001076
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001077 GlobalValue *asan_mapping_scale =
1078 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1079 ConstantInt::get(IntptrTy, Mapping.Scale),
1080 kAsanMappingScaleName);
1081 // Read the global, otherwise it may be optimized away.
1082 IRB.CreateLoad(asan_mapping_scale, true);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001083}
1084
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001085// virtual
1086bool AddressSanitizer::doInitialization(Module &M) {
1087 // Initialize the private fields. No one has accessed them before.
1088 TD = getAnalysisIfAvailable<DataLayout>();
1089
1090 if (!TD)
1091 return false;
Alexey Samsonove39e1312013-08-12 11:46:09 +00001092 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001093 DynamicallyInitializedGlobals.Init(M);
1094
1095 C = &(M.getContext());
1096 LongSize = TD->getPointerSizeInBits();
1097 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001098
1099 AsanCtorFunction = Function::Create(
1100 FunctionType::get(Type::getVoidTy(*C), false),
1101 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1102 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1103 // call __asan_init in the module ctor.
1104 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1105 AsanInitFunction = checkInterfaceFunction(
1106 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1107 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1108 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +00001109
Alexey Samsonov11af9a82013-01-17 11:12:32 +00001110 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001111 emitShadowMapping(M, IRB);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001112
Kostya Serebryany7bcfc992011-12-15 21:59:03 +00001113 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001114 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001115}
1116
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001117bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1118 // For each NSObject descendant having a +load method, this method is invoked
1119 // by the ObjC runtime before any of the static constructors is called.
1120 // Therefore we need to instrument such methods with a call to __asan_init
1121 // at the beginning in order to initialize our runtime before any access to
1122 // the shadow memory.
1123 // We cannot just ignore these methods, because they may call other
1124 // instrumented functions.
1125 if (F.getName().find(" load]") != std::string::npos) {
1126 IRBuilder<> IRB(F.begin()->begin());
1127 IRB.CreateCall(AsanInitFunction);
1128 return true;
1129 }
1130 return false;
1131}
1132
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001133bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001134 if (BL->isIn(F)) return false;
1135 if (&F == AsanCtorFunction) return false;
Kostya Serebryany3797adb2013-03-18 07:33:49 +00001136 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +00001137 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +00001138 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001139
Kostya Serebryany8eec41f2013-02-26 06:58:09 +00001140 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryanya1a8a322012-01-30 23:50:10 +00001141 maybeInsertAsanInitAtFunctionEntry(F);
1142
Kostya Serebryany20985712013-06-26 09:18:17 +00001143 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendling67658342012-10-09 07:45:08 +00001144 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001145
1146 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1147 return false;
Bill Wendling67658342012-10-09 07:45:08 +00001148
1149 // We want to instrument every address only once per basic block (unless there
1150 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001151 SmallSet<Value*, 16> TempsToInstrument;
1152 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001153 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany20985712013-06-26 09:18:17 +00001154 int NumAllocas = 0;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001155 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001156
1157 // Fill the set of memory operations to instrument.
1158 for (Function::iterator FI = F.begin(), FE = F.end();
1159 FI != FE; ++FI) {
1160 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001161 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001162 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1163 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +00001164 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001165 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001166 if (ClOpt && ClOptSameTemp) {
1167 if (!TempsToInstrument.insert(Addr))
1168 continue; // We've seen this temp in the current BB.
1169 }
1170 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1171 // ok, take it.
1172 } else {
Kostya Serebryany20985712013-06-26 09:18:17 +00001173 if (isa<AllocaInst>(BI))
1174 NumAllocas++;
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001175 CallSite CS(BI);
1176 if (CS) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001177 // A call inside BB.
1178 TempsToInstrument.clear();
Kostya Serebryany1479c9b2013-02-20 12:35:15 +00001179 if (CS.doesNotReturn())
1180 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001181 }
1182 continue;
1183 }
1184 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +00001185 NumInsnsPerBB++;
1186 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1187 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001188 }
1189 }
1190
Kostya Serebryany20985712013-06-26 09:18:17 +00001191 Function *UninstrumentedDuplicate = 0;
1192 bool LikelyToInstrument =
1193 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1194 if (ClKeepUninstrumented && LikelyToInstrument) {
1195 ValueToValueMapTy VMap;
1196 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1197 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1198 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1199 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1200 }
1201
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001202 // Instrument.
1203 int NumInstrumented = 0;
1204 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1205 Instruction *Inst = ToInstrument[i];
1206 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1207 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +00001208 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001209 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001210 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001211 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001212 }
1213 NumInstrumented++;
1214 }
1215
Alexey Samsonov59cca132012-12-25 12:04:36 +00001216 FunctionStackPoisoner FSP(F, *this);
1217 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001218
1219 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1220 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1221 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1222 Instruction *CI = NoReturnCalls[i];
1223 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001224 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +00001225 }
1226
Kostya Serebryany20985712013-06-26 09:18:17 +00001227 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1228 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1229
1230 if (ClKeepUninstrumented) {
1231 if (!res) {
1232 // No instrumentation is done, no need for the duplicate.
1233 if (UninstrumentedDuplicate)
1234 UninstrumentedDuplicate->eraseFromParent();
1235 } else {
1236 // The function was instrumented. We must have the duplicate.
1237 assert(UninstrumentedDuplicate);
1238 UninstrumentedDuplicate->setSection("NOASAN");
1239 assert(!F.hasSection());
1240 F.setSection("ASAN");
1241 }
1242 }
1243
1244 return res;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001245}
1246
1247static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1248 if (ShadowRedzoneSize == 1) return PoisonByte;
1249 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1250 if (ShadowRedzoneSize == 4)
1251 return (PoisonByte << 24) + (PoisonByte << 16) +
1252 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +00001253 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001254}
1255
1256static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1257 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001258 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001259 size_t ShadowGranularity,
1260 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001261 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001262 i+= ShadowGranularity, Shadow++) {
1263 if (i + ShadowGranularity <= Size) {
1264 *Shadow = 0; // fully addressable
1265 } else if (i >= Size) {
1266 *Shadow = Magic; // unaddressable
1267 } else {
1268 *Shadow = Size - i; // first Size-i bytes are addressable
1269 }
1270 }
1271}
1272
Alexey Samsonov59cca132012-12-25 12:04:36 +00001273// Workaround for bug 11395: we don't want to instrument stack in functions
1274// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1275// FIXME: remove once the bug 11395 is fixed.
1276bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1277 if (LongSize != 32) return false;
1278 CallInst *CI = dyn_cast<CallInst>(I);
1279 if (!CI || !CI->isInlineAsm()) return false;
1280 if (CI->getNumArgOperands() <= 5) return false;
1281 // We have inline assembly with quite a few arguments.
1282 return true;
1283}
1284
1285void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1286 IRBuilder<> IRB(*C);
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001287 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1288 std::string Suffix = itostr(i);
1289 AsanStackMallocFunc[i] = checkInterfaceFunction(
1290 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1291 IntptrTy, IntptrTy, NULL));
1292 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1293 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1294 IntptrTy, IntptrTy, NULL));
1295 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001296 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1297 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1298 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1299 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1300}
1301
1302void FunctionStackPoisoner::poisonRedZones(
Jakub Staszak4c710642013-08-09 20:53:48 +00001303 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB, Value *ShadowBase,
Alexey Samsonov59cca132012-12-25 12:04:36 +00001304 bool DoPoison) {
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001305 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001306 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1307 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1308 Type *RZPtrTy = PointerType::get(RZTy, 0);
1309
1310 Value *PoisonLeft = ConstantInt::get(RZTy,
1311 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1312 Value *PoisonMid = ConstantInt::get(RZTy,
1313 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1314 Value *PoisonRight = ConstantInt::get(RZTy,
1315 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1316
1317 // poison the first red zone.
1318 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1319
1320 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001321 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001322 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1323 AllocaInst *AI = AllocaVec[i];
1324 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1325 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001326 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001327 Value *Ptr = NULL;
1328
1329 Pos += AlignedSize;
1330
1331 assert(ShadowBase->getType() == IntptrTy);
1332 if (SizeInBytes < AlignedSize) {
1333 // Poison the partial redzone at right
1334 Ptr = IRB.CreateAdd(
1335 ShadowBase, ConstantInt::get(IntptrTy,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001336 (Pos >> Mapping.Scale) - ShadowRZSize));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001337 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001338 uint32_t Poison = 0;
1339 if (DoPoison) {
1340 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001341 RedzoneSize(),
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001342 1ULL << Mapping.Scale,
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001343 kAsanStackPartialRedzoneMagic);
Kostya Serebryany3e1d45b2013-06-03 14:46:56 +00001344 Poison =
1345 ASan.TD->isLittleEndian()
1346 ? support::endian::byte_swap<uint32_t, support::little>(Poison)
1347 : support::endian::byte_swap<uint32_t, support::big>(Poison);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001348 }
1349 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1350 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1351 }
1352
1353 // Poison the full redzone at right.
1354 Ptr = IRB.CreateAdd(ShadowBase,
Alexey Samsonov19cd7e92013-01-16 13:23:28 +00001355 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001356 bool LastAlloca = (i == AllocaVec.size() - 1);
1357 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001358 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1359
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001360 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001361 }
1362}
1363
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001364// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1365// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1366static int StackMallocSizeClass(uint64_t LocalStackSize) {
1367 assert(LocalStackSize <= kMaxStackMallocSize);
1368 uint64_t MaxSize = kMinStackMallocSize;
1369 for (int i = 0; ; i++, MaxSize *= 2)
1370 if (LocalStackSize <= MaxSize)
1371 return i;
1372 llvm_unreachable("impossible LocalStackSize");
1373}
1374
Kostya Serebryany671c3ba2013-09-17 12:14:50 +00001375// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1376// We can not use MemSet intrinsic because it may end up calling the actual
1377// memset. Size is a multiple of 8.
1378// Currently this generates 8-byte stores on x86_64; it may be better to
1379// generate wider stores.
1380void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1381 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1382 assert(!(Size % 8));
1383 assert(kAsanStackAfterReturnMagic == 0xf5);
1384 for (int i = 0; i < Size; i += 8) {
1385 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1386 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1387 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1388 }
1389}
1390
Alexey Samsonov59cca132012-12-25 12:04:36 +00001391void FunctionStackPoisoner::poisonStack() {
Alexey Samsonov59cca132012-12-25 12:04:36 +00001392 uint64_t LocalStackSize = TotalStackSize +
1393 (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001394
Alexey Samsonov59cca132012-12-25 12:04:36 +00001395 bool DoStackMalloc = ASan.CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001396 && LocalStackSize <= kMaxStackMallocSize;
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001397 int StackMallocIdx = -1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001398
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001399 assert(AllocaVec.size() > 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001400 Instruction *InsBefore = AllocaVec[0];
1401 IRBuilder<> IRB(InsBefore);
1402
1403
1404 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1405 AllocaInst *MyAlloca =
1406 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Alexey Samsonov59cca132012-12-25 12:04:36 +00001407 if (ClRealignStack && StackAlignment < RedzoneSize())
1408 StackAlignment = RedzoneSize();
1409 MyAlloca->setAlignment(StackAlignment);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001410 assert(MyAlloca->isStaticAlloca());
1411 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1412 Value *LocalStackBase = OrigStackBase;
1413
1414 if (DoStackMalloc) {
Kostya Serebryanyac04aba2013-09-18 14:07:14 +00001415 // LocalStackBase = OrigStackBase
1416 // if (__asan_option_detect_stack_use_after_return)
1417 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001418 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1419 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
Kostya Serebryanyac04aba2013-09-18 14:07:14 +00001420 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1421 kAsanOptionDetectUAR, IRB.getInt32Ty());
1422 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1423 Constant::getNullValue(IRB.getInt32Ty()));
1424 Instruction *Term =
1425 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1426 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1427 IRBuilder<> IRBIf(Term);
1428 LocalStackBase = IRBIf.CreateCall2(
1429 AsanStackMallocFunc[StackMallocIdx],
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001430 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
Kostya Serebryanyac04aba2013-09-18 14:07:14 +00001431 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1432 IRB.SetInsertPoint(InsBefore);
1433 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1434 Phi->addIncoming(OrigStackBase, CmpBlock);
1435 Phi->addIncoming(LocalStackBase, SetBlock);
1436 LocalStackBase = Phi;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001437 }
1438
Kostya Serebryany30160562013-03-22 10:37:20 +00001439 // This string will be parsed by the run-time (DescribeAddressIfStack).
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001440 SmallString<2048> StackDescriptionStorage;
1441 raw_svector_ostream StackDescription(StackDescriptionStorage);
Kostya Serebryany30160562013-03-22 10:37:20 +00001442 StackDescription << AllocaVec.size() << " ";
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001443
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001444 // Insert poison calls for lifetime intrinsics for alloca.
1445 bool HavePoisonedAllocas = false;
1446 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1447 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1448 IntrinsicInst *II = APC.InsBefore;
1449 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1450 assert(AI);
1451 IRBuilder<> IRB(II);
1452 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1453 HavePoisonedAllocas |= APC.DoPoison;
1454 }
1455
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001456 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001457 // Replace Alloca instructions with base+offset.
1458 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1459 AllocaInst *AI = AllocaVec[i];
1460 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1461 StringRef Name = AI->getName();
1462 StackDescription << Pos << " " << SizeInBytes << " "
1463 << Name.size() << " " << Name << " ";
1464 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001465 assert((AlignedSize % RedzoneSize()) == 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001466 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001467 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
Alexey Samsonovf985f442012-12-04 01:34:23 +00001468 AI->getType());
Alexey Samsonov1afbb512012-12-12 14:31:53 +00001469 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001470 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001471 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001472 }
1473 assert(Pos == LocalStackSize);
1474
Kostya Serebryany30160562013-03-22 10:37:20 +00001475 // The left-most redzone has enough space for at least 4 pointers.
1476 // Write the Magic value to redzone[0].
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001477 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1478 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1479 BasePlus0);
Kostya Serebryany30160562013-03-22 10:37:20 +00001480 // Write the frame description constant to redzone[1].
1481 Value *BasePlus1 = IRB.CreateIntToPtr(
1482 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1483 IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001484 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001485 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Alexey Samsonov59cca132012-12-25 12:04:36 +00001486 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1487 IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001488 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryany30160562013-03-22 10:37:20 +00001489 // Write the PC to redzone[2].
1490 Value *BasePlus2 = IRB.CreateIntToPtr(
1491 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1492 2 * ASan.LongSize/8)),
1493 IntptrPtrTy);
1494 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001495
1496 // Poison the stack redzones at the entry.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001497 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1498 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001499
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001500 // Unpoison the stack before all ret instructions.
1501 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1502 Instruction *Ret = RetVec[i];
1503 IRBuilder<> IRBRet(Ret);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001504 // Mark the current frame as retired.
1505 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1506 BasePlus0);
1507 // Unpoison the stack.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001508 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001509 if (DoStackMalloc) {
Kostya Serebryanyf3d4b352013-09-10 13:16:56 +00001510 assert(StackMallocIdx >= 0);
Alexey Samsonovf985f442012-12-04 01:34:23 +00001511 // In use-after-return mode, mark the whole stack frame unaddressable.
Kostya Serebryany671c3ba2013-09-17 12:14:50 +00001512 if (StackMallocIdx <= 4) {
1513 // For small sizes inline the whole thing:
1514 // if LocalStackBase != OrigStackBase:
1515 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1516 // **SavedFlagPtr(LocalStackBase) = 0
1517 // FIXME: if LocalStackBase != OrigStackBase don't call poisonRedZones.
1518 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1519 TerminatorInst *PoisonTerm =
1520 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1521 IRBuilder<> IRBPoison(PoisonTerm);
1522 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1523 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1524 ClassSize >> Mapping.Scale);
1525 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1526 LocalStackBase,
1527 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1528 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1529 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1530 IRBPoison.CreateStore(
1531 Constant::getNullValue(IRBPoison.getInt8Ty()),
1532 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1533 } else {
1534 // For larger frames call __asan_stack_free_*.
1535 IRBRet.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1536 ConstantInt::get(IntptrTy, LocalStackSize),
1537 OrigStackBase);
1538 }
Alexey Samsonovf985f442012-12-04 01:34:23 +00001539 } else if (HavePoisonedAllocas) {
1540 // If we poisoned some allocas in llvm.lifetime analysis,
1541 // unpoison whole stack frame now.
1542 assert(LocalStackBase == OrigStackBase);
1543 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001544 }
1545 }
1546
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001547 // We are done. Remove the old unused alloca instructions.
1548 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1549 AllocaVec[i]->eraseFromParent();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001550}
Alexey Samsonovf985f442012-12-04 01:34:23 +00001551
Alexey Samsonov59cca132012-12-25 12:04:36 +00001552void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak4c710642013-08-09 20:53:48 +00001553 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonovf985f442012-12-04 01:34:23 +00001554 // For now just insert the call to ASan runtime.
1555 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1556 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1557 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1558 : AsanUnpoisonStackMemoryFunc,
1559 AddrArg, SizeArg);
1560}
Alexey Samsonov59cca132012-12-25 12:04:36 +00001561
1562// Handling llvm.lifetime intrinsics for a given %alloca:
1563// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1564// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1565// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1566// could be poisoned by previous llvm.lifetime.end instruction, as the
1567// variable may go in and out of scope several times, e.g. in loops).
1568// (3) if we poisoned at least one %alloca in a function,
1569// unpoison the whole stack frame at function exit.
Alexey Samsonov59cca132012-12-25 12:04:36 +00001570
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001571AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1572 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1573 // We're intested only in allocas we can handle.
1574 return isInterestingAlloca(*AI) ? AI : 0;
1575 // See if we've already calculated (or started to calculate) alloca for a
1576 // given value.
1577 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1578 if (I != AllocaForValue.end())
1579 return I->second;
1580 // Store 0 while we're calculating alloca for value V to avoid
1581 // infinite recursion if the value references itself.
1582 AllocaForValue[V] = 0;
1583 AllocaInst *Res = 0;
1584 if (CastInst *CI = dyn_cast<CastInst>(V))
1585 Res = findAllocaForValue(CI->getOperand(0));
1586 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1587 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1588 Value *IncValue = PN->getIncomingValue(i);
1589 // Allow self-referencing phi-nodes.
1590 if (IncValue == PN) continue;
1591 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1592 // AI for incoming values should exist and should all be equal.
1593 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1594 return 0;
1595 Res = IncValueAI;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001596 }
Alexey Samsonov59cca132012-12-25 12:04:36 +00001597 }
Alexey Samsonov1c8b8252012-12-27 08:50:58 +00001598 if (Res != 0)
1599 AllocaForValue[V] = Res;
Alexey Samsonov59cca132012-12-25 12:04:36 +00001600 return Res;
1601}